sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::ffi::c_char;
use std::ptr::null_mut;

use crate::sys::{ffi, utils};

use super::values::{GetValues, same_name};

pub(super) unsafe fn refresh_disk_io<T: GetValues>(disks: &mut [T]) {
    const IO_SYSCTL_SIZE: usize = std::mem::size_of::<ffi::io_sysctl>();
    let mib = &[ffi::CTL_HW, ffi::HW_IOSTATS, IO_SYSCTL_SIZE as libc::c_int];
    let mut size: libc::size_t = 0;

    unsafe {
        if !utils::get_sysctl_raw(mib, null_mut(), &mut size) {
            sinf_debug!("failed to get iostats info");
            return;
        }
        let mut nb_drives = size as usize / IO_SYSCTL_SIZE;
        if nb_drives < 1 {
            sinf_debug!("no drive");
            return;
        }
        let mut drives: Vec<ffi::io_sysctl> = Vec::with_capacity(nb_drives);
        if !utils::get_sysctl_raw(mib, drives.as_mut_ptr() as *mut _, &mut size) {
            sinf_debug!("failed to get iostats drives");
            return;
        }
        nb_drives = size as usize / IO_SYSCTL_SIZE;
        drives.set_len(nb_drives);

        for drive in drives {
            if let Some(disk) = disks
                .iter_mut()
                .find(|disk| same_name(disk.dev_id(), &drive.name))
            {
                disk.update_old();
                *disk.get_read() = drive.rbytes;
                *disk.get_written() = drive.wbytes;
            }
        }
    }
}

pub(super) fn get_dev_id(path: &[c_char]) -> Vec<c_char> {
    let mut start = None;
    let mut end = None;
    for (pos, c) in path.iter().enumerate().rev() {
        if *c == b'/' as c_char {
            start = Some(pos + 1);
            break;
        } else if end.is_none() && *c != 0 {
            end = Some(pos);
        }
    }
    let start = start.unwrap_or(0);
    match end {
        Some(end) => path[start..=end].to_vec(),
        None => path[start..].to_vec(),
    }
}