sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::fs::{read, read_to_string};

const BOARD: &str = "/proc/device-tree/board";
const COMPATIBLE: &str = "/proc/device-tree/compatible";

pub(super) fn name() -> Option<String> {
    read_to_string(BOARD)
        .ok()
        .map(|value| value.trim().to_owned())
        .or_else(|| compatible().map(|(_, name)| name))
}

pub(super) fn vendor() -> Option<String> {
    compatible().map(|(vendor, _)| vendor)
}

fn compatible() -> Option<(String, String)> {
    parse_compatible(&read(COMPATIBLE).ok()?)
}

fn parse_compatible(data: &[u8]) -> Option<(String, String)> {
    let first = data.split(|&byte| byte == 0).next()?;
    let (vendor, name) = std::str::from_utf8(first).ok()?.split_once(',')?;
    Some((vendor.to_owned(), name.to_owned()))
}

#[cfg(test)]
mod tests {
    use super::parse_compatible;

    #[test]
    fn parses_first_compatible_entry() {
        let data = b"vendor,board\0other,entry\0";
        assert_eq!(
            parse_compatible(data),
            Some(("vendor".to_owned(), "board".to_owned()))
        );
    }

    #[test]
    fn ignores_incomplete_entries() {
        assert_eq!(parse_compatible(b"vendor\0"), None);
        assert_eq!(parse_compatible(b""), None);
    }
}