use std::alloc::{GlobalAlloc, Layout, System};
use std::cell::Cell;
struct RecordingAllocator;
thread_local! {
static LARGEST_ALLOCATION: Cell<usize> = const { Cell::new(0) };
}
fn record(size: usize) {
let _ = LARGEST_ALLOCATION.try_with(|largest| largest.set(largest.get().max(size)));
}
unsafe impl GlobalAlloc for RecordingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
record(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
record(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
record(new_size);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static ALLOCATOR: RecordingAllocator = RecordingAllocator;
pub fn largest_allocation_during<T, F>(f: F) -> (T, usize)
where
F: FnOnce() -> T,
{
LARGEST_ALLOCATION.with(|largest| largest.set(0));
let result = f();
(result, LARGEST_ALLOCATION.with(Cell::get))
}