use clock_kit::LatencyRing;
use core::sync::atomic::{AtomicUsize, Ordering};
use std::alloc::{GlobalAlloc, Layout, System};
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
struct Counting;
#[allow(unsafe_code)]
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
#[test]
fn stats_and_record_never_allocate() {
let mut ring = LatencyRing::<4096>::new();
for i in 0..4_096_u64 {
ring.record(i % 1_000);
}
let before = ALLOCS.load(Ordering::Relaxed);
let stats = ring.stats();
let mid = ALLOCS.load(Ordering::Relaxed);
for i in 0..1_000_u64 {
ring.record(i);
let _ = ring.stats();
}
let after = ALLOCS.load(Ordering::Relaxed);
assert_eq!(mid - before, 0, "stats() allocated");
assert_eq!(after - mid, 0, "record()/stats() loop allocated");
assert!(stats.mean > 0 || stats.min == 0);
assert_eq!(ring.len(), 4096);
}