use std::alloc::Layout;
pub const ALLOCATE_SYMBOL: &str = "__lehit_allocate";
pub const DEALLOCATE_SYMBOL: &str = "__lehit_deallocate";
#[derive(Debug, Clone, Copy)]
pub struct RuntimeAllocator {
pub(crate) allocate: unsafe extern "C" fn(size: usize, align: usize) -> *mut u8,
pub(crate) deallocate: unsafe extern "C" fn(pointer: *mut u8, size: usize, align: usize),
}
impl RuntimeAllocator {
pub const unsafe fn new(
allocate: unsafe extern "C" fn(usize, usize) -> *mut u8,
deallocate: unsafe extern "C" fn(*mut u8, usize, usize),
) -> Self {
Self {
allocate,
deallocate,
}
}
}
impl Default for RuntimeAllocator {
fn default() -> Self {
unsafe { Self::new(default_allocate, default_deallocate) }
}
}
unsafe extern "C" fn default_allocate(size: usize, align: usize) -> *mut u8 {
let Ok(layout) = Layout::from_size_align(size.max(1), align) else {
return std::ptr::null_mut();
};
let pointer = unsafe { std::alloc::alloc(layout) };
if pointer.is_null() {
std::alloc::handle_alloc_error(layout);
}
pointer
}
unsafe extern "C" fn default_deallocate(pointer: *mut u8, size: usize, align: usize) {
if pointer.is_null() {
return;
}
let Ok(layout) = Layout::from_size_align(size.max(1), align) else {
return;
};
unsafe { std::alloc::dealloc(pointer, layout) }
}