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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#![feature(auto_traits, negative_impls)]
#![feature(local_key_cell_methods)]

use crate::mem::allocator::StableMemoryAllocator;
use crate::primitive::s_unsafe_cell::SUnsafeCell;
use ic_cdk::print;
use primitive::s_slice::SSlice;
use utils::mem_context::OutOfMemory;

pub mod collections;
pub mod mem;
pub mod primitive;
pub mod utils;

static mut STABLE_MEMORY_ALLOCATOR: Option<SSlice<StableMemoryAllocator>> = None;

pub fn init_allocator(offset: u64) {
    unsafe {
        if STABLE_MEMORY_ALLOCATOR.is_none() {
            let allocator = SSlice::<StableMemoryAllocator>::init(offset);

            STABLE_MEMORY_ALLOCATOR = Some(allocator)
        } else {
            unreachable!("StableMemoryAllocator can only be initialized once");
        }
    }
}

pub fn reinit_allocator(offset: u64) {
    unsafe {
        if STABLE_MEMORY_ALLOCATOR.is_none() {
            let allocator = SSlice::<StableMemoryAllocator>::reinit(offset)
                .expect("Unable to reinit StableMemoryAllocator");

            STABLE_MEMORY_ALLOCATOR = Some(allocator)
        } else {
            unreachable!("StableMemoryAllocator can only be initialized once")
        }
    }
}

fn get_allocator() -> SSlice<StableMemoryAllocator> {
    unsafe { STABLE_MEMORY_ALLOCATOR.as_ref().unwrap().clone() }
}

pub fn allocate<T>(size: usize) -> Result<SSlice<T>, OutOfMemory> {
    get_allocator().allocate(size)
}

pub fn deallocate<T>(membox: SSlice<T>) {
    get_allocator().deallocate(membox)
}

pub fn reallocate<T>(membox: SSlice<T>, new_size: usize) -> Result<SSlice<T>, OutOfMemory> {
    get_allocator().reallocate(membox, new_size)
}

pub fn reset() {
    get_allocator().reset()
}

pub fn get_allocated_size() -> u64 {
    get_allocator().get_allocated_size()
}

pub fn get_free_size() -> u64 {
    get_allocator().get_free_size()
}

pub fn _set_custom_data_ptr(idx: usize, data_ptr: u64) {
    get_allocator().set_custom_data_ptr(idx, data_ptr)
}

pub fn _get_custom_data_ptr(idx: usize) -> u64 {
    get_allocator().get_custom_data_ptr(idx)
}

pub fn _debug_print_allocator() {
    print(format!("{:?}", get_allocator()))
}