use alloc::alloc::{alloc, dealloc};
use core::{alloc::Layout, ffi::c_void};
use crate::ctypes;
struct MemoryControlBlock {
size: usize,
}
const CTRL_BLK_SIZE: usize = core::mem::size_of::<MemoryControlBlock>();
#[unsafe(no_mangle)]
pub unsafe extern "C" fn malloc(size: ctypes::size_t) -> *mut c_void {
let layout = Layout::from_size_align(size + CTRL_BLK_SIZE, 8).unwrap();
unsafe {
let ptr = alloc(layout).cast::<MemoryControlBlock>();
assert!(!ptr.is_null(), "malloc failed");
ptr.write(MemoryControlBlock { size });
ptr.add(1).cast()
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn free(ptr: *mut c_void) {
if ptr.is_null() {
return;
}
let ptr = ptr.cast::<MemoryControlBlock>();
assert!(ptr as usize > CTRL_BLK_SIZE, "free a null pointer");
unsafe {
let ptr = ptr.sub(1);
let size = ptr.read().size;
let layout = Layout::from_size_align(size + CTRL_BLK_SIZE, 8).unwrap();
dealloc(ptr.cast(), layout)
}
}