use std::alloc::{handle_alloc_error, Layout};
use std::fmt::{Debug, Formatter};
use std::panic::RefUnwindSafe;
use std::ptr::NonNull;
use std::sync::Arc;
mod alignment;
pub use alignment::ALIGNMENT;
#[inline]
fn dangling_ptr() -> NonNull<u8> {
unsafe { NonNull::new_unchecked(ALIGNMENT as *mut u8) }
}
pub fn allocate_aligned(size: usize) -> NonNull<u8> {
unsafe {
if size == 0 {
dangling_ptr()
} else {
let layout = Layout::from_size_align_unchecked(size, ALIGNMENT);
let raw_ptr = std::alloc::alloc(layout);
NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
}
}
}
pub fn allocate_aligned_zeroed(size: usize) -> NonNull<u8> {
unsafe {
if size == 0 {
dangling_ptr()
} else {
let layout = Layout::from_size_align_unchecked(size, ALIGNMENT);
let raw_ptr = std::alloc::alloc_zeroed(layout);
NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
}
}
}
pub unsafe fn free_aligned(ptr: NonNull<u8>, size: usize) {
if size != 0 {
std::alloc::dealloc(
ptr.as_ptr() as *mut u8,
Layout::from_size_align_unchecked(size, ALIGNMENT),
);
}
}
pub unsafe fn reallocate(
ptr: NonNull<u8>,
old_size: usize,
new_size: usize,
) -> NonNull<u8> {
if old_size == 0 {
return allocate_aligned(new_size);
}
if new_size == 0 {
free_aligned(ptr, old_size);
return dangling_ptr();
}
let raw_ptr = std::alloc::realloc(
ptr.as_ptr() as *mut u8,
Layout::from_size_align_unchecked(old_size, ALIGNMENT),
new_size,
);
NonNull::new(raw_ptr).unwrap_or_else(|| {
handle_alloc_error(Layout::from_size_align_unchecked(new_size, ALIGNMENT))
})
}
pub trait Allocation: RefUnwindSafe + Send + Sync {}
impl<T: RefUnwindSafe + Send + Sync> Allocation for T {}
pub(crate) enum Deallocation {
Arrow(usize),
Custom(Arc<dyn Allocation>),
}
impl Debug for Deallocation {
fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
match self {
Deallocation::Arrow(capacity) => {
write!(f, "Deallocation::Arrow {{ capacity: {} }}", capacity)
}
Deallocation::Custom(_) => {
write!(f, "Deallocation::Custom {{ capacity: unknown }}")
}
}
}
}