Skip to content

Commit

Permalink
Merge pull request #80 from rust-embedded/dedupe-code
Browse files Browse the repository at this point in the history
deduplicate code between Allocator and GlobalAlloc
  • Loading branch information
newAM committed Oct 31, 2023
2 parents 11a5cc8 + 08b99fd commit 38d425d
Showing 1 changed file with 15 additions and 29 deletions.
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

0 comments on commit 38d425d

Please sign in to comment.