Skip to content

Implement the Allocator trait from the unstable allocator_api #61

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 10 commits into from
Oct 29, 2023
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

### Added

- Implemented [`Allocator`] for `Heap` with the `allocator_api` crate feature.
This feature requires a nightly toolchain for the unstable [`allocator_api`]
compiler feature.

[`Allocator`]: https://doc.rust-lang.org/core/alloc/trait.Allocator.html
[`allocator_api`]: https://doc.rust-lang.org/beta/unstable-book/library-features/allocator-api.html

### Changed

- Updated `linked_list_allocator` dependency to 0.10.5, which allows
compiling with stable rust.

Expand Down
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ license = "MIT OR Apache-2.0"
name = "embedded-alloc"
version = "0.5.0"

[features]
allocator_api = []

[dependencies]
critical-section = "1.0"

Expand Down
38 changes: 38 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#![doc = include_str!("../README.md")]
#![no_std]
#![cfg_attr(feature = "allocator_api", feature(allocator_api, alloc_layout_extra))]

use core::alloc::{GlobalAlloc, Layout};
use core::cell::RefCell;
Expand Down Expand Up @@ -88,3 +89,40 @@ unsafe impl GlobalAlloc for Heap {
});
}
}

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

use crate::Heap;

unsafe impl Allocator for 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)
}),
}
}

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)
});
}
}
}
}