1use core::fmt;
16use std::sync::OnceLock;
17
18use crate::{Mhz, Pressure, Result, mem::LimitSource, os::keep, parse::cpu_name};
19
20mod features;
21mod usage;
22
23pub use features::{Feature, Features, X86Level, features, has, x86_level};
24pub(crate) use usage::States;
25pub use usage::{DEFAULT_WINDOW, Sampler, Times, Usage, free, times, usage, usage_over, used};
26
27#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29#[non_exhaustive]
30pub enum Arch {
31 X86_64,
33 X86,
35 Aarch64,
37 Arm,
39 Riscv64,
41 Powerpc64,
43 S390x,
45 Loongarch64,
47 Wasm32,
49 Other,
51}
52
53impl Arch {
54 #[must_use]
60 pub const fn name(self) -> &'static str {
61 match self {
62 Self::X86_64 => "x86_64",
63 Self::X86 => "x86",
64 Self::Aarch64 => "aarch64",
65 Self::Arm => "arm",
66 Self::Riscv64 => "riscv64",
67 Self::Powerpc64 => "powerpc64",
68 Self::S390x => "s390x",
69 Self::Loongarch64 => "loongarch64",
70 Self::Wasm32 => "wasm32",
71 Self::Other => "other",
72 }
73 }
74
75 #[must_use]
83 pub const fn is_64bit(self) -> bool {
84 matches!(
85 self,
86 Self::X86_64
87 | Self::Aarch64
88 | Self::Riscv64
89 | Self::Powerpc64
90 | Self::S390x
91 | Self::Loongarch64
92 )
93 }
94}
95
96#[must_use]
98pub const fn arch() -> Arch {
99 if cfg!(target_arch = "x86_64") {
100 Arch::X86_64
101 } else if cfg!(target_arch = "x86") {
102 Arch::X86
103 } else if cfg!(target_arch = "aarch64") {
104 Arch::Aarch64
105 } else if cfg!(target_arch = "arm") {
106 Arch::Arm
107 } else if cfg!(target_arch = "riscv64") {
108 Arch::Riscv64
109 } else if cfg!(target_arch = "powerpc64") {
110 Arch::Powerpc64
111 } else if cfg!(target_arch = "s390x") {
112 Arch::S390x
113 } else if cfg!(target_arch = "loongarch64") {
114 Arch::Loongarch64
115 } else if cfg!(target_arch = "wasm32") {
116 Arch::Wasm32
117 } else {
118 Arch::Other
119 }
120}
121
122#[must_use]
130pub fn is_64bit() -> bool {
131 static IS_64: OnceLock<bool> = OnceLock::new();
132 *IS_64.get_or_init(crate::sys::processor_is_64bit)
133}
134
135#[must_use]
137pub fn is_32bit() -> bool {
138 !is_64bit()
139}
140
141#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
143#[non_exhaustive]
144pub enum Vendor {
145 Intel,
147 Amd,
149 Apple,
151 Arm,
153 Qualcomm,
155 Ampere,
157 Nvidia,
159 Samsung,
161 Mediatek,
163 Hygon,
165 Zhaoxin,
167 Broadcom,
169 Marvell,
171 Fujitsu,
173 HiSilicon,
175 Microsoft,
177 #[default]
179 Unknown,
180}
181
182impl Vendor {
183 #[must_use]
185 pub const fn name(self) -> &'static str {
186 match self {
187 Self::Intel => "Intel",
188 Self::Amd => "AMD",
189 Self::Apple => "Apple",
190 Self::Arm => "ARM",
191 Self::Qualcomm => "Qualcomm",
192 Self::Ampere => "Ampere",
193 Self::Nvidia => "NVIDIA",
194 Self::Samsung => "Samsung",
195 Self::Mediatek => "MediaTek",
196 Self::Hygon => "Hygon",
197 Self::Zhaoxin => "Zhaoxin",
198 Self::Broadcom => "Broadcom",
199 Self::Marvell => "Marvell",
200 Self::Fujitsu => "Fujitsu",
201 Self::HiSilicon => "HiSilicon",
202 Self::Microsoft => "Microsoft",
203 Self::Unknown => "unknown",
204 }
205 }
206}
207
208struct Static {
209 logical: usize,
210 physical: usize,
211 physical_exact: bool,
212 packages: usize,
213 name: &'static str,
214 raw_name: Option<&'static str>,
215 vendor: Vendor,
216}
217
218fn facts() -> &'static Static {
219 static FACTS: OnceLock<Static> = OnceLock::new();
220 FACTS.get_or_init(|| build(crate::sys::cpu()))
221}
222
223fn build(f: crate::sys::CpuFacts) -> Static {
224 let logical = f.logical.max(1);
225 let physical = f.physical.unwrap_or(logical).clamp(1, logical);
226 let packages = f.packages.unwrap_or(1).clamp(1, physical);
227 let name = f
228 .name
229 .or_else(|| f.raw_name.as_deref().map(cpu_name::clean))
230 .filter(|n| !n.is_empty())
231 .unwrap_or_else(|| match f.vendor {
232 Vendor::Unknown => "unknown".to_owned(),
233 v => format!("{} {}", v.name(), arch().name()),
234 });
235 Static {
236 logical,
237 physical,
238 physical_exact: f.physical.is_some(),
239 packages,
240 name: keep(name),
241 raw_name: f.raw_name.filter(|n| !n.trim().is_empty()).map(keep),
242 vendor: f.vendor,
243 }
244}
245
246#[must_use]
250pub fn logical() -> usize {
251 facts().logical
252}
253
254#[must_use]
257pub fn physical() -> usize {
258 facts().physical
259}
260
261#[must_use]
267pub fn available() -> usize {
268 crate::sys::cpu_available(logical()).clamp(1, logical())
269}
270
271#[must_use]
275pub fn name() -> &'static str {
276 facts().name
277}
278
279#[must_use]
282pub fn raw_name() -> Option<&'static str> {
283 facts().raw_name
284}
285
286#[must_use]
288pub fn vendor() -> Vendor {
289 facts().vendor
290}
291
292#[must_use]
295pub fn packages() -> usize {
296 facts().packages
297}
298
299#[must_use]
303pub fn online() -> usize {
304 crate::sys::cpu_online(logical()).clamp(1, logical())
305}
306
307#[derive(Clone, Copy, PartialEq, Eq, Debug)]
309#[non_exhaustive]
310pub struct Counts {
311 pub logical: usize,
313 pub physical: usize,
315 pub packages: usize,
317 pub available: usize,
319 pub online: usize,
321 pub physical_exact: bool,
324}
325
326#[must_use]
333pub fn count() -> Counts {
334 let f = facts();
335 Counts {
336 logical: f.logical,
337 physical: f.physical,
338 packages: f.packages,
339 available: available(),
340 online: online(),
341 physical_exact: f.physical_exact,
342 }
343}
344
345#[derive(Clone, Copy, PartialEq, Debug)]
347#[non_exhaustive]
348pub struct CpuQuota {
349 pub cpus: f32,
351 pub source: LimitSource,
353}
354
355pub fn quota() -> Result<Option<CpuQuota>> {
372 crate::sys::cpu_quota()
373}
374
375#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
377#[non_exhaustive]
378pub struct Frequency {
379 pub base: Option<Mhz>,
381 pub max: Option<Mhz>,
383}
384
385#[must_use]
393pub fn frequency() -> &'static Frequency {
394 static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
395 FREQUENCY.get_or_init(crate::sys::frequency)
396}
397
398pub fn current_frequency() -> Result<Option<Mhz>> {
406 crate::sys::current_frequency()
407}
408
409#[derive(Clone, Copy, PartialEq, Debug)]
417#[non_exhaustive]
418pub struct Load {
419 pub one: f32,
421 pub five: f32,
423 pub fifteen: f32,
425}
426
427impl Load {
428 pub(crate) fn new(one: f32, five: f32, fifteen: f32) -> Load {
429 let clean = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
430 Load {
431 one: clean(one),
432 five: clean(five),
433 fifteen: clean(fifteen),
434 }
435 }
436
437 #[must_use]
446 pub fn per_cpu(&self) -> Load {
447 let n = logical() as f32;
448 Load::new(self.one / n, self.five / n, self.fifteen / n)
449 }
450}
451
452impl fmt::Display for Load {
453 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454 write!(f, "{:.2} {:.2} {:.2}", self.one, self.five, self.fifteen)
455 }
456}
457
458pub fn load() -> Result<Option<Load>> {
474 crate::sys::load()
475}
476
477pub fn pressure() -> Result<Option<Pressure>> {
487 crate::sys::cpu_pressure()
488}
489
490#[cfg(test)]
491mod tests {
492 use super::*;
493
494 fn facts_with(
495 logical: usize,
496 physical: Option<usize>,
497 raw: Option<&str>,
498 name: Option<&str>,
499 vendor: Vendor,
500 ) -> Static {
501 build(crate::sys::CpuFacts {
502 logical,
503 physical,
504 packages: None,
505 raw_name: raw.map(str::to_owned),
506 name: name.map(str::to_owned),
507 vendor,
508 })
509 }
510
511 #[test]
512 fn test_cpu_counts_hold_their_invariants() {
513 assert!(physical() >= 1 && physical() <= logical());
514 let a = available();
515 assert!(a >= 1 && a <= logical());
516 assert_ne!(is_64bit(), is_32bit());
517 if arch().is_64bit() {
518 assert!(is_64bit());
519 }
520 assert!(!name().is_empty());
521 }
522
523 #[test]
524 fn test_cpu_build_cleans_and_falls_back() {
525 let s = facts_with(
526 8,
527 Some(4),
528 Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"),
529 None,
530 Vendor::Intel,
531 );
532 assert_eq!(
533 (s.logical, s.physical, s.name),
534 (8, 4, "Intel Core i7-8700")
535 );
536 assert_eq!(s.raw_name, Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
537 let s = facts_with(0, Some(99), None, None, Vendor::Arm);
538 assert_eq!((s.logical, s.physical), (1, 1));
539 assert_eq!(s.name, format!("ARM {}", arch().name()));
540 assert_eq!(
541 facts_with(4, None, Some(" "), None, Vendor::Unknown).name,
542 "unknown"
543 );
544 assert_eq!(
545 facts_with(4, None, None, Some("Cortex-A76"), Vendor::Arm).name,
546 "Cortex-A76"
547 );
548 }
549
550 #[test]
551 fn test_cpu_counts_and_load_live() {
552 let c = count();
553 assert!(c.packages >= 1 && c.packages <= c.physical);
554 assert!(c.online >= 1 && c.online <= c.logical);
555 if let Some(load) = load().unwrap() {
556 assert!(load.one >= 0.0 && load.five >= 0.0 && load.fifteen >= 0.0);
557 }
558 let f = frequency();
559 if let (Some(b), Some(m)) = (f.base, f.max) {
560 assert!(b.0 > 0 && m.0 > 0);
561 }
562 let _ = current_frequency().unwrap();
563 let _ = quota().unwrap();
564 let _ = pressure().unwrap();
565 }
566
567 #[test]
568 fn test_cpu_load_display_and_cleaning() {
569 let l = Load::new(2.149, f32::NAN, -1.0);
570 assert_eq!(l.to_string(), "2.15 0.00 0.00");
571 assert!(l.per_cpu().one <= l.one);
572 }
573
574 #[test]
575 fn test_cpu_packages_clamped() {
576 let s = build(crate::sys::CpuFacts {
577 logical: 8,
578 physical: Some(4),
579 packages: Some(9),
580 raw_name: None,
581 name: None,
582 vendor: Vendor::Amd,
583 });
584 assert_eq!((s.packages, s.physical_exact), (4, true));
585 assert!(!facts_with(8, None, None, None, Vendor::Amd).physical_exact);
586 }
587
588 #[test]
589 fn test_cpu_arch_names_and_bitness() {
590 assert_eq!(Arch::X86_64.name(), "x86_64");
591 assert!(Arch::X86_64.is_64bit() && !Arch::X86.is_64bit() && !Arch::Arm.is_64bit());
592 assert_eq!(arch().name(), std::env::consts::ARCH);
593 }
594}