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
//! Memory allocation APIs

use crate::rt;

pub use std::alloc::Layout;

/// Allocate memory with the global allocator.
pub unsafe fn alloc(layout: Layout) -> *mut u8 {
    let ptr = std::alloc::alloc(layout);
    rt::alloc(ptr);
    ptr
}

/// Deallocate memory with the global allocator.
pub unsafe fn dealloc(ptr: *mut u8, layout: Layout) {
    rt::dealloc(ptr);
    std::alloc::dealloc(ptr, layout)
}

/// Track allocations, detecting leaks
#[derive(Debug)]
pub struct Track<T> {
    value: T,
    obj: rt::Allocation,
}

impl<T> Track<T> {
    /// Track a value for leaks
    pub fn new(value: T) -> Track<T> {
        Track {
            value,
            obj: rt::Allocation::new(),
        }
    }

    /// Get a reference to the value
    pub fn get_ref(&self) -> &T {
        &self.value
    }

    /// Get a mutable reference to the value
    pub fn get_mut(&mut self) -> &mut T {
        &mut self.value
    }

    /// Stop tracking the value for leaks
    pub fn into_inner(self) -> T {
        self.value
    }
}