1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use std::collections::{HashMap, HashSet};
use std::convert::Infallible;
use std::fs::read_to_string;
use std::path::Path;
use std::str::FromStr;

const DEFAULT_FILE: &str = "/proc/cpuinfo";
const KIB: usize = 1024;
const MIB: usize = 1024 * KIB;
const GIB: usize = 1024 * MIB;

#[derive(Debug, Eq, PartialEq)]
pub struct CpuInfo(String);

impl CpuInfo {
    /// Reads CPU information from `/proc/cpuinfo`.
    /// # Errors
    /// Returns an [`std::io::Error`] if the file could not be read
    pub fn read() -> Result<Self, std::io::Error> {
        Self::read_from(DEFAULT_FILE)
    }

    /// Reads CPU information from the given file.
    /// # Errors
    /// Returns an [`std::io::Error`] if the file could not be read
    pub fn read_from(filename: impl AsRef<Path>) -> Result<Self, std::io::Error> {
        read_to_string(filename).map(Self)
    }

    #[must_use]
    pub fn cpu(&self, index: usize) -> Option<Cpu> {
        self.cpus()
            .filter_map(|cpu| cpu.processor().map(|processor| (processor, cpu)))
            .find_map(|(processor, cpu)| if processor == index { Some(cpu) } else { None })
    }

    pub fn cpus(&self) -> impl Iterator<Item = Cpu> {
        self.0
            .split("\n\n")
            .filter(|text| !text.is_empty())
            .map(Cpu::from_str)
    }

    pub fn iter(&self) -> impl Iterator<Item = Cpu> {
        self.cpus()
    }
}

impl From<&str> for CpuInfo {
    fn from(s: &str) -> Self {
        Self::from(s.to_string())
    }
}

impl From<String> for CpuInfo {
    fn from(text: String) -> Self {
        Self(text)
    }
}

impl FromStr for CpuInfo {
    type Err = Infallible;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(s))
    }
}

#[derive(Debug, Eq, PartialEq)]
pub struct Cpu<'cpu_info>(HashMap<&'cpu_info str, &'cpu_info str>);

impl<'cpu_info> Cpu<'cpu_info> {
    fn from_str(s: &'cpu_info str) -> Self {
        Self(
            s.lines()
                .filter_map(|line| line.split_once(':'))
                .map(|(key, value)| (key.trim(), value.trim()))
                .collect(),
        )
    }

    #[must_use]
    pub fn get(&self, key: &str) -> Option<&str> {
        self.0.get(key).copied()
    }

    #[must_use]
    pub fn processor(&self) -> Option<usize> {
        self.get("processor").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn vendor_id(&self) -> Option<&str> {
        self.get("vendor_id")
    }

    #[must_use]
    pub fn cpu_family(&self) -> Option<u8> {
        self.get("cpu family").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn model(&self) -> Option<usize> {
        self.get("model").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn model_name(&self) -> Option<&str> {
        self.get("model name")
    }

    #[must_use]
    pub fn stepping(&self) -> Option<usize> {
        self.get("stepping").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn microcode(&self) -> Option<usize> {
        self.get("microcode")
            .and_then(|s| usize::from_str_radix(s.trim_start_matches("0x"), 16).ok())
    }

    #[must_use]
    pub fn cpu_mhz(&self) -> Option<f32> {
        self.get("cpu MHz").and_then(|s| s.parse().ok())
    }

    /// Returns the CPU's cache size in bytes
    #[must_use]
    pub fn cache_size(&self) -> Option<usize> {
        self.get("cache size")
            .and_then(|s| match s.split_once(' ') {
                Some((value, unit)) => {
                    let value: usize = value.parse().ok()?;
                    match unit {
                        "B" => Some(value),
                        "KB" => Some(value * KIB),
                        "MB" => Some(value * MIB),
                        "GB" => Some(value * GIB),
                        _ => None,
                    }
                }
                None => s.parse().ok(),
            })
    }

    #[must_use]
    pub fn physical_id(&self) -> Option<usize> {
        self.get("physical id").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn siblings(&self) -> Option<usize> {
        self.get("siblings").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn core_id(&self) -> Option<usize> {
        self.get("core id").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn cpu_cores(&self) -> Option<usize> {
        self.get("cpu cores").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn apicid(&self) -> Option<usize> {
        self.get("apicid").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn initial_apicid(&self) -> Option<usize> {
        self.get("initial apicid").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn fpu(&self) -> Option<bool> {
        self.get("fpu").map(|s| s == "yes")
    }

    #[must_use]
    pub fn fpu_exception(&self) -> Option<bool> {
        self.get("fpu_exception").map(|s| s == "yes")
    }

    #[must_use]
    pub fn cpuid_level(&self) -> Option<usize> {
        self.get("cpuid level").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn wp(&self) -> Option<bool> {
        self.get("wp").map(|s| s == "yes")
    }

    #[must_use]
    pub fn flags(&self) -> HashSet<&str> {
        self.get("flags")
            .map_or_else(HashSet::default, |s| s.split(' ').collect())
    }

    #[must_use]
    pub fn vmx_flags(&self) -> HashSet<&str> {
        self.get("vmx flags")
            .map_or_else(HashSet::default, |s| s.split(' ').collect())
    }

    #[must_use]
    pub fn bugs(&self) -> HashSet<&str> {
        self.get("bugs")
            .map_or_else(HashSet::default, |s| s.split(' ').collect())
    }

    #[must_use]
    pub fn bogomips(&self) -> Option<f32> {
        self.get("bogomips").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn clflush_size(&self) -> Option<usize> {
        self.get("clflush size").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn cache_alignment(&self) -> Option<usize> {
        self.get("cache_alignment").and_then(|s| s.parse().ok())
    }

    #[must_use]
    pub fn address_sizes(&self) -> Option<(usize, usize)> {
        self.get("address sizes")
            .and_then(|s| s.split_once(','))
            .map(|(lhs, rhs)| {
                (
                    lhs.trim().trim_end_matches(" bits physical"),
                    rhs.trim().trim_end_matches(" bits virtual"),
                )
            })
            .and_then(|(phy, vir)| {
                phy.parse()
                    .ok()
                    .and_then(|phy| vir.parse().ok().map(|vir| (phy, vir)))
            })
    }

    #[must_use]
    pub fn power_management(&self) -> Option<&str> {
        self.get("power management")
    }
}