use core::fmt;
use std::sync::OnceLock;
use crate::{Mhz, Pressure, Result, mem::LimitSource, os::keep, parse::cpu_name};
mod features;
mod topology;
mod usage;
pub use features::{Feature, Features, X86Level, features, has, x86_level};
pub use topology::{
Cache, CacheKind, Core, CoreKind, NumaNode, Package, Topology, cache_line, caches, is_hybrid,
numa_nodes, topology,
};
pub(crate) use usage::States;
pub use usage::{DEFAULT_WINDOW, Sampler, Times, Usage, free, times, usage, usage_over, used};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Arch {
X86_64,
X86,
Aarch64,
Arm,
Riscv64,
Powerpc64,
S390x,
Loongarch64,
Wasm32,
Other,
}
impl Arch {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::X86_64 => "x86_64",
Self::X86 => "x86",
Self::Aarch64 => "aarch64",
Self::Arm => "arm",
Self::Riscv64 => "riscv64",
Self::Powerpc64 => "powerpc64",
Self::S390x => "s390x",
Self::Loongarch64 => "loongarch64",
Self::Wasm32 => "wasm32",
Self::Other => "other",
}
}
#[must_use]
pub const fn is_64bit(self) -> bool {
matches!(
self,
Self::X86_64
| Self::Aarch64
| Self::Riscv64
| Self::Powerpc64
| Self::S390x
| Self::Loongarch64
)
}
}
#[must_use]
pub const fn arch() -> Arch {
if cfg!(target_arch = "x86_64") {
Arch::X86_64
} else if cfg!(target_arch = "x86") {
Arch::X86
} else if cfg!(target_arch = "aarch64") {
Arch::Aarch64
} else if cfg!(target_arch = "arm") {
Arch::Arm
} else if cfg!(target_arch = "riscv64") {
Arch::Riscv64
} else if cfg!(target_arch = "powerpc64") {
Arch::Powerpc64
} else if cfg!(target_arch = "s390x") {
Arch::S390x
} else if cfg!(target_arch = "loongarch64") {
Arch::Loongarch64
} else if cfg!(target_arch = "wasm32") {
Arch::Wasm32
} else {
Arch::Other
}
}
#[must_use]
pub fn is_64bit() -> bool {
static IS_64: OnceLock<bool> = OnceLock::new();
*IS_64.get_or_init(crate::sys::processor_is_64bit)
}
#[must_use]
pub fn is_32bit() -> bool {
!is_64bit()
}
#[must_use]
pub fn native_arch() -> Arch {
static ARCH: OnceLock<Arch> = OnceLock::new();
*ARCH.get_or_init(crate::sys::native_arch)
}
#[must_use]
pub fn is_translated() -> bool {
native_arch() != arch()
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
#[non_exhaustive]
pub enum Vendor {
Intel,
Amd,
Apple,
Arm,
Qualcomm,
Ampere,
Nvidia,
Samsung,
Mediatek,
Hygon,
Zhaoxin,
Broadcom,
Marvell,
Fujitsu,
HiSilicon,
Microsoft,
#[default]
Unknown,
}
impl Vendor {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Intel => "Intel",
Self::Amd => "AMD",
Self::Apple => "Apple",
Self::Arm => "ARM",
Self::Qualcomm => "Qualcomm",
Self::Ampere => "Ampere",
Self::Nvidia => "NVIDIA",
Self::Samsung => "Samsung",
Self::Mediatek => "MediaTek",
Self::Hygon => "Hygon",
Self::Zhaoxin => "Zhaoxin",
Self::Broadcom => "Broadcom",
Self::Marvell => "Marvell",
Self::Fujitsu => "Fujitsu",
Self::HiSilicon => "HiSilicon",
Self::Microsoft => "Microsoft",
Self::Unknown => "unknown",
}
}
}
struct Static {
logical: usize,
physical: usize,
physical_exact: bool,
packages: usize,
name: &'static str,
raw_name: Option<&'static str>,
vendor: Vendor,
}
fn facts() -> &'static Static {
static FACTS: OnceLock<Static> = OnceLock::new();
FACTS.get_or_init(|| build(crate::sys::cpu()))
}
fn build(f: crate::sys::CpuFacts) -> Static {
let logical = f.logical.max(1);
let physical = f.physical.unwrap_or(logical).clamp(1, logical);
let packages = f.packages.unwrap_or(1).clamp(1, physical);
let name = f
.name
.or_else(|| f.raw_name.as_deref().map(cpu_name::clean))
.filter(|n| !n.is_empty())
.unwrap_or_else(|| match f.vendor {
Vendor::Unknown => "unknown".to_owned(),
v => format!("{} {}", v.name(), arch().name()),
});
Static {
logical,
physical,
physical_exact: f.physical.is_some(),
packages,
name: keep(name),
raw_name: f.raw_name.filter(|n| !n.trim().is_empty()).map(keep),
vendor: f.vendor,
}
}
#[must_use]
pub fn logical() -> usize {
facts().logical
}
#[must_use]
pub fn physical() -> usize {
facts().physical
}
#[must_use]
pub fn available() -> usize {
crate::sys::cpu_available(logical()).clamp(1, logical())
}
#[must_use]
pub fn name() -> &'static str {
facts().name
}
#[must_use]
pub fn raw_name() -> Option<&'static str> {
facts().raw_name
}
#[must_use]
pub fn vendor() -> Vendor {
facts().vendor
}
#[must_use]
pub fn packages() -> usize {
facts().packages
}
#[must_use]
pub fn online() -> usize {
crate::sys::cpu_online(logical()).clamp(1, logical())
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Counts {
pub logical: usize,
pub physical: usize,
pub packages: usize,
pub available: usize,
pub online: usize,
pub physical_exact: bool,
}
#[must_use]
pub fn count() -> Counts {
let f = facts();
Counts {
logical: f.logical,
physical: f.physical,
packages: f.packages,
available: available(),
online: online(),
physical_exact: f.physical_exact,
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
#[non_exhaustive]
pub struct CpuQuota {
pub cpus: f32,
pub source: LimitSource,
}
pub fn quota() -> Result<Option<CpuQuota>> {
crate::sys::cpu_quota()
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct Frequency {
pub base: Option<Mhz>,
pub max: Option<Mhz>,
}
#[must_use]
pub fn frequency() -> &'static Frequency {
static FREQUENCY: OnceLock<Frequency> = OnceLock::new();
FREQUENCY.get_or_init(crate::sys::frequency)
}
pub fn current_frequency() -> Result<Option<Mhz>> {
crate::sys::current_frequency()
}
#[derive(Clone, Copy, PartialEq, Debug)]
#[non_exhaustive]
pub struct Load {
pub one: f32,
pub five: f32,
pub fifteen: f32,
}
impl Load {
pub(crate) fn new(one: f32, five: f32, fifteen: f32) -> Load {
let clean = |v: f32| if v.is_finite() { v.max(0.0) } else { 0.0 };
Load {
one: clean(one),
five: clean(five),
fifteen: clean(fifteen),
}
}
#[must_use]
pub fn per_cpu(&self) -> Load {
let n = logical() as f32;
Load::new(self.one / n, self.five / n, self.fifteen / n)
}
}
impl fmt::Display for Load {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:.2} {:.2} {:.2}", self.one, self.five, self.fifteen)
}
}
pub fn load() -> Result<Option<Load>> {
crate::sys::load()
}
pub fn pressure() -> Result<Option<Pressure>> {
crate::sys::cpu_pressure()
}
#[cfg(test)]
mod tests {
use super::*;
fn facts_with(
logical: usize,
physical: Option<usize>,
raw: Option<&str>,
name: Option<&str>,
vendor: Vendor,
) -> Static {
build(crate::sys::CpuFacts {
logical,
physical,
packages: None,
raw_name: raw.map(str::to_owned),
name: name.map(str::to_owned),
vendor,
})
}
#[test]
fn test_cpu_counts_hold_their_invariants() {
assert!(physical() >= 1 && physical() <= logical());
let a = available();
assert!(a >= 1 && a <= logical());
assert_ne!(is_64bit(), is_32bit());
if arch().is_64bit() {
assert!(is_64bit());
}
assert!(!name().is_empty());
}
#[test]
fn test_cpu_build_cleans_and_falls_back() {
let s = facts_with(
8,
Some(4),
Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"),
None,
Vendor::Intel,
);
assert_eq!(
(s.logical, s.physical, s.name),
(8, 4, "Intel Core i7-8700")
);
assert_eq!(s.raw_name, Some("Intel(R) Core(TM) i7-8700 CPU @ 3.20GHz"));
let s = facts_with(0, Some(99), None, None, Vendor::Arm);
assert_eq!((s.logical, s.physical), (1, 1));
assert_eq!(s.name, format!("ARM {}", arch().name()));
assert_eq!(
facts_with(4, None, Some(" "), None, Vendor::Unknown).name,
"unknown"
);
assert_eq!(
facts_with(4, None, None, Some("Cortex-A76"), Vendor::Arm).name,
"Cortex-A76"
);
}
#[test]
fn test_cpu_counts_and_load_live() {
let c = count();
assert!(c.packages >= 1 && c.packages <= c.physical);
assert!(c.online >= 1 && c.online <= c.logical);
if let Some(load) = load().unwrap() {
assert!(load.one >= 0.0 && load.five >= 0.0 && load.fifteen >= 0.0);
}
let f = frequency();
if let (Some(b), Some(m)) = (f.base, f.max) {
assert!(b.0 > 0 && m.0 > 0);
}
let _ = current_frequency().unwrap();
let _ = quota().unwrap();
let _ = pressure().unwrap();
}
#[test]
fn test_cpu_load_display_and_cleaning() {
let l = Load::new(2.149, f32::NAN, -1.0);
assert_eq!(l.to_string(), "2.15 0.00 0.00");
assert!(l.per_cpu().one <= l.one);
}
#[test]
fn test_cpu_packages_clamped() {
let s = build(crate::sys::CpuFacts {
logical: 8,
physical: Some(4),
packages: Some(9),
raw_name: None,
name: None,
vendor: Vendor::Amd,
});
assert_eq!((s.packages, s.physical_exact), (4, true));
assert!(!facts_with(8, None, None, None, Vendor::Amd).physical_exact);
}
#[test]
fn test_cpu_arch_names_and_bitness() {
assert_eq!(Arch::X86_64.name(), "x86_64");
assert!(Arch::X86_64.is_64bit() && !Arch::X86.is_64bit() && !Arch::Arm.is_64bit());
assert_eq!(arch().name(), std::env::consts::ARCH);
}
}