use core::mem;
use core::ops::DerefMut;
use core::{
alloc::{GlobalAlloc, Layout},
cell::RefCell,
};
thread_local! {
pub static TRACE_ALLOCATOR: RefCell<bool> = RefCell::new(false);
}
#[non_exhaustive]
pub struct TracingAllocator<A> {
pub allocator: A,
}
impl<A> TracingAllocator<A> {
pub const fn new(allocator: A) -> Self {
Self { allocator }
}
}
unsafe impl<A> GlobalAlloc for TracingAllocator<A>
where
A: GlobalAlloc,
{
#[track_caller]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let ptr = self.allocator.alloc(layout);
let _ = TRACE_ALLOCATOR.try_with(|guard| {
if let Ok(mut trace_allocations) = guard.try_borrow_mut() {
if mem::replace(trace_allocations.deref_mut(), false) {
tracing::trace! {
addr = ptr as usize,
size = layout.size(),
"alloc",
};
*trace_allocations = true;
}
drop(trace_allocations);
}
});
ptr
}
#[track_caller]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.allocator.dealloc(ptr, layout);
let _ = TRACE_ALLOCATOR.try_with(|guard| {
if let Ok(mut trace_allocations) = guard.try_borrow_mut() {
if mem::replace(trace_allocations.deref_mut(), false) {
tracing::trace! {
addr = ptr as usize,
size = layout.size(),
"dealloc",
};
*trace_allocations = true;
}
drop(guard);
}
});
}
}
pub fn trace_allocations<F: FnOnce() -> R, R>(f: F) -> R {
TRACE_ALLOCATOR.with(|guard| {
let mut previous_state = false;
if let Ok(mut trace_allocations) = guard.try_borrow_mut() {
previous_state = mem::replace(&mut trace_allocations, true);
}
let res = f();
if let Ok(mut trace_allocations) = guard.try_borrow_mut() {
*trace_allocations = previous_state;
}
res
})
}
pub fn ignore_allocations<F: FnOnce() -> R, R>(f: F) -> R {
TRACE_ALLOCATOR.with(|guard| {
let mut previous_state = true;
if let Ok(mut trace_allocations) = guard.try_borrow_mut() {
previous_state = mem::replace(&mut trace_allocations, false);
}
let res = f();
if let Ok(mut trace_allocations) = guard.try_borrow_mut() {
*trace_allocations = previous_state;
}
res
})
}