use crate::Allocator;
use alloc::alloc::Layout;
use core::alloc::GlobalAlloc;
use core::ops::Deref;
use core::ptr::NonNull;
use spin::Mutex;
pub struct LockedAllocator(Mutex<Allocator>);
impl LockedAllocator {
pub const fn empty() -> LockedAllocator {
LockedAllocator(Mutex::new(Allocator::empty()))
}
}
impl Deref for LockedAllocator {
type Target = Mutex<Allocator>;
fn deref(&self) -> &Mutex<Allocator> {
&self.0
}
}
unsafe impl GlobalAlloc for LockedAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.0
.lock()
.allocate(layout)
.ok()
.map_or(0 as *mut u8, |a| a.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.0
.lock()
.deallocate(NonNull::new_unchecked(ptr), layout);
}
}