diff --git a/src/allocator/bump.rs b/src/allocator/bump.rs index 5644dab5..355daef3 100644 --- a/src/allocator/bump.rs +++ b/src/allocator/bump.rs @@ -1,3 +1,7 @@ +use super::{align_up, Locked}; +use alloc::alloc::{GlobalAlloc, Layout}; +use core::ptr; + pub struct BumpAllocator { heap_start: usize, heap_end: usize, @@ -26,3 +30,29 @@ impl BumpAllocator { self.next = heap_start; } } + +unsafe impl GlobalAlloc for Locked { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let mut bump = self.lock(); // get a mutable reference + + let alloc_start = align_up(bump.next, layout.align()); + let alloc_end = alloc_start + layout.size(); + + if alloc_end > bump.heap_end { + ptr::null_mut() // out of memory + } else { + bump.next = alloc_end; + bump.allocations += 1; + alloc_start as *mut u8 + } + } + + unsafe fn dealloc(&self, _ptr: *mut u8, _layout: Layout) { + let mut bump = self.lock(); // get a mutable reference + + bump.allocations -= 1; + if bump.allocations == 0 { + bump.next = bump.heap_start; + } + } +}