use core::cell::Cell;
thread_local! {
static SATURATIONS: Cell<u64> = const { Cell::new(0) };
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Saturations(pub u64);
impl Saturations {
#[must_use]
pub const fn is_clean(self) -> bool {
self.0 == 0
}
}
#[must_use]
pub fn saturations() -> Saturations {
Saturations(SATURATIONS.with(Cell::get))
}
pub(crate) fn record() {
SATURATIONS.with(|count| count.set(count.get().saturating_add(1)));
}
#[cfg(test)]
mod tests {
use super::{record, saturations};
#[test]
fn the_counter_counts_and_is_readable_only_through_the_snapshot() {
let before = saturations();
record();
record();
assert_eq!(saturations().0, before.0 + 2);
assert!(!saturations().is_clean());
}
#[test]
fn the_counter_saturates_rather_than_wrapping() {
super::SATURATIONS.with(|count| count.set(u64::MAX));
record();
assert_eq!(saturations().0, u64::MAX);
super::SATURATIONS.with(|count| count.set(0));
}
#[test]
#[expect(
clippy::disallowed_methods,
reason = "the property under test is thread-locality, which needs a thread"
)]
fn a_count_on_another_thread_is_not_visible_here() {
let before = saturations();
std::thread::spawn(|| {
record();
record();
record();
})
.join()
.expect("the counting thread finished");
assert_eq!(saturations(), before, "another thread's count leaked here");
}
}