use std::sync::OnceLock;
use crate::{Bytes, sys::TopologyFacts};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Topology {
pub packages: Vec<Package>,
pub cores: Vec<Core>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Package {
pub id: u32,
pub cores: Vec<u32>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Core {
pub id: u32,
pub package: u32,
pub logical: Vec<u32>,
pub kind: CoreKind,
pub capacity: Option<u16>,
pub numa_node: Option<u32>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum CoreKind {
Performance,
Efficiency,
Uniform,
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Cache {
pub level: u8,
pub kind: CacheKind,
pub size: Bytes,
pub line: u32,
pub shared_by: Vec<u32>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum CacheKind {
Data,
Instruction,
Unified,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct NumaNode {
pub id: u32,
pub cpus: Vec<u32>,
pub memory: Option<Bytes>,
}
fn facts() -> &'static TopologyFacts {
static FACTS: OnceLock<TopologyFacts> = OnceLock::new();
FACTS.get_or_init(|| {
let mut f = crate::sys::cpu_topology();
f.topology.packages.sort_by_key(|p| p.id);
f.topology.cores.sort_by_key(|c| (c.package, c.id));
f.caches
.sort_by_key(|c| (c.level, c.shared_by.first().copied()));
f.numa.sort_by_key(|n| n.id);
f
})
}
#[must_use]
pub fn topology() -> &'static Topology {
&facts().topology
}
#[must_use]
pub fn caches() -> &'static [Cache] {
&facts().caches
}
#[must_use]
pub fn cache_line() -> usize {
let line = caches()
.iter()
.find(|c| c.level == 1 && c.kind != CacheKind::Instruction)
.map(|c| c.line as usize)
.filter(|l| l.is_power_of_two() && (16..=1024).contains(l));
line.unwrap_or(
if cfg!(all(target_vendor = "apple", target_arch = "aarch64")) {
128
} else {
64
},
)
}
#[must_use]
pub fn numa_nodes() -> &'static [NumaNode] {
&facts().numa
}
#[must_use]
pub fn is_hybrid() -> bool {
let cores = &topology().cores;
cores.iter().any(|c| c.kind == CoreKind::Performance)
&& cores.iter().any(|c| c.kind == CoreKind::Efficiency)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cpu_topology_live_is_consistent() {
assert!(cache_line().is_power_of_two());
let t = topology();
assert!(std::ptr::eq(t, topology()));
for c in &t.cores {
assert!(!c.logical.is_empty());
assert!(t.packages.iter().any(|p| p.id == c.package));
}
for pair in t.packages.windows(2) {
assert!(pair[0].id < pair[1].id);
}
for pair in numa_nodes().windows(2) {
assert!(pair[0].id < pair[1].id);
}
}
}