Skip to content

Commit caf5801

Browse files
committed
Implement the Allocator trait from the unstable allocator_api
1 parent 4f1f0dc commit caf5801

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

Cargo.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ license = "MIT OR Apache-2.0"
2323
name = "embedded-alloc"
2424
version = "0.5.0"
2525

26+
[features]
27+
allocator_api = []
28+
2629
[dependencies]
2730
critical-section = "1.0"
2831

rust-toolchain

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
nightly

src/lib.rs

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
#![doc = include_str!("../README.md")]
22
#![no_std]
3+
#![cfg_attr(
4+
feature = "allocator_api",
5+
feature(allocator_api, nonnull_slice_from_raw_parts, alloc_layout_extra)
6+
)]
37

48
use core::alloc::{GlobalAlloc, Layout};
59
use core::cell::RefCell;
@@ -88,3 +92,40 @@ unsafe impl GlobalAlloc for Heap {
8892
});
8993
}
9094
}
95+
96+
#[cfg(feature = "allocator_api")]
97+
mod allocator_api {
98+
use core::{
99+
alloc::{AllocError, Allocator, Layout},
100+
ptr::NonNull,
101+
};
102+
103+
use crate::Heap;
104+
105+
unsafe impl Allocator for Heap {
106+
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
107+
match layout.size() {
108+
0 => Ok(NonNull::slice_from_raw_parts(layout.dangling(), 0)),
109+
size => critical_section::with(|cs| {
110+
self.heap
111+
.borrow(cs)
112+
.borrow_mut()
113+
.allocate_first_fit(layout)
114+
.map(|allocation| NonNull::slice_from_raw_parts(allocation, size))
115+
.map_err(|_| AllocError)
116+
}),
117+
}
118+
}
119+
120+
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
121+
if layout.size() != 0 {
122+
critical_section::with(|cs| {
123+
self.heap
124+
.borrow(cs)
125+
.borrow_mut()
126+
.deallocate(NonNull::new_unchecked(ptr.as_ptr()), layout)
127+
});
128+
}
129+
}
130+
}
131+
}

0 commit comments

Comments
 (0)