use std::mem::size_of;
use std::ptr::NonNull;
use std::{
alloc::{handle_alloc_error, Layout},
sync::atomic::AtomicIsize,
};
use crate::types::NativeType;
mod alignment;
pub use alignment::ALIGNMENT;
pub static mut ALLOCATIONS: AtomicIsize = AtomicIsize::new(0);
pub fn total_allocated_bytes() -> isize {
unsafe { ALLOCATIONS.load(std::sync::atomic::Ordering::SeqCst) }
}
#[inline]
pub unsafe fn dangling<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 {
dangling()
} else {
let size = size * size_of::<T>();
ALLOCATIONS.fetch_add(size as isize, std::sync::atomic::Ordering::SeqCst);
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 {
dangling()
} else {
let size = size * size_of::<T>();
ALLOCATIONS.fetch_add(size as isize, std::sync::atomic::Ordering::SeqCst);
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 size != 0 {
let size = size * size_of::<T>();
ALLOCATIONS.fetch_sub(size as isize, std::sync::atomic::Ordering::SeqCst);
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> {
if old_size == 0 {
return allocate_aligned(new_size);
}
if new_size == 0 {
free_aligned(ptr, old_size);
return dangling();
}
let old_size = old_size * size_of::<T>();
let new_size = new_size * size_of::<T>();
ALLOCATIONS.fetch_add(
new_size as isize - old_size as isize,
std::sync::atomic::Ordering::SeqCst,
);
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))
})
}