Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use OsString for System #1230

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 20 additions & 5 deletions examples/simple.rs
Expand Up @@ -440,11 +440,26 @@ fn interpret_input(
System OS version: {}\n\
System OS (long) version: {}\n\
System host name: {}",
System::name().unwrap_or_else(|| "<unknown>".to_owned()),
System::kernel_version().unwrap_or_else(|| "<unknown>".to_owned()),
System::os_version().unwrap_or_else(|| "<unknown>".to_owned()),
System::long_os_version().unwrap_or_else(|| "<unknown>".to_owned()),
System::host_name().unwrap_or_else(|| "<unknown>".to_owned()),
System::name()
.unwrap_or_else(|| "<unknown>".into())
.as_encoded_bytes()
.as_bstr(),
System::kernel_version()
.unwrap_or_else(|| "<unknown>".into())
.as_encoded_bytes()
.as_bstr(),
System::os_version()
.unwrap_or_else(|| "<unknown>".into())
.as_encoded_bytes()
.as_bstr(),
System::long_os_version()
.unwrap_or_else(|| "<unknown>".into())
.as_encoded_bytes()
.as_bstr(),
System::host_name()
.unwrap_or_else(|| "<unknown>".into())
.as_encoded_bytes()
.as_bstr(),
);
}
e => {
Expand Down
27 changes: 18 additions & 9 deletions src/c_interface.rs
Expand Up @@ -586,18 +586,21 @@ pub extern "C" fn sysinfo_cpu_frequency(system: CSystem) -> u64 {
/// Equivalent of [`System::name()`][crate::System#method.name].
#[no_mangle]
pub extern "C" fn sysinfo_system_name() -> RString {
let c_string = if let Some(c) = System::name().and_then(|p| CString::new(p).ok()) {
c.into_raw() as _
} else {
std::ptr::null()
};
let c_string =
if let Some(c) = System::name().and_then(|p| CString::new(p.as_encoded_bytes()).ok()) {
c.into_raw() as _
} else {
std::ptr::null()
};
c_string
}

/// Equivalent of [`System::version()`][crate::System#method.version].
#[no_mangle]
pub extern "C" fn sysinfo_system_version() -> RString {
let c_string = if let Some(c) = System::os_version().and_then(|c| CString::new(c).ok()) {
let c_string = if let Some(c) =
System::os_version().and_then(|c| CString::new(c.as_encoded_bytes()).ok())
{
c.into_raw() as _
} else {
std::ptr::null()
Expand All @@ -608,7 +611,9 @@ pub extern "C" fn sysinfo_system_version() -> RString {
/// Equivalent of [`System::kernel_version()`][crate::System#method.kernel_version].
#[no_mangle]
pub extern "C" fn sysinfo_system_kernel_version() -> RString {
let c_string = if let Some(c) = System::kernel_version().and_then(|c| CString::new(c).ok()) {
let c_string = if let Some(c) =
System::kernel_version().and_then(|c| CString::new(c.as_encoded_bytes()).ok())
{
c.into_raw() as _
} else {
std::ptr::null()
Expand All @@ -620,7 +625,9 @@ pub extern "C" fn sysinfo_system_kernel_version() -> RString {
/// Equivalent of [`System::host_name()`][crate::System#method.host_name].
#[no_mangle]
pub extern "C" fn sysinfo_system_host_name() -> RString {
let c_string = if let Some(c) = System::host_name().and_then(|c| CString::new(c).ok()) {
let c_string = if let Some(c) =
System::host_name().and_then(|c| CString::new(c.as_encoded_bytes()).ok())
{
c.into_raw() as _
} else {
std::ptr::null()
Expand All @@ -631,7 +638,9 @@ pub extern "C" fn sysinfo_system_host_name() -> RString {
/// Equivalent of [`System::long_os_version()`][crate::System#method.long_os_version].
#[no_mangle]
pub extern "C" fn sysinfo_system_long_version() -> RString {
let c_string = if let Some(c) = System::long_os_version().and_then(|c| CString::new(c).ok()) {
let c_string = if let Some(c) =
System::long_os_version().and_then(|c| CString::new(c.as_encoded_bytes()).ok())
{
c.into_raw() as _
} else {
std::ptr::null()
Expand Down
14 changes: 7 additions & 7 deletions src/common.rs
Expand Up @@ -728,7 +728,7 @@ impl System {
///
/// println!("OS: {:?}", System::name());
/// ```
pub fn name() -> Option<String> {
pub fn name() -> Option<OsString> {
SystemInner::name()
}

Expand All @@ -741,7 +741,7 @@ impl System {
///
/// println!("kernel version: {:?}", System::kernel_version());
/// ```
pub fn kernel_version() -> Option<String> {
pub fn kernel_version() -> Option<OsString> {
SystemInner::kernel_version()
}

Expand All @@ -755,7 +755,7 @@ impl System {
///
/// println!("OS version: {:?}", System::os_version());
/// ```
pub fn os_version() -> Option<String> {
pub fn os_version() -> Option<OsString> {
SystemInner::os_version()
}

Expand All @@ -768,7 +768,7 @@ impl System {
///
/// println!("Long OS Version: {:?}", System::long_os_version());
/// ```
pub fn long_os_version() -> Option<String> {
pub fn long_os_version() -> Option<OsString> {
SystemInner::long_os_version()
}

Expand All @@ -786,7 +786,7 @@ impl System {
///
/// println!("Distribution ID: {:?}", System::distribution_id());
/// ```
pub fn distribution_id() -> String {
pub fn distribution_id() -> OsString {
SystemInner::distribution_id()
}

Expand All @@ -799,7 +799,7 @@ impl System {
///
/// println!("Hostname: {:?}", System::host_name());
/// ```
pub fn host_name() -> Option<String> {
pub fn host_name() -> Option<OsString> {
SystemInner::host_name()
}

Expand All @@ -812,7 +812,7 @@ impl System {
///
/// println!("CPU Archicture: {:?}", System::cpu_arch());
/// ```
pub fn cpu_arch() -> Option<String> {
pub fn cpu_arch() -> Option<OsString> {
SystemInner::cpu_arch()
}
}
Expand Down
89 changes: 41 additions & 48 deletions src/unix/apple/system.rs
Expand Up @@ -10,8 +10,9 @@ use crate::{Cpu, CpuRefreshKind, LoadAvg, MemoryRefreshKind, Pid, Process, Proce
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use std::cell::UnsafeCell;
use std::collections::HashMap;
use std::ffi::CStr;
use std::ffi::{CStr, OsStr, OsString};
use std::mem;
use std::os::unix::ffi::{OsStrExt, OsStringExt};
#[cfg(all(target_os = "macos", not(feature = "apple-sandbox")))]
use std::time::SystemTime;

Expand Down Expand Up @@ -352,62 +353,56 @@ impl SystemInner {
boot_time()
}

pub(crate) fn name() -> Option<String> {
pub(crate) fn name() -> Option<OsString> {
get_system_info(libc::KERN_OSTYPE, Some("Darwin"))
}

pub(crate) fn long_os_version() -> Option<String> {
pub(crate) fn long_os_version() -> Option<OsString> {
#[cfg(target_os = "macos")]
let friendly_name = match Self::os_version().unwrap_or_default() {
f_n if f_n.starts_with("14.0") => "Sonoma",
f_n if f_n.starts_with("10.16")
| f_n.starts_with("11.0")
| f_n.starts_with("11.1")
| f_n.starts_with("11.2") =>
let friendly_name = match Self::os_version().unwrap_or_default().as_bytes() {
f_n if f_n.starts_with(b"14.0") => "Sonoma",
f_n if f_n.starts_with(b"10.16")
| f_n.starts_with(b"11.0")
| f_n.starts_with(b"11.1")
| f_n.starts_with(b"11.2") =>
{
"Big Sur"
}
f_n if f_n.starts_with("10.15") => "Catalina",
f_n if f_n.starts_with("10.14") => "Mojave",
f_n if f_n.starts_with("10.13") => "High Sierra",
f_n if f_n.starts_with("10.12") => "Sierra",
f_n if f_n.starts_with("10.11") => "El Capitan",
f_n if f_n.starts_with("10.10") => "Yosemite",
f_n if f_n.starts_with("10.9") => "Mavericks",
f_n if f_n.starts_with("10.8") => "Mountain Lion",
f_n if f_n.starts_with("10.7") => "Lion",
f_n if f_n.starts_with("10.6") => "Snow Leopard",
f_n if f_n.starts_with("10.5") => "Leopard",
f_n if f_n.starts_with("10.4") => "Tiger",
f_n if f_n.starts_with("10.3") => "Panther",
f_n if f_n.starts_with("10.2") => "Jaguar",
f_n if f_n.starts_with("10.1") => "Puma",
f_n if f_n.starts_with("10.0") => "Cheetah",
f_n if f_n.starts_with(b"10.15") => "Catalina",
f_n if f_n.starts_with(b"10.14") => "Mojave",
f_n if f_n.starts_with(b"10.13") => "High Sierra",
f_n if f_n.starts_with(b"10.12") => "Sierra",
_ => "",
};

#[cfg(target_os = "macos")]
let long_name = Some(format!(
"MacOS {} {}",
Self::os_version().unwrap_or_default(),
friendly_name
));
let long_name = {
let mut buf = b"macOS ".to_vec();
buf.extend(Self::os_version().unwrap_or_default().as_bytes());
buf.push(b' ');
buf.extend(friendly_name.as_bytes());
Some(OsString::from_vec(buf))
};

#[cfg(target_os = "ios")]
let long_name = Some(format!("iOS {}", Self::os_version().unwrap_or_default()));
let long_name = {
let mut buf = b"iOS ".to_vec();
buf.extend(Self::os_version().unwrap_or_default().as_bytes());
Some(OsString::from_vec(buf))
};

long_name
}

pub(crate) fn host_name() -> Option<String> {
pub(crate) fn host_name() -> Option<OsString> {
get_system_info(libc::KERN_HOSTNAME, None)
}

pub(crate) fn kernel_version() -> Option<String> {
pub(crate) fn kernel_version() -> Option<OsString> {
get_system_info(libc::KERN_OSRELEASE, None)
}

pub(crate) fn os_version() -> Option<String> {
pub(crate) fn os_version() -> Option<OsString> {
unsafe {
// get the size for the buffer first
let mut size = 0;
Expand All @@ -427,7 +422,7 @@ impl SystemInner {
buf.resize(pos, 0);
}

String::from_utf8(buf).ok()
Some(OsString::from_vec(buf))
} else {
// getting the system value failed
None
Expand All @@ -439,11 +434,11 @@ impl SystemInner {
}
}

pub(crate) fn distribution_id() -> String {
std::env::consts::OS.to_owned()
pub(crate) fn distribution_id() -> OsString {
std::env::consts::OS.into()
}

pub(crate) fn cpu_arch() -> Option<String> {
pub(crate) fn cpu_arch() -> Option<OsString> {
let mut arch_str: [u8; 32] = [0; 32];
let mut mib = [libc::CTL_HW as _, libc::HW_MACHINE as _];

Expand All @@ -453,20 +448,18 @@ impl SystemInner {
arch_str.as_mut_ptr() as *mut _,
&mut mib,
) {
CStr::from_bytes_until_nul(&arch_str)
.ok()
.and_then(|res| match res.to_str() {
Ok(arch) => Some(arch.to_string()),
Err(_) => None,
})
Some(
OsStr::from_bytes(CStr::from_bytes_until_nul(&arch_str).ok()?.to_bytes())
.to_os_string(),
)
} else {
None
}
}
}
}

fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> {
fn get_system_info(value: c_int, default: Option<&str>) -> Option<OsString> {
let mut mib: [c_int; 2] = [libc::CTL_KERN, value];
let mut size = 0;

Expand All @@ -483,7 +476,7 @@ fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> {

// exit early if we did not update the size
if size == 0 {
default.map(|s| s.to_owned())
default.map(|s| s.into())
} else {
// set the buffer to the correct size
let mut buf = vec![0_u8; size as _];
Expand All @@ -498,14 +491,14 @@ fn get_system_info(value: c_int, default: Option<&str>) -> Option<String> {
) == -1
{
// If command fails return default
default.map(|s| s.to_owned())
default.map(|s| s.into())
} else {
if let Some(pos) = buf.iter().position(|x| *x == 0) {
// Shrink buffer to terminate the null bytes
buf.resize(pos, 0);
}

String::from_utf8(buf).ok()
Some(OsString::from_vec(buf))
}
}
}
Expand Down