#![allow(dead_code)]
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
pub static CURRENT: AtomicUsize = AtomicUsize::new(0);
pub static PEAK: AtomicUsize = AtomicUsize::new(0);
pub static ALLOCATIONS: AtomicUsize = AtomicUsize::new(0);
fn grow(size: usize) {
let now = CURRENT.fetch_add(size, Ordering::SeqCst) + size;
PEAK.fetch_max(now, Ordering::SeqCst);
}
pub struct PeakAlloc;
unsafe impl GlobalAlloc for PeakAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc(layout) }
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
grow(layout.size());
unsafe { System.alloc_zeroed(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
CURRENT.fetch_sub(layout.size(), Ordering::SeqCst);
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
grow(new_size);
CURRENT.fetch_sub(layout.size(), Ordering::SeqCst);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
pub struct CountAlloc;
unsafe impl GlobalAlloc for CountAlloc {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCATIONS.fetch_add(1, Ordering::SeqCst);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
}