Skip to main content

CUSTOM_ALLOCATOR_MODULE_TEMPLATE

Constant CUSTOM_ALLOCATOR_MODULE_TEMPLATE 

Source
const CUSTOM_ALLOCATOR_MODULE_TEMPLATE: &str = "mod custom_allocator {\n    use core::alloc::{GlobalAlloc, Layout};\n    use core::cell::UnsafeCell;\n    use core::ptr::null_mut;\n\n    struct CustomBumpAllocator {\n        state: UnsafeCell<State>,\n    }\n\n    struct State {\n        start: usize,\n        end: usize,\n        current: usize,\n        initialized: bool,\n    }\n\n    unsafe impl Sync for CustomBumpAllocator {}\n\n    impl CustomBumpAllocator {\n        const fn uninit() -> Self {\n            Self {\n                state: UnsafeCell::new(State {\n                    start: 0,\n                    end: 0,\n                    current: 0,\n                    initialized: false,\n                }),\n            }\n        }\n\n        unsafe fn init(&self, start: *mut usize, end: *mut usize) {\n            let state = &mut *self.state.get();\n            state.start = start as usize;\n            state.end = end as usize;\n            state.current = state.start;\n            state.initialized = true;\n        }\n\n        unsafe fn alloc_inner(&self, layout: Layout) -> *mut u8 {\n            let state = &mut *self.state.get();\n            if !state.initialized {\n                return null_mut();\n            }\n\n            let aligned = (state.current + layout.align() - 1) & !(layout.align() - 1);\n            let next = aligned.saturating_add(layout.size());\n            if next > state.end {\n                return null_mut();\n            }\n\n            state.current = next;\n            aligned as *mut u8\n        }\n    }\n\n    unsafe impl GlobalAlloc for CustomBumpAllocator {\n        unsafe fn alloc(&self, layout: Layout) -> *mut u8 {\n            self.alloc_inner(layout)\n        }\n\n        unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) {}\n    }\n\n    #[global_allocator]\n    static GLOBAL_ALLOCATOR: CustomBumpAllocator = CustomBumpAllocator::uninit();\n\n    pub fn init(start: *mut usize, end: *mut usize) {\n        unsafe { GLOBAL_ALLOCATOR.init(start, end) };\n    }\n}\n";