Coverage Report

Created: 2024-05-20 06:38

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