use std::alloc::{handle_alloc_error, Layout};
use std::mem::size_of;
use std::ptr::NonNull;
mod alignment;
mod types;
pub use alignment::ALIGNMENT;
pub use types::NativeType;
#[inline]
unsafe fn null_pointer<T: NativeType>() -> NonNull<T> {
NonNull::new_unchecked(ALIGNMENT as *mut T)
}
pub fn allocate_aligned<T: NativeType>(size: usize) -> NonNull<T> {
unsafe {
if size == 0 {
null_pointer()
} else {
let size = size * size_of::<T>();
let layout = Layout::from_size_align_unchecked(size, ALIGNMENT);
let raw_ptr = std::alloc::alloc(layout) as *mut T;
NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
}
}
}
pub fn allocate_aligned_zeroed<T: NativeType>(size: usize) -> NonNull<T> {
unsafe {
if size == 0 {
null_pointer()
} else {
let size = size * size_of::<T>();
let layout = Layout::from_size_align_unchecked(size, ALIGNMENT);
let raw_ptr = std::alloc::alloc_zeroed(layout) as *mut T;
NonNull::new(raw_ptr).unwrap_or_else(|| handle_alloc_error(layout))
}
}
}
pub unsafe fn free_aligned<T: NativeType>(ptr: NonNull<T>, size: usize) {
if ptr != null_pointer() {
let size = size * size_of::<T>();
std::alloc::dealloc(
ptr.as_ptr() as *mut u8,
Layout::from_size_align_unchecked(size, ALIGNMENT),
);
}
}
pub unsafe fn reallocate<T: NativeType>(
ptr: NonNull<T>,
old_size: usize,
new_size: usize,
) -> NonNull<T> {
let old_size = old_size * size_of::<T>();
let new_size = new_size * size_of::<T>();
if ptr == null_pointer() {
return allocate_aligned(new_size);
}
if new_size == 0 {
free_aligned(ptr, old_size);
return null_pointer();
}
let raw_ptr = std::alloc::realloc(
ptr.as_ptr() as *mut u8,
Layout::from_size_align_unchecked(old_size, ALIGNMENT),
new_size,
) as *mut T;
NonNull::new(raw_ptr).unwrap_or_else(|| {
handle_alloc_error(Layout::from_size_align_unchecked(new_size, ALIGNMENT))
})
}