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::os::windows::ffi::OsStringExt;

use windows::Win32::NetworkManagement::IpHelper::{
    FreeMibTable, GetIfTable2, MIB_IF_ROW2, MIB_IF_TABLE2,
};
use windows::Win32::NetworkManagement::Ndis::MediaConnectStateDisconnected;

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

fn interface_id(row: &MIB_IF_ROW2) -> Vec<u16> {
    let guid = &row.InterfaceGuid;
    let mut id = Vec::with_capacity(10);
    id.push(guid.data2);
    id.push(guid.data3);
    id.extend(guid.data4.iter().map(|&value| value as u16));
    id
}

fn interface_name(row: &MIB_IF_ROW2) -> OsString {
    let len = row.Alias.iter().position(|&value| value == 0).unwrap_or(0);
    OsString::from_wide(&row.Alias[..len])
}

fn link_speed(value: u64) -> Option<u64> {
    (value != 0).then_some(value)
}

fn snapshot(row: &MIB_IF_ROW2) -> NetworkSnapshot {
    NetworkSnapshot::new(
        row.InOctets,
        row.OutOctets,
        row.InUcastPkts.saturating_add(row.InNUcastPkts),
        row.OutUcastPkts.saturating_add(row.OutNUcastPkts),
        row.InErrors,
        row.OutErrors,
    )
}

pub(super) fn refresh_from_table(
    interfaces: &mut HashMap<OsString, NetworkData>,
    remove_not_listed_interfaces: bool,
) {
    let mut table: *mut MIB_IF_TABLE2 = std::ptr::null_mut();

    unsafe {
        if GetIfTable2(&mut table).is_err() {
            return;
        }

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

        // Software interfaces must be filtered out so that only hardware interfaces remain.
        let mut groups: HashMap<Vec<u16>, usize> = HashMap::new();
        let mut indexes = Vec::new();
        let rows = (*table).Table.as_ptr();
        for index in 0..(*table).NumEntries {
            let row = &*rows.offset(index as _);
            if (row.TransmitLinkSpeed == 0 && row.ReceiveLinkSpeed == 0)
                || row.MediaConnectState == MediaConnectStateDisconnected
                || row.PhysicalAddressLength == 0
            {
                continue;
            }
            let id = interface_id(row);
            let count = groups.entry(id.clone()).or_insert(0);
            *count += 1;
            if *count == 1 {
                indexes.push((index, id));
            }
        }

        for (index, id) in indexes {
            if groups.get(&id).is_some_and(|count| *count > 1) {
                continue;
            }
            let row = &*rows.offset(index as _);
            let snapshot = snapshot(row);
            let mtu = row.Mtu as u64;
            let transmit_link_speed = link_speed(row.TransmitLinkSpeed);
            let receive_link_speed = link_speed(row.ReceiveLinkSpeed);
            let operational_state = InterfaceOperationalState::from_enum(row.OperStatus);

            match interfaces.entry(interface_name(row)) {
                hash_map::Entry::Occupied(mut entry) => {
                    entry.get_mut().inner.update(
                        snapshot,
                        mtu,
                        transmit_link_speed,
                        receive_link_speed,
                        operational_state,
                    );
                }
                hash_map::Entry::Vacant(entry) => {
                    entry.insert(NetworkData {
                        inner: NetworkDataInner::new(
                            snapshot,
                            mtu,
                            transmit_link_speed,
                            receive_link_speed,
                            operational_state,
                        ),
                    });
                }
            }
        }
        FreeMibTable(table as _);
    }

    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;
        }
    }
}