1use std::sync::atomic::AtomicUsize;
2
3pub static ALLOCATED: AtomicUsize = AtomicUsize::new(0);
4pub static FREEED: AtomicUsize = AtomicUsize::new(0);
5
6#[macro_export]
15macro_rules! wrap_global_allocator {
16 ($alloc:path) => {
17 #[global_allocator]
18 static A: InstrumentedAllocator = InstrumentedAllocator;
19
20 struct InstrumentedAllocator;
21
22 unsafe impl std::alloc::GlobalAlloc for InstrumentedAllocator {
23 unsafe fn alloc(&self, layout: std::alloc::Layout) -> *mut u8 {
24 use std::sync::atomic::Ordering::Relaxed;
25 let ptr = $alloc.alloc(layout);
26 if !ptr.is_null() {
27 $crate::alloc::ALLOCATED.fetch_add(layout.size(), Relaxed);
28 }
29 ptr
30 }
31 unsafe fn dealloc(&self, ptr: *mut u8, layout: std::alloc::Layout) {
32 use std::sync::atomic::Ordering::Relaxed;
33 if !ptr.is_null() {
34 $crate::alloc::FREEED.fetch_add(layout.size(), Relaxed);
35 }
36 $alloc.dealloc(ptr, layout);
37 }
38 unsafe fn realloc(&self, ptr: *mut u8, layout: std::alloc::Layout, new_size: usize) -> *mut u8 {
39 use std::sync::atomic::Ordering::*;
40 if !ptr.is_null() {
41 $crate::alloc::FREEED.fetch_add(layout.size(), Relaxed);
42 }
43 let ptr = $alloc.realloc(ptr, layout, new_size);
44 if !ptr.is_null() {
45 $crate::alloc::ALLOCATED.fetch_add(new_size, Relaxed);
46 }
47 ptr
48 }
49 }
50 };
51}
52
53#[macro_export]
62macro_rules! instrumented_allocator {
63 () => {
64 $crate::wrap_global_allocator!(std::alloc::System);
65 };
66}