use std::alloc::{GlobalAlloc, Layout, System}; use std::sync::atomic::{AtomicUsize, Ordering}; static LIVE: AtomicUsize = AtomicUsize::new(0); static PEAK: AtomicUsize = AtomicUsize::new(0); pub struct MeasuredAllocator; fn add(size: usize) { let live = LIVE.fetch_add(size, Ordering::Relaxed) + size; PEAK.fetch_max(live, Ordering::Relaxed); } unsafe impl GlobalAlloc for MeasuredAllocator { unsafe fn alloc(&self, layout: Layout) -> *mut u8 { let p = unsafe { System.alloc(layout) }; if !p.is_null() { add(layout.size()); } p } unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { let p = unsafe { System.alloc_zeroed(layout) }; if !p.is_null() { add(layout.size()); } p } unsafe fn dealloc(&self, p: *mut u8, layout: Layout) { unsafe { System.dealloc(p, layout) }; LIVE.fetch_sub(layout.size(), Ordering::Relaxed); } unsafe fn realloc(&self, p: *mut u8, layout: Layout, size: usize) -> *mut u8 { let next = unsafe { System.realloc(p, layout, size) }; if !next.is_null() { if size >= layout.size() { add(size - layout.size()); } else { LIVE.fetch_sub(layout.size() - size, Ordering::Relaxed); } } next } } pub fn live() -> usize { LIVE.load(Ordering::Relaxed) } pub fn peak() -> usize { PEAK.load(Ordering::Relaxed) } #[allow( dead_code, reason = "examples `include!` this file without resetting the peak, so an expectation is unfulfilled there" )] pub fn reset_peak_now() { PEAK.store(live(), Ordering::Relaxed); }