use super::Locked;
use alloc::alloc::{GlobalAlloc, Layout};
use core::{ptr, ptr::NonNull};
use linked_list_allocator::Heap;
pub struct LinkedListAllocator {
heap: Heap,
heap_start: usize,
heap_end: usize,
}
impl LinkedListAllocator {
pub const fn new() -> Self {
Self {
heap: Heap::empty(),
heap_start: 0,
heap_end: 0,
}
}
pub unsafe fn init(&mut self, heap_start: usize, heap_size: usize) {
self.heap_start = heap_start;
self.heap_end = heap_start + heap_size;
unsafe {
self.heap.init(heap_start as *mut u8, heap_size);
}
}
fn contains_allocation(&self, ptr: *mut u8, layout: Layout) -> bool {
if ptr.is_null() || layout.size() == 0 {
return false;
}
let addr = ptr as usize;
let Some(end) = addr.checked_add(layout.size()) else {
return false;
};
addr >= self.heap_start && end <= self.heap_end
}
}
impl Default for LinkedListAllocator {
fn default() -> Self {
Self::new()
}
}
unsafe impl GlobalAlloc for Locked<LinkedListAllocator> {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
crate::interrupts::without_interrupts(|| {
let mut allocator = self.lock();
match allocator.heap.allocate_first_fit(layout) {
Ok(ptr) => ptr.as_ptr(),
Err(_) => ptr::null_mut(),
}
})
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
crate::interrupts::without_interrupts(|| {
let mut allocator = self.lock();
if !allocator.contains_allocation(ptr, layout) {
return;
}
let Some(ptr) = NonNull::new(ptr) else {
return;
};
unsafe {
allocator.heap.deallocate(ptr, layout);
}
});
}
}