use core::cell::RefCell;
use core::ptr::NonNull;
use super::alloc::layout::Layout;
use super::alloc::Heap;
use cortex_m::interrupt::Mutex;
pub struct CortexMHeap {
heap: Mutex<RefCell<Heap>>,
}
impl CortexMHeap {
pub fn empty() -> CortexMHeap {
CortexMHeap {
heap: Mutex::new(RefCell::new(Heap::empty())),
}
}
pub unsafe fn init(&self, start_addr: usize, size: usize) {
cortex_m::interrupt::free(|cs| {
self.heap.borrow(cs).borrow_mut().init(start_addr, size);
});
}
pub fn used(&self) -> usize {
cortex_m::interrupt::free(|cs| self.heap.borrow(cs).borrow_mut().used())
}
pub fn free(&self) -> usize {
cortex_m::interrupt::free(|cs| self.heap.borrow(cs).borrow_mut().free())
}
pub unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
cortex_m::interrupt::free(|cs| {
self.heap
.borrow(cs)
.borrow_mut()
.allocate_first_fit(layout)
.ok()
.map_or(core::ptr::null_mut::<u8>(), |allocation| {
allocation.as_ptr()
})
})
}
pub unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
cortex_m::interrupt::free(|cs| {
self.heap
.borrow(cs)
.borrow_mut()
.deallocate(NonNull::new_unchecked(ptr), layout)
});
}
}