sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use libc::{c_char, c_void};

pub(crate) unsafe fn get_sys_value(mut len: usize, value: *mut c_void, mib: &mut [i32]) -> bool {
    unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            mib.len() as _,
            value,
            &mut len as *mut _,
            std::ptr::null_mut(),
            0,
        ) == 0
    }
}

pub(crate) unsafe fn get_sys_value_by_name(
    name: &[u8],
    len: &mut usize,
    value: *mut c_void,
) -> bool {
    unsafe {
        libc::sysctlbyname(
            name.as_ptr() as *const _,
            value,
            len,
            std::ptr::null_mut(),
            0,
        ) == 0
    }
}

pub(crate) fn get_sysctl_str(name: &[u8]) -> Option<String> {
    let mut len = 0;

    unsafe {
        libc::sysctlbyname(
            name.as_ptr() as *const c_char,
            std::ptr::null_mut(),
            &mut len,
            std::ptr::null_mut(),
            0,
        );
        if len == 0 {
            return None;
        }

        let mut buf = Vec::with_capacity(len);
        libc::sysctlbyname(
            name.as_ptr() as *const c_char,
            buf.as_mut_ptr() as _,
            &mut len,
            std::ptr::null_mut(),
            0,
        );
        if len == 0 {
            return None;
        }
        buf.set_len(len);
        while buf.last() == Some(&b'\0') {
            buf.pop();
        }
        String::from_utf8(buf).ok()
    }
}

pub(crate) fn get_sysctl_u64(name: &[u8]) -> Option<u64> {
    let mut value = 0u64;
    let mut len = std::mem::size_of::<u64>();
    let ok =
        unsafe { get_sys_value_by_name(name, &mut len, &mut value as *mut u64 as *mut c_void) };
    ok.then_some(value)
}