24
24
extern crate libmimalloc_sys as ffi;
25
25
26
26
use std:: alloc:: { GlobalAlloc , Layout } ;
27
- use std:: ptr:: null_mut;
28
27
use libc:: c_void;
29
28
use ffi:: * ;
30
29
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
+
31
51
/// Drop-in mimalloc global allocator.
32
52
///
33
53
/// ## Usage
@@ -40,12 +60,41 @@ use ffi::*;
40
60
pub struct MiMalloc ;
41
61
42
62
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
46
83
}
47
84
85
+ #[ inline]
48
86
unsafe fn dealloc ( & self , ptr : * mut u8 , _layout : Layout ) {
49
87
mi_free ( ptr as * const c_void ) ;
50
88
}
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
+ }
51
100
}
0 commit comments