mirmalloc 0.2.0

MiMalloc Rust Bindings
Documentation
use std::alloc::Layout;
use libmimalloc_sys_ms::{
    mi_heap_t, mi_heap_new, mi_heap_delete, mi_heap_malloc_aligned,
    mi_heap_zalloc_aligned, mi_heap_realloc_aligned, mi_free,
};

pub struct RawHeap(*mut mi_heap_t);

// SAFETY: mi_heap_t is thread-safe according to mimalloc documentation
unsafe impl Send for RawHeap {}
unsafe impl Sync for RawHeap {}

impl RawHeap {
    pub fn new() -> Self {
        unsafe {
            Self(mi_heap_new())
        }
    }

    pub unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        unsafe { mi_heap_malloc_aligned(self.0, layout.size(), layout.align()) as *mut u8 }
    }

    pub unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
        unsafe { mi_free(ptr as *mut _) }
    }

    pub unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        unsafe { mi_heap_zalloc_aligned(self.0, layout.size(), layout.align()) as *mut u8 }
    }

    pub unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        unsafe { mi_heap_realloc_aligned(self.0, ptr as *mut _, new_size, layout.align()) as *mut u8 }
    }
}

impl Drop for RawHeap {
    fn drop(&mut self) {
        unsafe {
            mi_heap_delete(self.0);
        }
    }
}