1 //! Get system identification
2 use std::mem;
3 use libc::{self, c_char};
4 use std::ffi::CStr;
5 use std::str::from_utf8_unchecked;
6 
7 /// Describes the running system.  Return type of [`uname`].
8 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
9 #[repr(transparent)]
10 pub struct UtsName(libc::utsname);
11 
12 impl UtsName {
13     /// Name of the operating system implementation
sysname(&self) -> &str14     pub fn sysname(&self) -> &str {
15         to_str(&(&self.0.sysname as *const c_char ) as *const *const c_char)
16     }
17 
18     /// Network name of this machine.
nodename(&self) -> &str19     pub fn nodename(&self) -> &str {
20         to_str(&(&self.0.nodename as *const c_char ) as *const *const c_char)
21     }
22 
23     /// Release level of the operating system.
release(&self) -> &str24     pub fn release(&self) -> &str {
25         to_str(&(&self.0.release as *const c_char ) as *const *const c_char)
26     }
27 
28     /// Version level of the operating system.
version(&self) -> &str29     pub fn version(&self) -> &str {
30         to_str(&(&self.0.version as *const c_char ) as *const *const c_char)
31     }
32 
33     /// Machine hardware platform.
machine(&self) -> &str34     pub fn machine(&self) -> &str {
35         to_str(&(&self.0.machine as *const c_char ) as *const *const c_char)
36     }
37 }
38 
39 /// Get system identification
uname() -> UtsName40 pub fn uname() -> UtsName {
41     unsafe {
42         let mut ret = mem::MaybeUninit::uninit();
43         libc::uname(ret.as_mut_ptr());
44         UtsName(ret.assume_init())
45     }
46 }
47 
48 #[inline]
to_str<'a>(s: *const *const c_char) -> &'a str49 fn to_str<'a>(s: *const *const c_char) -> &'a str {
50     unsafe {
51         let res = CStr::from_ptr(*s).to_bytes();
52         from_utf8_unchecked(res)
53     }
54 }
55 
56 #[cfg(test)]
57 mod test {
58     #[cfg(target_os = "linux")]
59     #[test]
test_uname_linux()60     pub fn test_uname_linux() {
61         assert_eq!(super::uname().sysname(), "Linux");
62     }
63 
64     #[cfg(any(target_os = "macos", target_os = "ios"))]
65     #[test]
test_uname_darwin()66     pub fn test_uname_darwin() {
67         assert_eq!(super::uname().sysname(), "Darwin");
68     }
69 
70     #[cfg(target_os = "freebsd")]
71     #[test]
test_uname_freebsd()72     pub fn test_uname_freebsd() {
73         assert_eq!(super::uname().sysname(), "FreeBSD");
74     }
75 }
76