use std::alloc::Layout;
use crate::{
header::{AllocationHeader, HEADER_SIZE},
AllocationError,
};
pub fn alloc(size: usize) -> Result<*mut u8, AllocationError> {
let size = size
.checked_add(HEADER_SIZE)
.ok_or(AllocationError::ArithmeticError)?
.checked_next_multiple_of(HEADER_SIZE)
.ok_or(AllocationError::ArithmeticError)?;
let layout = Layout::from_size_align(size, HEADER_SIZE)?;
let ptr = unsafe { std::alloc::alloc(layout) };
if ptr.is_null() {
return Err(AllocationError::OutOfMemory);
}
let header: &mut AllocationHeader = unsafe { &mut *ptr.cast() };
header.mark_as_used();
header.set_size(size);
Ok(unsafe { ptr.add(HEADER_SIZE) })
}