sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use super::*;

/// Disk I/O statistics read from `/proc/diskstats`.
#[derive(Debug, PartialEq)]
pub(super) struct DiskStat {
    pub(super) sectors_read: u64,
    pub(super) sectors_written: u64,
}

impl DiskStat {
    /// Returns the name and the values of interest.
    fn new_from_line(line: &str) -> Option<(String, Self)> {
        let mut iter = line.split_whitespace();
        // 3rd field.
        let name = iter.nth(2).map(ToString::to_string)?;
        // 6th field.
        let sectors_read = iter.nth(2).and_then(|v| u64::from_str(v).ok()).unwrap_or(0);
        // 10th field.
        let sectors_written = iter.nth(3).and_then(|v| u64::from_str(v).ok()).unwrap_or(0);
        Some((
            name,
            Self {
                sectors_read,
                sectors_written,
            },
        ))
    }
}

pub(super) fn disk_stats(refresh_kind: &DiskRefreshKind) -> HashMap<String, DiskStat> {
    if refresh_kind.io_usage() {
        let path = "/proc/diskstats";
        match fs::read_to_string(path) {
            Ok(content) => disk_stats_inner(&content),
            Err(_error) => {
                sinf_debug!("failed to read {path:?}: {_error:?}");
                HashMap::new()
            }
        }
    } else {
        Default::default()
    }
}

// Split out so that it can be tested.
pub(super) fn disk_stats_inner(content: &str) -> HashMap<String, DiskStat> {
    let mut data = HashMap::new();

    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        if let Some((name, stats)) = DiskStat::new_from_line(line) {
            data.insert(name, stats);
        }
    }
    data
}