Skip to content

Instantly share code, notes, and snippets.

@Yoplitein
Last active October 10, 2022 06:55
Show Gist options
  • Save Yoplitein/45b3b32243210309392d92c9791f48d6 to your computer and use it in GitHub Desktop.
Save Yoplitein/45b3b32243210309392d92c9791f48d6 to your computer and use it in GitHub Desktop.
GlobalAllocator that tracks number of allocated bytes
use std::sync::atomic::{AtomicUsize, Ordering};
use std::alloc;
#[global_allocator]
static COUNTING_ALLOC: CountingAlloc = CountingAlloc::new();
struct CountingAlloc {
used: AtomicUsize,
}
impl CountingAlloc {
pub const fn new() -> Self {
Self {
used: AtomicUsize::new(0)
}
}
pub fn bytes_used(&self) -> usize {
self.used.load(Ordering::SeqCst)
}
}
unsafe impl alloc::GlobalAlloc for CountingAlloc {
unsafe fn alloc(&self, layout: alloc::Layout) -> *mut u8 {
self.used.fetch_add(layout.size(), Ordering::SeqCst);
alloc::System.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: alloc::Layout) {
self.used.fetch_sub(layout.size(), Ordering::SeqCst);
alloc::System.dealloc(ptr, layout)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment