use serde::Serialize;
use std::alloc::{GlobalAlloc, Layout};
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
static ALLOCS: AtomicU64 = AtomicU64::new(0);
static REALLOCS: AtomicU64 = AtomicU64::new(0);
static FREES: AtomicU64 = AtomicU64::new(0);
static ALLOCATED: AtomicU64 = AtomicU64::new(0);
static FREED: AtomicU64 = AtomicU64::new(0);
static LIVE: AtomicU64 = AtomicU64::new(0);
static PEAK: AtomicU64 = AtomicU64::new(0);
static FAILURES: AtomicU64 = AtomicU64::new(0);
fn grow(bytes: u64) {
let n = LIVE.fetch_add(bytes, Relaxed) + bytes;
PEAK.fetch_max(n, Relaxed);
}
#[derive(Clone, Copy, Debug, Default, Serialize)]
pub struct Snapshot {
pub alloc_calls: u64,
pub realloc_calls: u64,
pub free_calls: u64,
pub allocated_bytes: u64,
pub freed_bytes: u64,
pub live_bytes: u64,
pub global_peak_bytes: u64,
pub failures: u64,
}
pub fn snapshot() -> Snapshot {
Snapshot {
alloc_calls: ALLOCS.load(Relaxed),
realloc_calls: REALLOCS.load(Relaxed),
free_calls: FREES.load(Relaxed),
allocated_bytes: ALLOCATED.load(Relaxed),
freed_bytes: FREED.load(Relaxed),
live_bytes: LIVE.load(Relaxed),
global_peak_bytes: PEAK.load(Relaxed),
failures: FAILURES.load(Relaxed),
}
}
pub struct CountingAllocator;
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, l: Layout) -> *mut u8 {
let p = unsafe { mimalloc::MiMalloc.alloc(l) };
if p.is_null() {
FAILURES.fetch_add(1, Relaxed);
} else {
ALLOCS.fetch_add(1, Relaxed);
ALLOCATED.fetch_add(l.size() as u64, Relaxed);
grow(l.size() as u64);
}
p
}
unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 {
let p = unsafe { mimalloc::MiMalloc.alloc_zeroed(l) };
if p.is_null() {
FAILURES.fetch_add(1, Relaxed);
} else {
ALLOCS.fetch_add(1, Relaxed);
ALLOCATED.fetch_add(l.size() as u64, Relaxed);
grow(l.size() as u64);
}
p
}
unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
unsafe { mimalloc::MiMalloc.dealloc(p, l) };
FREES.fetch_add(1, Relaxed);
FREED.fetch_add(l.size() as u64, Relaxed);
LIVE.fetch_sub(l.size() as u64, Relaxed);
}
unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
let q = unsafe { mimalloc::MiMalloc.realloc(p, l, n) };
if q.is_null() {
FAILURES.fetch_add(1, Relaxed);
} else {
REALLOCS.fetch_add(1, Relaxed);
ALLOCATED.fetch_add(n as u64, Relaxed);
FREED.fetch_add(l.size() as u64, Relaxed);
if n >= l.size() {
grow((n - l.size()) as u64)
} else {
LIVE.fetch_sub((l.size() - n) as u64, Relaxed);
}
}
q
}
}