mirror of
https://github.com/phil-opp/blog_os.git
synced 2025-12-16 14:27:49 +00:00
Implement GlobalAlloc for BumpAllocator
This commit is contained in:
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user