1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::alloc::{GlobalAlloc, Layout, System};
use crate::get_global_tracker;
use crate::token::get_active_allocation_group;
pub struct Allocator<A> {
    inner: A,
}
impl<A> Allocator<A> {
    
    pub const fn from_allocator(allocator: A) -> Self {
        Self { inner: allocator }
    }
}
impl Allocator<System> {
    
    pub const fn system() -> Allocator<System> {
        Self::from_allocator(System)
    }
}
impl Default for Allocator<System> {
    fn default() -> Self {
        Self::from_allocator(System)
    }
}
unsafe impl<A: GlobalAlloc> GlobalAlloc for Allocator<A> {
    #[track_caller]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        let size = layout.size();
        let ptr = self.inner.alloc(layout);
        let addr = ptr as usize;
        if let Some(tracker) = get_global_tracker() {
            if let Some(group) = get_active_allocation_group() {
                tracker.allocated(addr, size, group.id(), group.tags())
            }
        }
        ptr
    }
    #[track_caller]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        let addr = ptr as usize;
        self.inner.dealloc(ptr, layout);
        if let Some(tracker) = get_global_tracker() {
            tracker.deallocated(addr)
        }
    }
}