use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
struct TrackingAllocator;
std::thread_local! {
static TRACK_ALLOCATIONS: Cell<bool> = const { Cell::new(false) };
static ALLOCATION_COUNT: Cell<usize> = const { Cell::new(0) };
}
unsafe impl GlobalAlloc for TrackingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
TRACK_ALLOCATIONS.with(|tracking| {
if tracking.get() {
ALLOCATION_COUNT.with(|count| count.set(count.get() + 1));
}
});
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
TRACK_ALLOCATIONS.with(|tracking| {
if tracking.get() {
ALLOCATION_COUNT.with(|count| count.set(count.get() + 1));
}
});
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOCATOR: TrackingAllocator = TrackingAllocator;
pub fn tracked_allocations(run: impl FnOnce()) -> usize {
ALLOCATION_COUNT.with(|count| count.set(0));
TRACK_ALLOCATIONS.with(|tracking| tracking.set(true));
run();
TRACK_ALLOCATIONS.with(|tracking| tracking.set(false));
ALLOCATION_COUNT.with(Cell::get)
}