Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions static-alloc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ all-features = true
[dependencies]
alloc-traits = { path = "../alloc-traits", version = "0.1.0" }
portable-atomic = { version = "1", optional = true, default-features = false }
allocator-api2 = { version = "0.4", optional = true, default-features = false }

[dev-dependencies]
allocator-api2 = { version = "0.4", features = ["std"] }

[features]
alloc = []
Expand Down Expand Up @@ -52,3 +56,8 @@ path = "tests/unsync.rs"
name = "chain"
path = "tests/chain.rs"
required-features = ["nightly_chain"]

[[test]]
name = "allocator-api2"
path = "tests/allocator-api2.rs"
required-features = ["allocator-api2"]
147 changes: 147 additions & 0 deletions static-alloc/src/allocator_api2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
use crate::{
bump::{Bump, BumpSlice, BumpView},
unsync,
};

use allocator_api2::alloc::{AllocError, Allocator, Layout};
use core::ptr::NonNull;

unsafe impl<T> Allocator for Bump<T> {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
Allocator::allocate(&self.as_view(), layout)
}

unsafe fn deallocate(&self, _: NonNull<u8>, _: Layout) {}

unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// Safety: passing along requirements. These two allocators serve the same allocations, a
// property we permit for these two of our own types.
unsafe { Allocator::shrink(&self.as_view(), ptr, old_layout, new_layout) }
}
}

unsafe impl Allocator for BumpSlice {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
Allocator::allocate(&self.as_view(), layout)
}

unsafe fn deallocate(&self, _: NonNull<u8>, _: Layout) {}

unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// Safety: passing along requirements. These two allocators serve the same allocations, a
// property we permit for these two of our own types.
unsafe { Allocator::shrink(&self.as_view(), ptr, old_layout, new_layout) }
}
}

unsafe impl Allocator for BumpView<'_> {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
let len = layout.size();
match self.get_layout(layout) {
None => Err(AllocError),
Some(allocation) => Ok(NonNull::slice_from_raw_parts(allocation.ptr, len)),
}
}

unsafe fn deallocate(&self, _: NonNull<u8>, _: Layout) {}

unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// Safety: Caller guarantees `ptr` was allocated from `self` (or equivalent, for transitive
// use of this) which requires it to be valid and described by `old_layout`.
unsafe { shrink_in_place(ptr, old_layout, new_layout) }
}
}

unsafe impl<T> Allocator for unsync::Bump<T> {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
<unsync::BumpSlice as Allocator>::allocate(self, layout)
}

unsafe fn deallocate(&self, _: NonNull<u8>, _: Layout) {}

unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// Safety: passing along requirements. These two allocators serve the same allocations, a
// property we permit for these two of our own types.
unsafe { <unsync::BumpSlice as Allocator>::shrink(self, ptr, old_layout, new_layout) }
}
}

unsafe impl Allocator for unsync::BumpSlice {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
let len = layout.size();
match self.alloc(layout) {
None => Err(AllocError),
Some(allocation) => Ok(NonNull::slice_from_raw_parts(allocation, len)),
}
}

unsafe fn deallocate(&self, _: NonNull<u8>, _: Layout) {}

unsafe fn shrink(
&self,
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
// Safety: Caller guarantees `ptr` was allocated from `self` (or equivalent, for transitive
// use of this) which requires it to be valid and described by `old_layout`.
unsafe { shrink_in_place(ptr, old_layout, new_layout) }
}
}

/// Safety: caller must only call this on `ptr` point to a valid allocation with the fitting layout
/// `old_layout`. Returns a derived pointer into the same allocation on success.
unsafe fn shrink_in_place(
ptr: NonNull<u8>,
old_layout: Layout,
new_layout: Layout,
) -> Result<NonNull<[u8]>, AllocError> {
debug_assert!(new_layout.size() <= old_layout.size());
let len = new_layout.size();

let offset = ptr.align_offset(new_layout.align());

if offset > 0 {
if old_layout
.size()
.checked_sub(offset)
.is_none_or(|n| n < len)
{
// Won't fit in-place. Sorry.
return Err(AllocError);
}

// Safety: in-bounds as we just verified that old layout has at least as many bytes as
// offset, and the caller was required to pass a live allocation with corresponding
// layout; implying that it also has that many bytes.
let dst = unsafe { ptr.byte_add(offset) };
// Safety: just verified that layout has at least `len` bytes after the offset so `dst`
// also has provenance according to the caller's requirements.
unsafe { ptr.copy_to(dst, len) };
dst
} else {
ptr
};

Ok(NonNull::slice_from_raw_parts(ptr, len))
}
6 changes: 3 additions & 3 deletions static-alloc/src/bump.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ pub struct BumpSlice {
///
/// Note: You might think that we can
#[derive(Clone, Copy)]
struct BumpView<'lt> {
pub(crate) struct BumpView<'lt> {
header: &'lt Header,
storage: &'lt UnsafeCell<[MaybeUninit<u8>]>,
}
Expand Down Expand Up @@ -564,7 +564,7 @@ impl<T> Bump<T> {
self.header = Header::empty();
}

fn as_view(&self) -> BumpView<'_> {
pub(crate) fn as_view(&self) -> BumpView<'_> {
BumpView {
header: &self.header,
storage: {
Expand Down Expand Up @@ -1028,7 +1028,7 @@ impl BumpSlice {
self.header = Header::empty();
}

fn as_view(&self) -> BumpView<'_> {
pub(crate) fn as_view(&self) -> BumpView<'_> {
BumpView {
header: &self.header,
storage: &self.storage,
Expand Down
3 changes: 3 additions & 0 deletions static-alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@
#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "allocator-api2")]
mod allocator_api2;

pub mod bump;
pub use bump::Bump;
pub mod leaked;
Expand Down
38 changes: 38 additions & 0 deletions static-alloc/tests/allocator-api2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
use allocator_api2 as astd;
use static_alloc::{Bump, unsync};

#[test]
fn local_vector() {
let storage = Bump::<[u8; 128]>::uninit();

let mut v = astd::vec::Vec::<u8, _>::new_in(&storage);
assert_eq!(v.len(), 0);
v.extend(0..64);
assert_eq!(v.len(), 64);

assert!(
v.try_reserve(64).is_err(),
"Reserved more space than available"
);

let _ = v.push_within_capacity(0);
assert!(v.capacity() <= 128);
}

#[test]
fn unsync_vector() {
let storage = unsync::Bump::<[u8; 128]>::uninit();

let mut v = astd::vec::Vec::<u8, _>::new_in(&storage);
assert_eq!(v.len(), 0);
v.extend(0..64);
assert_eq!(v.len(), 64);

assert!(
v.try_reserve(64).is_err(),
"Reserved more space than available"
);

let _ = v.push_within_capacity(0);
assert!(v.capacity() <= 128);
}
Loading