mimalloc_rs/
lib.rs

1#![feature(allocator_api)]
2
3#![no_std]
4
5extern crate core;
6
7#[repr(C)]
8pub struct mi_heap_t {
9    __x: u8
10}
11
12
13
14#[link(name="mimalloc")]
15
16extern "C" {
17    pub fn mi_stats_print(_: *mut libc::FILE);
18    pub fn mi_stats_reset();
19    pub fn mi_malloc(_: usize) -> *mut u8;
20    pub fn mi_free(_: *mut u8);
21    pub fn mi_heap_malloc(_: *mut mi_heap_t,_: usize ) -> *mut u8;
22    pub fn mi_heap_destroy(_: *mut mi_heap_t);
23    pub fn mi_realloc(_: *mut u8,_: usize) -> *mut u8;
24    pub fn mi_expand(_: *mut u8,_: usize) -> *mut u8;
25    pub fn mi_zalloc(_: usize) -> *mut u8;
26    pub fn mi_heap_get_default() -> *mut mi_heap_t;
27    pub fn mi_calloc(_: usize,_: usize) -> *mut u8;
28}
29
30use core::alloc::{GlobalAlloc,Layout};
31
32pub struct MiMalloc;
33
34unsafe impl GlobalAlloc for MiMalloc {
35    unsafe fn alloc(&self,layout: Layout) -> *mut u8 {
36        let ptr = mi_malloc(layout.size());
37        assert!(!ptr.is_null());
38        ptr
39    }
40
41    unsafe fn dealloc(&self,ptr: *mut u8,_:Layout) {
42        assert!(!ptr.is_null());
43        mi_free(ptr);
44    }
45    unsafe fn alloc_zeroed(&self,layout: Layout) -> *mut u8 {
46        mi_calloc(1,layout.size())
47    }
48    
49    unsafe fn realloc(&self,ptr: *mut u8,layout: Layout,new_size: usize) -> *mut u8 {
50        if ptr.is_null() {
51            self.alloc(layout)
52        } else {
53            mi_realloc(ptr, new_size)
54        }
55    }
56}