sinf 0.1.0

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

/// PCI (Peripheral Component Interconnect) is an architecture used to identify and manage hardware devices.
#[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct PCI {
    /// The PCI domain, also called a segment.
    pub domain: u32,
    /// The PCI bus.
    pub bus: u32,
    /// The PCI device.
    pub device: u32,
    /// The PCI function.
    pub function: u32,
}

impl fmt::Display for PCI {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let Self {
            domain,
            bus,
            device,
            function,
        } = self;
        write!(f, "{domain:04x}:{bus:02x}:{device:02x}.{function}")
    }
}

impl core::str::FromStr for PCI {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fn get_next_u32<'a>(
            iter: &mut impl Iterator<Item = &'a str>,
            missing_msg: &'static str,
            invalid_msg: &'static str,
        ) -> Result<u32, &'static str> {
            let Some(value) = iter.next() else {
                return Err(missing_msg);
            };
            u32::from_str_radix(value, 16).map_err(|_| invalid_msg)
        }

        let mut iter = s.split(':');
        let domain = get_next_u32(&mut iter, "missing domain", "invalid domain")?;
        let bus = get_next_u32(&mut iter, "missing bus", "invalid bus")?;
        let Some(last) = iter.next() else {
            return Err("missing device");
        };
        if iter.next().is_some() {
            return Err("unexpected `:` after bus");
        };
        let mut iter = last.split('.');
        let device = get_next_u32(&mut iter, "missing device", "invalid device")?;
        let function = get_next_u32(&mut iter, "missing function", "invalid function")?;
        if iter.next().is_some() {
            return Err("unexpected `:` after function");
        };

        // Skip range checks for the fake address used by M-series GPUs.
        if s != "ffffffff:ff:ff.255" {
            if bus > 0xff {
                return Err("invalid bus");
            }
            if device > 0x1f {
                return Err("invalid device");
            }
            if function > 0x07 {
                return Err("invalid function");
            }
        }

        Ok(Self {
            domain,
            bus,
            device,
            function,
        })
    }
}