extern crate alloc_no_stdlib as alloc;
pub use self::alloc::{
AllocatedStackMemory, Allocator, SliceWrapper, SliceWrapperMut, StackAllocator,
};
#[cfg(test)]
pub(crate) use self::alloc::{
bzero, declare_stack_allocator_struct, define_allocator_memory_pool,
define_stack_allocator_traits, static_array,
};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct AllocError;
impl core::fmt::Display for AllocError {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.write_str("the allocator returned fewer elements than requested")
}
}
#[cfg(feature = "std")]
impl std::error::Error for AllocError {}
pub struct CheckedAllocator<A>(pub A);
impl<A> CheckedAllocator<A> {
pub fn try_alloc_cell<T>(&mut self, len: usize) -> Result<A::AllocatedMemory, AllocError>
where
A: Allocator<T>,
{
try_alloc_cell(&mut self.0, len)
}
pub fn free_cell<T>(&mut self, memory: A::AllocatedMemory)
where
A: Allocator<T>,
{
if !memory.slice().is_empty() {
self.0.free_cell(memory);
}
}
}
#[allow(clippy::disallowed_methods)]
pub(crate) fn try_alloc_cell<T, A: Allocator<T>>(
alloc: &mut A,
len: usize,
) -> Result<A::AllocatedMemory, AllocError> {
if len == 0 {
return Ok(alloc_default::<T, A>());
}
let memory = alloc.alloc_cell(len);
if memory.slice().len() < len {
if !memory.slice().is_empty() {
alloc.free_cell(memory);
}
return Err(AllocError);
}
Ok(memory)
}
pub(crate) fn try_copy_slice<T: Copy, A: Allocator<T>>(
alloc: &mut A,
data: &[T],
) -> Result<A::AllocatedMemory, AllocError> {
let mut memory = try_alloc_cell(alloc, data.len())?;
if memory.slice().len() != data.len() {
alloc.free_cell(memory);
return Err(AllocError);
}
memory.slice_mut().copy_from_slice(data);
Ok(memory)
}
pub(crate) fn alloc_default<T, A: Allocator<T>>() -> A::AllocatedMemory {
A::AllocatedMemory::default()
}
#[cfg(test)]
mod tests {
use super::{AllocError, AllocatedStackMemory, Allocator, CheckedAllocator, SliceWrapper};
struct TestAllocator<'a>(&'a mut [u8]);
impl<'a> Allocator<u8> for TestAllocator<'a> {
type AllocatedMemory = AllocatedStackMemory<'a, u8>;
fn alloc_cell(&mut self, len: usize) -> Self::AllocatedMemory {
assert_ne!(len, 0);
if self.0.len() == len {
AllocatedStackMemory {
mem: core::mem::take(&mut self.0),
}
} else {
Self::AllocatedMemory::default()
}
}
fn free_cell(&mut self, memory: Self::AllocatedMemory) {
assert!(!memory.slice().is_empty());
self.0 = memory.mem;
}
}
#[test]
fn checked_allocation_handles_empty_requests_and_failures() {
let mut backing = [0; 4];
let mut alloc = CheckedAllocator(TestAllocator(&mut backing));
let empty = alloc.try_alloc_cell(0).unwrap();
assert!(empty.slice().is_empty());
alloc.free_cell(empty);
assert_eq!(alloc.try_alloc_cell(5).err(), Some(AllocError));
let memory = alloc.try_alloc_cell(4).unwrap();
assert_eq!(memory.slice().len(), 4);
assert_eq!(alloc.try_alloc_cell(4).err(), Some(AllocError));
alloc.free_cell(memory);
assert!(alloc.try_alloc_cell(4).is_ok());
}
}