#![allow(unsafe_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
pub struct Counting;
thread_local! {
static WATCH: Cell<bool> = const { Cell::new(false) };
static COUNT: Cell<usize> = const { Cell::new(0) };
}
fn note() {
let _ = WATCH.try_with(|w| {
if w.get() {
let _ = COUNT.try_with(|c| c.set(c.get() + 1));
}
});
}
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
note();
System.alloc(l)
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
System.dealloc(p, l)
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
note();
System.realloc(p, l, n)
}
}
pub fn allocations(f: impl FnOnce()) -> usize {
COUNT.with(|c| c.set(0));
WATCH.with(|w| w.set(true));
f();
WATCH.with(|w| w.set(false));
COUNT.with(|c| c.get())
}