Skip to content

deduplicate code between Allocator and GlobalAlloc #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 31, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 15 additions & 29 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,18 +66,17 @@ impl Heap {
pub fn free(&self) -> usize {
critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().free())
}

fn alloc_first_fit(&self, layout: Layout) -> Result<NonNull<u8>, ()> {
critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().allocate_first_fit(layout))
}
}

unsafe impl GlobalAlloc for Heap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
critical_section::with(|cs| {
self.heap
.borrow(cs)
.borrow_mut()
.allocate_first_fit(layout)
.ok()
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
})
self.alloc_first_fit(layout)
.ok()
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
}

unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
Expand All @@ -92,36 +91,23 @@ unsafe impl GlobalAlloc for Heap {

#[cfg(feature = "allocator_api")]
mod allocator_api {
use core::{
alloc::{AllocError, Allocator, Layout},
ptr::NonNull,
};

use crate::Heap;
use core::alloc::{AllocError, Allocator, GlobalAlloc, Layout};
use core::ptr::NonNull;

unsafe impl Allocator for Heap {
unsafe impl Allocator for crate::Heap {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
match layout.size() {
0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
size => critical_section::with(|cs| {
self.heap
.borrow(cs)
.borrow_mut()
.allocate_first_fit(layout)
.map(|allocation| NonNull::slice_from_raw_parts(allocation, size))
.map_err(|_| AllocError)
}),
size => self
.alloc_first_fit(layout)
.map(|allocation| NonNull::slice_from_raw_parts(allocation, size))
.map_err(|_| AllocError),
}
}

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
if layout.size() != 0 {
critical_section::with(|cs| {
self.heap
.borrow(cs)
.borrow_mut()
.deallocate(NonNull::new_unchecked(ptr.as_ptr()), layout)
});
self.dealloc(ptr.as_ptr(), layout);
}
}
}
Expand Down