mirror of
https://github.com/phil-opp/blog_os.git
synced 2025-12-16 14:27:49 +00:00
Implement GlobalAlloc for LinkedListAllocator
This commit is contained in:
@@ -1,5 +1,6 @@
|
|||||||
use super::align_up;
|
use super::{align_up, Locked};
|
||||||
use core::mem;
|
use alloc::alloc::{GlobalAlloc, Layout};
|
||||||
|
use core::{mem, ptr};
|
||||||
|
|
||||||
struct ListNode {
|
struct ListNode {
|
||||||
size: usize,
|
size: usize,
|
||||||
@@ -103,3 +104,29 @@ impl LinkedListAllocator {
|
|||||||
Ok(alloc_start)
|
Ok(alloc_start)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
unsafe impl GlobalAlloc for Locked<LinkedListAllocator> {
|
||||||
|
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||||
|
// perform layout adjustments
|
||||||
|
let (size, align) = LinkedListAllocator::size_align(layout);
|
||||||
|
let mut allocator = self.inner.lock();
|
||||||
|
|
||||||
|
if let Some((region, alloc_start)) = allocator.find_region(size, align) {
|
||||||
|
let alloc_end = alloc_start + size;
|
||||||
|
let excess_size = region.end_addr() - alloc_end;
|
||||||
|
if excess_size > 0 {
|
||||||
|
allocator.add_free_region(alloc_end, excess_size);
|
||||||
|
}
|
||||||
|
alloc_start as *mut u8
|
||||||
|
} else {
|
||||||
|
ptr::null_mut()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||||
|
// perform layout adjustments
|
||||||
|
let (size, _) = LinkedListAllocator::size_align(layout);
|
||||||
|
|
||||||
|
self.inner.lock().add_free_region(ptr as usize, size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user