Skip to content

Commit

Permalink
Use allocator-api through allocator-api2 crate
Browse files Browse the repository at this point in the history
  • Loading branch information
zakarumych committed May 10, 2023
1 parent faac800 commit 98f86e5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ name = "try_alloc"
path = "tests/try_alloc.rs"
harness = false

[dependencies]
allocator-api2 = { version = "0.2.6" }

[dev-dependencies]
quickcheck = "1.0.3"
criterion = "0.3.6"
Expand All @@ -39,7 +42,7 @@ rand = "0.8.5"
default = []
collections = []
boxed = []
allocator_api = []
allocator_api = ["allocator-api2/nightly"]

# [profile.bench]
# debug = true
23 changes: 12 additions & 11 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,7 @@
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![no_std]
#![cfg_attr(
feature = "allocator_api",
feature(allocator_api, nonnull_slice_from_raw_parts)
)]
#![cfg_attr(feature = "allocator_api", feature(allocator_api))]

#[doc(hidden)]
pub extern crate alloc as core_alloc;
Expand All @@ -25,9 +22,8 @@ use core::mem;
use core::ptr::{self, NonNull};
use core::slice;
use core::str;
use core_alloc::alloc::{alloc, dealloc, Layout};
#[cfg(feature = "allocator_api")]
use core_alloc::alloc::{AllocError, Allocator};

use allocator_api2::alloc::{alloc, dealloc, AllocError, Allocator, Layout};

pub use alloc::AllocErr;

Expand Down Expand Up @@ -1886,11 +1882,12 @@ unsafe impl<'a> alloc::Alloc for &'a Bump {
}
}

#[cfg(feature = "allocator_api")]
unsafe impl<'a> Allocator for &'a Bump {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
self.try_alloc_layout(layout)
.map(|p| NonNull::slice_from_raw_parts(p, layout.size()))
.map(|p| unsafe {
NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(p.as_ptr(), layout.size()))
})
.map_err(|_| AllocError)
}

Expand All @@ -1905,7 +1902,9 @@ unsafe impl<'a> Allocator for &'a Bump {
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
Bump::shrink(self, ptr, old_layout, new_layout)
.map(|p| NonNull::slice_from_raw_parts(p, new_layout.size()))
.map(|p| unsafe {
NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(p.as_ptr(), new_layout.size()))
})
.map_err(|_| AllocError)
}

Expand All @@ -1916,7 +1915,9 @@ unsafe impl<'a> Allocator for &'a Bump {
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
Bump::grow(self, ptr, old_layout, new_layout)
.map(|p| NonNull::slice_from_raw_parts(p, new_layout.size()))
.map(|p| unsafe {
NonNull::new_unchecked(ptr::slice_from_raw_parts_mut(p.as_ptr(), new_layout.size()))
})
.map_err(|_| AllocError)
}

Expand Down

0 comments on commit 98f86e5

Please sign in to comment.