]> piware.de Git - learn-rust.git/blob - call-c-from-rust/src/main.rs
Implement the rest of c-mounts.c in Rust
[learn-rust.git] / call-c-from-rust / src / main.rs
1 mod libmount;
2
3 use std::ffi::CStr;
4 use std::ptr;
5 use std::process;
6
7 extern crate errno;
8
9 fn check_call(error: i32, msg: &str) {
10     if error < 0 {
11         errno::set_errno(errno::Errno(-error));
12         eprintln!("ERROR: {}: {}", msg, errno::errno());
13         process::exit(1);
14     }
15 }
16
17 fn main() {
18     let fstab_path_cstr: &CStr = unsafe { CStr::from_ptr (libmount::mnt_get_fstab_path()) };
19     println!("fstab path C-String: {:?}", fstab_path_cstr);
20     let fstab_path = fstab_path_cstr.to_str().unwrap(); // may cause UTF-8 decoding error
21     println!("fstab path str: {}", fstab_path);
22
23     let mut version = ptr::null();
24     check_call(unsafe { libmount::mnt_get_library_version(ptr::addr_of_mut!(version)) },
25                "Failed to get lib version");
26     println!("libmount version: {:?}", unsafe { CStr::from_ptr(version) });
27
28     let table = unsafe { libmount::mnt_new_table() };
29     check_call(unsafe {libmount::mnt_table_parse_mtab(table, ptr::null()) },
30                "Failed to parse mtab");
31     let mut fs = ptr::null_mut();
32     check_call(unsafe { libmount::mnt_table_first_fs(table, &mut fs) },
33                "Failed to find first fs");
34
35     println!("first fs type: {:?} source: {:?} target: {:?}",
36              unsafe { CStr::from_ptr (libmount::mnt_fs_get_fstype(fs)) },
37              unsafe { CStr::from_ptr (libmount::mnt_fs_get_source(fs)) },
38              unsafe { CStr::from_ptr (libmount::mnt_fs_get_target(fs)) });
39 }