Skip to main content

sys_lib/
cpu.rs

1//! The processor: architecture and bitness, name and vendor, and the three
2//! counts (cores, hardware threads, and what this process may use).
3//!
4//! ```
5//! use sys_lib as sys;
6//!
7//! println!("{} ({:?}, {})", sys::cpu::name(), sys::cpu::vendor(), sys::cpu::arch().name());
8//! println!("{} cores, {} threads, {} usable here", sys::cpu::physical(), sys::cpu::logical(), sys::cpu::available());
9//! // Size a worker pool by what the container allows, not by the host.
10//! let workers = sys::cpu::available();
11//! # let _ = workers;
12//! ```
13
14use std::sync::OnceLock;
15
16use crate::{os::keep, parse::cpu_name};
17
18/// A processor architecture.
19#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
20#[non_exhaustive]
21pub enum Arch {
22    /// x86-64.
23    X86_64,
24    /// 32-bit x86.
25    X86,
26    /// 64-bit ARM.
27    Aarch64,
28    /// 32-bit ARM.
29    Arm,
30    /// 64-bit RISC-V.
31    Riscv64,
32    /// 64-bit PowerPC.
33    Powerpc64,
34    /// IBM Z.
35    S390x,
36    /// 64-bit LoongArch.
37    Loongarch64,
38    /// 32-bit WebAssembly.
39    Wasm32,
40    /// Anything else.
41    Other,
42}
43
44impl Arch {
45    /// The name rustc uses: `"x86_64"`, `"aarch64"`.
46    ///
47    /// ```
48    /// assert_eq!(sys_lib::cpu::Arch::Aarch64.name(), "aarch64");
49    /// ```
50    #[must_use]
51    pub const fn name(self) -> &'static str {
52        match self {
53            Self::X86_64 => "x86_64",
54            Self::X86 => "x86",
55            Self::Aarch64 => "aarch64",
56            Self::Arm => "arm",
57            Self::Riscv64 => "riscv64",
58            Self::Powerpc64 => "powerpc64",
59            Self::S390x => "s390x",
60            Self::Loongarch64 => "loongarch64",
61            Self::Wasm32 => "wasm32",
62            Self::Other => "other",
63        }
64    }
65
66    /// Whether the architecture is 64-bit.
67    ///
68    /// ```
69    /// // The program's own bitness, as a compile-time constant:
70    /// const BUILD_IS_64: bool = sys_lib::cpu::arch().is_64bit();
71    /// # let _ = BUILD_IS_64;
72    /// ```
73    #[must_use]
74    pub const fn is_64bit(self) -> bool {
75        matches!(
76            self,
77            Self::X86_64
78                | Self::Aarch64
79                | Self::Riscv64
80                | Self::Powerpc64
81                | Self::S390x
82                | Self::Loongarch64
83        )
84    }
85}
86
87/// The architecture this program was compiled for.
88#[must_use]
89pub const fn arch() -> Arch {
90    if cfg!(target_arch = "x86_64") {
91        Arch::X86_64
92    } else if cfg!(target_arch = "x86") {
93        Arch::X86
94    } else if cfg!(target_arch = "aarch64") {
95        Arch::Aarch64
96    } else if cfg!(target_arch = "arm") {
97        Arch::Arm
98    } else if cfg!(target_arch = "riscv64") {
99        Arch::Riscv64
100    } else if cfg!(target_arch = "powerpc64") {
101        Arch::Powerpc64
102    } else if cfg!(target_arch = "s390x") {
103        Arch::S390x
104    } else if cfg!(target_arch = "loongarch64") {
105        Arch::Loongarch64
106    } else if cfg!(target_arch = "wasm32") {
107        Arch::Wasm32
108    } else {
109        Arch::Other
110    }
111}
112
113/// Whether the **processor** is 64-bit. A 32-bit program on a 64-bit machine
114/// still sees `true` (D-024); the program's own bitness is
115/// `cpu::arch().is_64bit()`.
116///
117/// ```
118/// assert_ne!(sys_lib::cpu::is_64bit(), sys_lib::cpu::is_32bit());
119/// ```
120#[must_use]
121pub fn is_64bit() -> bool {
122    static IS_64: OnceLock<bool> = OnceLock::new();
123    *IS_64.get_or_init(crate::sys::processor_is_64bit)
124}
125
126/// Whether the processor is 32-bit only.
127#[must_use]
128pub fn is_32bit() -> bool {
129    !is_64bit()
130}
131
132/// A CPU designer or manufacturer.
133#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
134#[non_exhaustive]
135pub enum Vendor {
136    /// Intel.
137    Intel,
138    /// AMD.
139    Amd,
140    /// Apple.
141    Apple,
142    /// Arm (Cortex and Neoverse cores).
143    Arm,
144    /// Qualcomm.
145    Qualcomm,
146    /// Ampere Computing.
147    Ampere,
148    /// NVIDIA.
149    Nvidia,
150    /// Samsung.
151    Samsung,
152    /// MediaTek.
153    Mediatek,
154    /// Hygon.
155    Hygon,
156    /// Zhaoxin and VIA (Centaur).
157    Zhaoxin,
158    /// Broadcom.
159    Broadcom,
160    /// Marvell (formerly Cavium).
161    Marvell,
162    /// Fujitsu.
163    Fujitsu,
164    /// HiSilicon.
165    HiSilicon,
166    /// Microsoft (Azure Cobalt).
167    Microsoft,
168    /// Not known.
169    #[default]
170    Unknown,
171}
172
173impl Vendor {
174    /// The vendor's name: "Intel", "AMD", "ARM".
175    #[must_use]
176    pub const fn name(self) -> &'static str {
177        match self {
178            Self::Intel => "Intel",
179            Self::Amd => "AMD",
180            Self::Apple => "Apple",
181            Self::Arm => "ARM",
182            Self::Qualcomm => "Qualcomm",
183            Self::Ampere => "Ampere",
184            Self::Nvidia => "NVIDIA",
185            Self::Samsung => "Samsung",
186            Self::Mediatek => "MediaTek",
187            Self::Hygon => "Hygon",
188            Self::Zhaoxin => "Zhaoxin",
189            Self::Broadcom => "Broadcom",
190            Self::Marvell => "Marvell",
191            Self::Fujitsu => "Fujitsu",
192            Self::HiSilicon => "HiSilicon",
193            Self::Microsoft => "Microsoft",
194            Self::Unknown => "unknown",
195        }
196    }
197}
198
199struct Static {
200    logical: usize,
201    physical: usize,
202    name: &'static str,
203    raw_name: Option<&'static str>,
204    vendor: Vendor,
205}
206
207fn facts() -> &'static Static {
208    static FACTS: OnceLock<Static> = OnceLock::new();
209    FACTS.get_or_init(|| build(crate::sys::cpu()))
210}
211
212fn build(f: crate::sys::CpuFacts) -> Static {
213    let logical = f.logical.max(1);
214    let physical = f.physical.unwrap_or(logical).clamp(1, logical);
215    let name = f
216        .name
217        .or_else(|| f.raw_name.as_deref().map(cpu_name::clean))
218        .filter(|n| !n.is_empty())
219        .unwrap_or_else(|| match f.vendor {
220            Vendor::Unknown => "unknown".to_owned(),
221            v => format!("{} {}", v.name(), arch().name()),
222        });
223    Static {
224        logical,
225        physical,
226        name: keep(name),
227        raw_name: f.raw_name.filter(|n| !n.trim().is_empty()).map(keep),
228        vendor: f.vendor,
229    }
230}
231
232/// Configured hardware threads: the right size for per-CPU arrays. A static
233/// fact (E-15: present CPUs, not the `possible` count VMs inflate). Windows
234/// counts every processor group (FR-12). At least 1.
235#[must_use]
236pub fn logical() -> usize {
237    facts().logical
238}
239
240/// Physical cores; [`logical`] when the topology is hidden (E-18). Always
241/// between 1 and `logical()`.
242#[must_use]
243pub fn physical() -> usize {
244    facts().physical
245}
246
247/// The CPUs this process may use right now: the affinity mask, intersected
248/// with the cgroup cpuset, then limited by the cgroup CPU quota (Linux), or the
249/// group affinity and the job object's CPU rate (Windows). Size worker pools by
250/// this. A live reading: affinity, hot-plug, and quotas change. Always between
251/// 1 and `logical()`.
252#[must_use]
253pub fn available() -> usize {
254    crate::sys::cpu_available(logical()).clamp(1, logical())
255}
256
257/// The cleaned product name: "AMD Ryzen 9 7950X", "Apple M2 Pro",
258/// "Cortex-A76 + Cortex-A55". Never empty: falls back to the vendor and
259/// architecture ("ARM aarch64"), then "unknown".
260#[must_use]
261pub fn name() -> &'static str {
262    facts().name
263}
264
265/// The name exactly as the OS reports it, for support output; `None` where the
266/// OS reports no brand string (most ARM Linux systems).
267#[must_use]
268pub fn raw_name() -> Option<&'static str> {
269    facts().raw_name
270}
271
272/// The vendor.
273#[must_use]
274pub fn vendor() -> Vendor {
275    facts().vendor
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    fn facts_with(
283        logical: usize,
284        physical: Option<usize>,
285        raw: Option<&str>,
286        name: Option<&str>,
287        vendor: Vendor,
288    ) -> Static {
289        build(crate::sys::CpuFacts {
290            logical,
291            physical,
292            raw_name: raw.map(str::to_owned),
293            name: name.map(str::to_owned),
294            vendor,
295        })
296    }
297
298    #[test]
299    fn test_cpu_counts_hold_their_invariants() {
300        assert!(physical() >= 1 && physical() <= logical());
301        let a = available();
302        assert!(a >= 1 && a <= logical());
303        assert_ne!(is_64bit(), is_32bit());
304        if arch().is_64bit() {
305            assert!(is_64bit());
306        }
307        assert!(!name().is_empty());
308    }
309
310    #[test]
311    fn test_cpu_build_cleans_and_falls_back() {
312        let s = facts_with(
313            8,
314            Some(4),
315            Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"),
316            None,
317            Vendor::Intel,
318        );
319        assert_eq!(
320            (s.logical, s.physical, s.name),
321            (8, 4, "Intel Core i7-8700")
322        );
323        assert_eq!(s.raw_name, Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
324        let s = facts_with(0, Some(99), None, None, Vendor::Arm);
325        assert_eq!((s.logical, s.physical), (1, 1));
326        assert_eq!(s.name, format!("ARM {}", arch().name()));
327        assert_eq!(
328            facts_with(4, None, Some("  "), None, Vendor::Unknown).name,
329            "unknown"
330        );
331        assert_eq!(
332            facts_with(4, None, None, Some("Cortex-A76"), Vendor::Arm).name,
333            "Cortex-A76"
334        );
335    }
336
337    #[test]
338    fn test_cpu_arch_names_and_bitness() {
339        assert_eq!(Arch::X86_64.name(), "x86_64");
340        assert!(Arch::X86_64.is_64bit() && !Arch::X86.is_64bit() && !Arch::Arm.is_64bit());
341        assert_eq!(arch().name(), std::env::consts::ARCH);
342    }
343}