Skip to content

Commit a5d806c

Browse files
committed
Added minimum alignment
1 parent 6d98a9a commit a5d806c

File tree

2 files changed

+55
-4
lines changed

2 files changed

+55
-4
lines changed

libmimalloc-sys/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
use libc::{c_void, size_t};
44

55
extern "C" {
6+
pub fn mi_zalloc_aligned(size: size_t, alignment: size_t) -> *const c_void;
67
pub fn mi_malloc_aligned(size: size_t, alignment: size_t) -> *const c_void;
8+
pub fn mi_realloc_aligned(p: *const c_void, size: size_t, alignment: size_t) -> *const c_void;
79
pub fn mi_free(p: *const c_void) -> c_void;
810
}

src/lib.rs

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,30 @@
2424
extern crate libmimalloc_sys as ffi;
2525

2626
use std::alloc::{GlobalAlloc, Layout};
27-
use std::ptr::null_mut;
2827
use libc::c_void;
2928
use ffi::*;
3029

30+
// Copied from https://github.com/rust-lang/rust/blob/master/src/libstd/sys_common/alloc.rs
31+
#[cfg(all(any(
32+
target_arch = "x86",
33+
target_arch = "arm",
34+
target_arch = "mips",
35+
target_arch = "powerpc",
36+
target_arch = "powerpc64",
37+
target_arch = "asmjs",
38+
target_arch = "wasm32"
39+
)))]
40+
const MIN_ALIGN: usize = 8;
41+
42+
#[cfg(all(any(
43+
target_arch = "x86_64",
44+
target_arch = "aarch64",
45+
target_arch = "mips64",
46+
target_arch = "s390x",
47+
target_arch = "sparc64"
48+
)))]
49+
const MIN_ALIGN: usize = 16;
50+
3151
/// Drop-in mimalloc global allocator.
3252
///
3353
/// ## Usage
@@ -40,12 +60,41 @@ use ffi::*;
4060
pub struct MiMalloc;
4161

4262
unsafe impl GlobalAlloc for MiMalloc {
43-
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
44-
mi_malloc_aligned(layout.size(), layout.align());
45-
null_mut()
63+
#[inline]
64+
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
65+
let align = if layout.align() > MIN_ALIGN {
66+
layout.align()
67+
} else {
68+
MIN_ALIGN
69+
};
70+
71+
mi_malloc_aligned(layout.size(), align) as *mut u8
72+
}
73+
74+
#[inline]
75+
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
76+
let align = if layout.align() > MIN_ALIGN {
77+
layout.align()
78+
} else {
79+
MIN_ALIGN
80+
};
81+
82+
mi_zalloc_aligned(layout.size(), align) as *mut u8
4683
}
4784

85+
#[inline]
4886
unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
4987
mi_free(ptr as *const c_void);
5088
}
89+
90+
#[inline]
91+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
92+
let align = if layout.align() > MIN_ALIGN {
93+
layout.align()
94+
} else {
95+
MIN_ALIGN
96+
};
97+
98+
mi_realloc_aligned(ptr as *const c_void, new_size, align) as *mut u8
99+
}
51100
}

0 commit comments

Comments
 (0)