Implement GlobalAlloc for BumpAllocator

This commit is contained in:
Philipp Oppermann
2020-01-09 15:35:03 +01:00
parent 08d2289dad
commit e87044a7ee

View File

@@ -1,3 +1,7 @@
use super::{align_up, Locked};
use alloc::alloc::{GlobalAlloc, Layout};
use core::ptr;
pub struct BumpAllocator { pub struct BumpAllocator {
heap_start: usize, heap_start: usize,
heap_end: usize, heap_end: usize,
@@ -26,3 +30,29 @@ impl BumpAllocator {
self.next = heap_start; self.next = heap_start;
} }
} }
unsafe impl GlobalAlloc for Locked<BumpAllocator> {
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;
}
}
}