sinf 0.1.0

Library for obtaining in-depth system information at both the hardware and software levels
Documentation
use std::collections::HashMap;
use std::fs::File;
use std::io::Read;

use super::arm::{get_arm_implementer, get_arm_part};
#[cfg(target_os = "android")]
use super::frequency::get_cpu_frequency;
#[cfg(target_os = "android")]
use super::inner::CpuInner;
#[cfg(target_os = "android")]
use crate::Cpu;

/// Builds a CPU list from `/proc/cpuinfo` when `/proc/stat` is unreadable (blocked by SELinux for apps since Android 8).
#[cfg(target_os = "android")]
pub(super) fn build_cpus_from_cpuinfo(
    vendors_brands: HashMap<usize, (String, String)>,
    refresh_frequency: bool,
) -> Vec<Cpu> {
    let mut cpus = vendors_brands.into_iter().collect::<Vec<_>>();
    cpus.sort_unstable_by_key(|(index, _)| *index);

    cpus.into_iter()
        .map(|(index, (vendor_id, brand))| {
            let name = format!("cpu{index}");
            Cpu {
                inner: CpuInner::new_with_values(
                    &name,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    if refresh_frequency {
                        get_cpu_frequency(index)
                    } else {
                        0
                    },
                    vendor_id,
                    brand,
                ),
            }
        })
        .collect()
}

/// Returns the brand/vendor string for the first CPU (which should be the same for all CPUs).
pub(crate) fn get_vendor_id_and_brand() -> HashMap<usize, (String, String)> {
    let mut s = String::new();
    if File::open("/proc/cpuinfo")
        .and_then(|mut f| f.read_to_string(&mut s))
        .is_err()
    {
        return HashMap::new();
    }
    get_vendor_id_and_brand_inner(&s)
}

#[inline]
pub(super) fn cpuinfo_is_key(line: &str, key: &[u8]) -> bool {
    let line = line.as_bytes();
    line.len() > key.len() && line[..key.len()].eq_ignore_ascii_case(key)
}

pub(super) fn get_vendor_id_and_brand_inner(data: &str) -> HashMap<usize, (String, String)> {
    fn get_value(s: &str) -> String {
        s.split(':')
            .next_back()
            .map(|x| x.trim().to_owned())
            .unwrap_or_default()
    }

    fn get_hex_value(s: &str) -> u32 {
        s.split(':')
            .next_back()
            .map(|x| x.trim())
            .filter(|x| x.starts_with("0x"))
            .and_then(|x| u32::from_str_radix(&x[2..], 16).ok())
            .unwrap_or_default()
    }

    #[inline]
    fn is_new_processor(line: &str) -> bool {
        line.split(':')
            .next()
            .is_some_and(|line| line.trim() == "processor")
    }

    #[derive(Default)]
    struct CpuInfo {
        index: usize,
        vendor_id: Option<String>,
        brand: Option<String>,
        implementer: Option<u32>,
        part: Option<u32>,
    }

    impl CpuInfo {
        fn has_all_info(&self) -> bool {
            (self.brand.is_some() && self.vendor_id.is_some())
                || (self.implementer.is_some() && self.part.is_some())
        }

        fn convert(mut self) -> (usize, String, String) {
            let (vendor_id, brand) = if let (Some(implementer), Some(part)) =
                (self.implementer.take(), self.part.take())
            {
                let vendor_id = get_arm_implementer(implementer).map(String::from);
                // An ARM CPU may also expose "model name", so when the brand cannot be retrieved from "CPU part", the value of "model name" is used instead.
                let brand = get_arm_part(implementer, part)
                    .map(String::from)
                    .or_else(|| self.brand.take());
                (vendor_id, brand)
            } else {
                (self.vendor_id.take(), self.brand.take())
            };
            (
                self.index,
                vendor_id.unwrap_or_default(),
                brand.unwrap_or_default(),
            )
        }
    }

    let mut cpus: HashMap<usize, (String, String)> = HashMap::new();
    let mut lines = data.split('\n').peekable();
    while let Some(line) = lines.next() {
        if is_new_processor(line) {
            let index = match line
                .split(':')
                .nth(1)
                .and_then(|i| i.trim().parse::<usize>().ok())
            {
                Some(index) => index,
                None => {
                    sinf_debug!("Couldn't get processor ID from {line:?}, ignoring this core");
                    continue;
                }
            };

            let mut info = CpuInfo {
                index,
                ..Default::default()
            };

            #[allow(clippy::while_let_on_iterator)]
            while let Some(line) = lines.peek() {
                if cpuinfo_is_key(line, b"vendor_id\t") {
                    info.vendor_id = Some(get_value(line));
                } else if cpuinfo_is_key(line, b"model name\t") {
                    info.brand = Some(get_value(line));
                } else if cpuinfo_is_key(line, b"CPU implementer\t") {
                    info.implementer = Some(get_hex_value(line));
                } else if cpuinfo_is_key(line, b"CPU part\t") {
                    info.part = Some(get_hex_value(line));
                } else if info.has_all_info() || is_new_processor(line) {
                    break;
                }
                lines.next();
            }
            let (index, vendor_id, brand) = info.convert();
            cpus.insert(index, (vendor_id, brand));
        }
    }
    cpus
}