use crate::cpu::CpuStats;
use std::{
fs::File,
io::{prelude::*, BufReader, Error, ErrorKind},
};
pub fn get_cpustats() -> Result<CpuStats, Error> {
let file = File::open("/proc/stat")?;
let mut file = BufReader::with_capacity(1024, file);
let mut matched_lines = 0u8;
let mut cpuctx = CpuStats::default();
let mut line = String::with_capacity(128);
while file.read_line(&mut line)? != 0 {
let first_bytes = &line.as_bytes()[..4];
match first_bytes {
b"intr" | b"ctxt" | b"soft" | b"proc" => {}
_ => {
line.clear();
continue;
}
}
let mut parts = line.splitn(3, ' ');
let field = match parts.next() {
Some("intr") => &mut cpuctx.interrupts,
Some("ctxt") => &mut cpuctx.ctx_switches,
Some("softirq") => &mut cpuctx.soft_interrupts,
Some("processes") => &mut cpuctx.processes,
Some("procs_running") => &mut cpuctx.procs_running,
Some("procs_blocked") => &mut cpuctx.procs_blocked,
_ => {
line.clear();
continue;
}
};
match parts.next() {
Some(value) => {
*field = {
let rval = value.trim().parse::<u64>().unwrap();
matched_lines += 1;
rval
}
}
None => {
line.clear();
continue;
}
}
if matched_lines == 6 {
return Ok(cpuctx);
}
line.clear();
}
Err(Error::new(
ErrorKind::Other,
"Couldn't find all the informations for CpuStats",
))
}