Skip to main content

regorus_mimalloc_sys/
lib.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use core::ffi::c_void;
5
6pub const MI_ALIGNMENT_MAX: usize = 1024 * 1024; // 1 MiB
7
8// Define core functions from mimalloc needed for the allocator
9extern "C" {
10    /// Allocate `size` bytes aligned by `alignment`.
11    /// Returns a pointer to the allocated memory, or null if out of memory. The returned pointer is aligned by `alignment`.
12    pub fn mi_malloc_aligned(size: usize, alignment: usize) -> *mut c_void;
13    pub fn mi_zalloc_aligned(size: usize, alignment: usize) -> *mut c_void;
14
15    /// Free previously allocated memory.
16    /// The pointer `p` must have been allocated before (or be nullptr).
17    pub fn mi_free(p: *mut c_void);
18    pub fn mi_realloc_aligned(p: *mut c_void, newsize: usize, alignment: usize) -> *mut c_void;
19
20    /// Reset allocator statistics.
21    pub fn mi_stats_reset();
22}
23
24#[cfg(test)]
25mod tests {
26    use super::*;
27
28    #[test]
29    fn memory_can_be_allocated_and_freed() {
30        let ptr = unsafe { mi_malloc_aligned(8, 8) }.cast::<u8>();
31        assert!(!ptr.cast::<c_void>().is_null());
32        unsafe { mi_free(ptr.cast::<c_void>()) };
33    }
34
35    #[test]
36    fn memory_can_be_allocated_zeroed_and_freed() {
37        let ptr = unsafe { mi_zalloc_aligned(8, 8) }.cast::<u8>();
38        assert!(!ptr.cast::<c_void>().is_null());
39        unsafe { mi_free(ptr.cast::<c_void>()) };
40    }
41
42    #[test]
43    fn memory_can_be_reallocated_and_freed() {
44        let ptr = unsafe { mi_malloc_aligned(8, 8) }.cast::<u8>();
45        assert!(!ptr.cast::<c_void>().is_null());
46        let realloc_ptr = unsafe { mi_realloc_aligned(ptr.cast::<c_void>(), 8, 8) }.cast::<u8>();
47        assert!(!realloc_ptr.cast::<c_void>().is_null());
48        unsafe { mi_free(ptr.cast::<c_void>()) };
49    }
50}