Last active
October 10, 2022 06:55
-
-
Save Yoplitein/45b3b32243210309392d92c9791f48d6 to your computer and use it in GitHub Desktop.
GlobalAllocator that tracks number of allocated bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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