1use std::collections::HashMap;
2use std::fs;
3
4#[derive(Debug, Default)]
5pub struct CpuInfo {
6 pub cache_size: String,
7 pub cores: usize,
8 pub cpu_speed: Vec<(usize, f64)>,
10 pub model_name: String,
11 pub vendor_id: String,
12 pub is_fpu: bool,
13 pub cpuid_level: usize,
14}
15
16impl CpuInfo {
17 pub fn new() -> Self {
18 let mut cpu_info = CpuInfo::default();
19 cpu_info.fetch();
20 cpu_info
21 }
22
23 fn fetch(&mut self) {
24 let raw_data =
25 fs::read_to_string("/proc/cpuinfo").expect("unable to read from cpuinfo file");
26
27 let mut map = HashMap::new();
30
31 let mut cpu_mhz_tracker: Vec<(usize, f64)> = vec![];
34
35 let mut l = 0;
37
38 for (_, line) in raw_data.lines().enumerate() {
39 if !line.contains(":") {
40 continue;
41 }
42
43 let kv: Vec<&str> = line.split(":").collect();
44
45 let key = kv[0].trim();
46 let value = kv[1].trim();
47
48 if key == "cpu MHz" {
49 l += 1;
50 cpu_mhz_tracker.push((l, value.parse::<f64>().unwrap()));
51
52 continue;
53 }
54
55 map.insert(key, value);
56 }
57
58 let vendor_id = map
59 .get("vendor_id")
60 .expect("could not retrieve vendor id")
61 .trim()
62 .to_string();
63
64 let model_name = map
65 .get("model name")
66 .expect("could not retrieve model name")
67 .trim()
68 .to_string();
69
70 let cpu_cores = map
71 .get("cpu cores")
72 .expect("could not retrieve cpu cores")
73 .trim()
74 .parse::<usize>()
75 .unwrap();
76
77 let cpuid_level = map
78 .get("cpuid level")
79 .expect("could not retrieve cpuid level")
80 .trim()
81 .parse::<usize>()
82 .unwrap();
83
84 let cache_size = map
85 .get("cache size")
86 .expect("could not retrieve cache size")
87 .trim()
88 .to_string();
89
90 let is_fpu = if map.get("fpu").expect("could not retrieve fpu").trim() == "yes" {
91 true
92 } else {
93 false
94 };
95
96 self.vendor_id = vendor_id;
97 self.model_name = model_name;
98 self.cpuid_level = cpuid_level;
99 self.cores = cpu_cores;
100 self.cache_size = cache_size;
101 self.cpu_speed = cpu_mhz_tracker;
102 self.is_fpu = is_fpu;
103 }
104}