sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::collections::{HashMap, hash_map};
use std::ffi::OsString;
use std::fs::File;
use std::io::Read;
use std::path::Path;

use crate::platform::network_data::{NetworkDataInner, NetworkSnapshot};
use crate::{InterfaceOperationalState, NetworkData};

fn read<P: AsRef<Path>>(parent: P, path: &str, data: &mut [u8]) -> u64 {
    if let Ok(mut file) = File::open(parent.as_ref().join(path))
        && let Ok(size) = file.read(data)
    {
        let mut i = 0;
        let mut value = 0;

        while i < size && i < data.len() && data[i].is_ascii_digit() {
            value *= 10;
            value += (data[i] - b'0') as u64;
            i += 1;
        }
        return value;
    }
    0
}

fn read_signed<P: AsRef<Path>>(parent: P, path: &str, data: &mut [u8]) -> i64 {
    if let Ok(mut file) = File::open(parent.as_ref().join(path))
        && let Ok(size) = file.read(data)
    {
        let mut i = 0;
        let mut value = 0;

        let negative = i < size && data[i] == b'-';
        if negative {
            i += 1;
        }

        while i < size && i < data.len() && data[i].is_ascii_digit() {
            value *= 10;
            value += (data[i] - b'0') as i64;
            i += 1;
        }
        return if negative { -value } else { value };
    }
    i64::MIN
}

// Clears and refills the buffer, so its length is the length of the value read.
fn read_str<'data, P: AsRef<Path>>(parent: P, path: &str, data: &'data mut Vec<u8>) -> &'data [u8] {
    data.clear();
    if let Ok(mut file) = File::open(parent.as_ref().join(path))
        && let Ok(size) = file.read_to_end(data)
    {
        &data[..size]
    } else {
        b""
    }
}

pub(super) fn refresh_networks_list_from_sysfs(
    interfaces: &mut HashMap<OsString, NetworkData>,
    remove_not_listed_interfaces: bool,
    sysfs_net: &Path,
) {
    if let Ok(dir) = std::fs::read_dir(sysfs_net) {
        // `ilog10` gives the number of digits minus one; the extra +1 is for the newline.
        let mut num_buf = [0u8; u64::MAX.ilog(10) as usize + 2];
        let mut str_buf = Vec::with_capacity(32);

        for stats in interfaces.values_mut() {
            stats.inner.updated = false;
        }

        for entry in dir.flatten() {
            let link_speed = match read_signed(entry.path(), "speed", &mut num_buf) {
                ..0 => None,
                speed => Some(speed as u64 * 1_000_000),
            };

            let parent = &entry.path().join("statistics");
            let entry_path = &entry.path();

            let snapshot = NetworkSnapshot::new(
                read(parent, "rx_bytes", &mut num_buf),
                read(parent, "tx_bytes", &mut num_buf),
                read(parent, "rx_packets", &mut num_buf),
                read(parent, "tx_packets", &mut num_buf),
                read(parent, "rx_errors", &mut num_buf),
                read(parent, "tx_errors", &mut num_buf),
            );
            let mtu = read(entry_path, "mtu", &mut num_buf);

            let operational_state = InterfaceOperationalState::from_data(
                read_str(entry_path, "operstate", &mut str_buf).trim_ascii(),
            );

            match interfaces.entry(entry.file_name()) {
                hash_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().inner.update(
                        snapshot,
                        mtu,
                        link_speed,
                        link_speed,
                        operational_state,
                    );
                }
                hash_map::Entry::Vacant(entry) => {
                    entry.insert(NetworkData {
                        inner: NetworkDataInner::new(
                            snapshot,
                            mtu,
                            link_speed,
                            link_speed,
                            operational_state,
                        ),
                    });
                }
            }
        }
    }
    // This is done here because the `refresh_networks_list_remove_interface` test verifies it.
    if remove_not_listed_interfaces {
        interfaces.retain(|_, interface| {
            if !interface.inner.updated {
                return false;
            }
            interface.inner.updated = false;
            true
        });
    } else {
        for interface in interfaces.values_mut() {
            interface.inner.updated = false;
        }
    }
}