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::{BufRead, BufReader};
use std::time::Instant;

use crate::sys::utils::to_u64;
use crate::{Cpu, CpuRefreshKind};

#[cfg(target_os = "android")]
use super::cpuinfo::build_cpus_from_cpuinfo;
use super::cpuinfo::get_vendor_id_and_brand;
use super::frequency::get_cpu_frequency;
use super::inner::CpuInner;
use super::values::CpuUsage;

macro_rules! to_str {
    ($e:expr) => {
        unsafe { std::str::from_utf8_unchecked($e) }
    };
}

pub(crate) struct CpusWrapper {
    pub(crate) global_cpu: CpuUsage,
    pub(crate) cpus: Vec<Cpu>,
    got_cpu_frequency: bool,
    /// Prevents an update when not enough time has passed since the last update.
    last_update: Option<Instant>,
}

impl CpusWrapper {
    pub(crate) fn new() -> Self {
        Self {
            global_cpu: CpuUsage::default(),
            cpus: Vec::with_capacity(4),
            got_cpu_frequency: false,
            last_update: None,
        }
    }

    pub(crate) fn refresh_if_needed(
        &mut self,
        only_update_global_cpu: bool,
        refresh_kind: CpuRefreshKind,
    ) {
        self.refresh(only_update_global_cpu, refresh_kind);
    }

    pub(crate) fn refresh(&mut self, only_update_global_cpu: bool, refresh_kind: CpuRefreshKind) {
        let need_cpu_usage_update = self
            .last_update
            .map(|last_update| last_update.elapsed() >= crate::MINIMUM_CPU_UPDATE_INTERVAL)
            .unwrap_or(true);

        let first = self.cpus.is_empty();
        let mut vendors_brands = if first {
            get_vendor_id_and_brand()
        } else {
            HashMap::new()
        };

        // If the last CPU usage update is too recent (less than `MINIMUM_CPU_UPDATE_INTERVAL`), CPU times are not updated.
        if need_cpu_usage_update {
            self.last_update = Some(Instant::now());
            let f = match File::open("/proc/stat") {
                Ok(f) => f,
                Err(_e) => {
                    #[cfg(not(target_os = "android"))]
                    sinf_debug!("failed to retrieve CPU information: {:?}", _e);
                    #[cfg(target_os = "android")]
                    {
                        sinf_debug!("failed to retrieve CPU usage information: {:?}", _e);
                        if first {
                            self.cpus =
                                build_cpus_from_cpuinfo(vendors_brands, refresh_kind.frequency());
                        }
                    }
                    return;
                }
            };
            let buf = BufReader::new(f);

            let mut i: usize = 0;
            let mut it = buf.split(b'\n');

            if first || refresh_kind.usage() {
                if let Some(Ok(line)) = it.next() {
                    if line.len() < 4 || &line[..4] != b"cpu " {
                        return;
                    }
                    let mut parts = line.split(|x| *x == b' ').filter(|s| !s.is_empty()).skip(1);
                    self.global_cpu.set(
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                        parts.next().map(to_u64).unwrap_or(0),
                    );
                }
                if first || !only_update_global_cpu {
                    while let Some(Ok(line)) = it.next() {
                        if line.len() < 3 || &line[..3] != b"cpu" {
                            break;
                        }

                        let mut parts = line.split(|x| *x == b' ').filter(|s| !s.is_empty());
                        if first {
                            let (vendor_id, brand) = match vendors_brands.remove(&i) {
                                Some((vendor_id, brand)) => (vendor_id, brand),
                                None => (String::new(), String::new()),
                            };
                            self.cpus.push(Cpu {
                                inner: CpuInner::new_with_values(
                                    to_str!(parts.next().unwrap_or(&[])),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    0,
                                    vendor_id,
                                    brand,
                                ),
                            });
                        } else {
                            parts.next(); // Skip the name.
                            if let Some(cpu) = self.cpus.get_mut(i) {
                                cpu.inner.set(
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                    parts.next().map(to_u64).unwrap_or(0),
                                );
                            } else {
                                // A new CPU was added and is ignored here.
                                sinf_debug!("ignoring new CPU added");
                            }
                        }

                        i += 1;
                    }
                }
                if i < self.cpus.len() {
                    sinf_debug!("{} CPU(s) seem to have been removed", self.cpus.len() - i);
                }
            }
        }

        if refresh_kind.frequency() {
            #[cfg(feature = "multithread")]
            use rayon::iter::{
                IndexedParallelIterator, IntoParallelRefMutIterator, ParallelIterator,
            };

            #[cfg(feature = "multithread")]
            // This function is deliberately generic so that it can be generalized.
            fn iter_mut<'a, T>(
                val: &'a mut T,
            ) -> <&'a mut T as rayon::iter::IntoParallelIterator>::Iter
            where
                &'a mut T: rayon::iter::IntoParallelIterator,
            {
                val.par_iter_mut()
            }

            #[cfg(not(feature = "multithread"))]
            fn iter_mut(val: &mut [Cpu]) -> std::slice::IterMut<'_, Cpu> {
                val.iter_mut()
            }

            // `get_cpu_frequency` is very slow, so better run it in parallel.
            iter_mut(&mut self.cpus)
                .enumerate()
                .for_each(|(pos, proc_)| proc_.inner.frequency = get_cpu_frequency(pos));

            self.got_cpu_frequency = true;
        }
    }

    pub(crate) fn get_global_raw_times(&self) -> (u64, u64) {
        self.global_cpu.raw_times()
    }

    pub(crate) fn len(&self) -> usize {
        self.cpus.len()
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.cpus.is_empty()
    }
}