nix/sys/
utsname.rs

1//! Get system identification
2use std::mem;
3use libc::{self, c_char};
4use std::ffi::CStr;
5use 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)]
10pub struct UtsName(libc::utsname);
11
12impl UtsName {
13    /// Name of the operating system implementation
14    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.
19    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.
24    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.
29    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.
34    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
40pub 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]
49fn 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)]
57mod test {
58    #[cfg(target_os = "linux")]
59    #[test]
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]
66    pub fn test_uname_darwin() {
67        assert_eq!(super::uname().sysname(), "Darwin");
68    }
69
70    #[cfg(target_os = "freebsd")]
71    #[test]
72    pub fn test_uname_freebsd() {
73        assert_eq!(super::uname().sysname(), "FreeBSD");
74    }
75}