Skip to content

Commit 0f4e3fe

Browse files
committed
deduplicate code between Allocator and GlobalAlloc
1 parent e37e935 commit 0f4e3fe

File tree

1 file changed

+14
-29
lines changed

1 file changed

+14
-29
lines changed

src/lib.rs

Lines changed: 14 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -66,18 +66,17 @@ impl Heap {
6666
pub fn free(&self) -> usize {
6767
critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().free())
6868
}
69+
70+
unsafe fn alloc_first_fit(&self, layout: Layout) -> Result<NonNull<u8>, ()> {
71+
critical_section::with(|cs| self.heap.borrow(cs).borrow_mut().allocate_first_fit(layout))
72+
}
6973
}
7074

7175
unsafe impl GlobalAlloc for Heap {
7276
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
73-
critical_section::with(|cs| {
74-
self.heap
75-
.borrow(cs)
76-
.borrow_mut()
77-
.allocate_first_fit(layout)
78-
.ok()
79-
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
80-
})
77+
self.alloc_first_fit(layout)
78+
.ok()
79+
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
8180
}
8281

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

9392
#[cfg(feature = "allocator_api")]
9493
mod allocator_api {
95-
use core::{
96-
alloc::{AllocError, Allocator, Layout},
97-
ptr::NonNull,
98-
};
99-
100-
use crate::Heap;
94+
use core::alloc::{AllocError, Allocator, Layout};
10195

102-
unsafe impl Allocator for Heap {
96+
unsafe impl Allocator for crate::Heap {
10397
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
10498
match layout.size() {
10599
0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
106-
size => critical_section::with(|cs| {
107-
self.heap
108-
.borrow(cs)
109-
.borrow_mut()
110-
.allocate_first_fit(layout)
111-
.map(|allocation| NonNull::slice_from_raw_parts(allocation, size))
112-
.map_err(|_| AllocError)
113-
}),
100+
size => self
101+
.alloc_first_fit(layout)
102+
.map(|allocation| NonNull::slice_from_raw_parts(allocation, size))
103+
.map_err(|_| AllocError),
114104
}
115105
}
116106

117107
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
118108
if layout.size() != 0 {
119-
critical_section::with(|cs| {
120-
self.heap
121-
.borrow(cs)
122-
.borrow_mut()
123-
.deallocate(NonNull::new_unchecked(ptr.as_ptr()), layout)
124-
});
109+
self.dealloc(ptr.as_ptr(), layout);
125110
}
126111
}
127112
}

0 commit comments

Comments
 (0)