#![cfg(test)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
thread_local! {
static ALLOCATED: Cell<usize> = const { Cell::new(0) };
static FREED: Cell<usize> = const { Cell::new(0) };
}
pub struct Counting;
fn bump(key: &'static std::thread::LocalKey<Cell<usize>>, n: usize) {
let _ = key.try_with(|c| c.set(c.get().wrapping_add(n)));
}
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let p = unsafe { System.alloc(layout) };
if !p.is_null() {
bump(&ALLOCATED, layout.size());
}
p
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
bump(&FREED, layout.size());
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
let p = unsafe { System.realloc(ptr, layout, new_size) };
if !p.is_null() {
if new_size >= layout.size() {
bump(&ALLOCATED, new_size - layout.size());
} else {
bump(&FREED, layout.size() - new_size);
}
}
p
}
}
pub fn live_bytes() -> usize {
let a = ALLOCATED.try_with(|c| c.get()).unwrap_or(0);
let f = FREED.try_with(|c| c.get()).unwrap_or(0);
a.saturating_sub(f)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn transient_allocations_net_to_zero() {
let before = live_bytes();
for _ in 0..10_000 {
let s = String::from("a transient heap allocation that is dropped");
std::hint::black_box(&s);
}
let growth = live_bytes().saturating_sub(before);
assert!(growth < 64 * 1024, "transient allocs leaked {growth} bytes");
}
#[test]
fn retained_allocations_are_visible() {
let before = live_bytes();
let mut kept: Vec<String> = Vec::new();
for i in 0..2_000 {
kept.push(format!("retained string number {i} with some padding"));
}
let growth = live_bytes().saturating_sub(before);
assert!(
growth > 50_000,
"retained allocs should be visible, saw {growth}"
);
std::hint::black_box(&kept);
}
#[test]
fn counters_are_independent_per_thread() {
let before = live_bytes();
std::thread::spawn(|| {
let mut v: Vec<String> = Vec::new();
for i in 0..5_000 {
v.push(format!("other thread allocation {i} padded out a bit"));
}
std::hint::black_box(&v);
})
.join()
.unwrap();
let growth = live_bytes().saturating_sub(before);
assert!(
growth < 64 * 1024,
"another thread's allocations leaked in: {growth}"
);
}
}