From a5c50e74084e6cf08801dff48e90c378e8ce25f1 Mon Sep 17 00:00:00 2001 From: Philipp Oppermann Date: Fri, 10 Jan 2020 11:52:04 +0100 Subject: [PATCH] Implement GlobalAlloc for LinkedListAllocator --- src/allocator/linked_list.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/allocator/linked_list.rs b/src/allocator/linked_list.rs index 80c69131..079f7cdb 100644 --- a/src/allocator/linked_list.rs +++ b/src/allocator/linked_list.rs @@ -1,5 +1,6 @@ -use super::align_up; -use core::mem; +use super::{align_up, Locked}; +use alloc::alloc::{GlobalAlloc, Layout}; +use core::{mem, ptr}; struct ListNode { size: usize, @@ -103,3 +104,29 @@ impl LinkedListAllocator { Ok(alloc_start) } } + +unsafe impl GlobalAlloc for Locked { + 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) + } +}