nix/sys/
utsname.rs

1//! Get system identification
2use std::mem;
3use std::os::unix::ffi::OsStrExt;
4use std::ffi::OsStr;
5use libc::c_char;
6use crate::{Errno, Result};
7
8/// Describes the running system.  Return type of [`uname`].
9#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
10#[repr(transparent)]
11pub struct UtsName(libc::utsname);
12
13impl UtsName {
14    /// Name of the operating system implementation.
15    pub fn sysname(&self) -> &OsStr {
16        cast_and_trim(&self.0.sysname)
17    }
18
19    /// Network name of this machine.
20    pub fn nodename(&self) -> &OsStr {
21        cast_and_trim(&self.0.nodename)
22    }
23
24    /// Release level of the operating system.
25    pub fn release(&self) -> &OsStr {
26        cast_and_trim(&self.0.release)
27    }
28
29    /// Version level of the operating system.
30    pub fn version(&self) -> &OsStr {
31        cast_and_trim(&self.0.version)
32    }
33
34    /// Machine hardware platform.
35    pub fn machine(&self) -> &OsStr {
36        cast_and_trim(&self.0.machine)
37    }
38}
39
40/// Get system identification
41pub fn uname() -> Result<UtsName> {
42    unsafe {
43        let mut ret = mem::MaybeUninit::zeroed();
44        Errno::result(libc::uname(ret.as_mut_ptr()))?;
45        Ok(UtsName(ret.assume_init()))
46    }
47}
48
49fn cast_and_trim(slice: &[c_char]) -> &OsStr {
50    let length = slice.iter().position(|&byte| byte == 0).unwrap_or(slice.len());
51    let bytes = unsafe {
52        std::slice::from_raw_parts(slice.as_ptr().cast(), length)
53    };
54
55    OsStr::from_bytes(bytes)
56}
57
58#[cfg(test)]
59mod test {
60    #[cfg(target_os = "linux")]
61    #[test]
62    pub fn test_uname_linux() {
63        assert_eq!(super::uname().unwrap().sysname(), "Linux");
64    }
65
66    #[cfg(any(target_os = "macos", target_os = "ios"))]
67    #[test]
68    pub fn test_uname_darwin() {
69        assert_eq!(super::uname().unwrap().sysname(), "Darwin");
70    }
71
72    #[cfg(target_os = "freebsd")]
73    #[test]
74    pub fn test_uname_freebsd() {
75        assert_eq!(super::uname().unwrap().sysname(), "FreeBSD");
76    }
77}