Skip to content

Commit f6ab188

Browse files
committed
add MiMallocExcess allocator implementation for Rust, see isue #1513
1 parent 2c23c7b commit f6ab188

4 files changed

Lines changed: 170 additions & 6 deletions

File tree

‎contrib/rust/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ static GLOBAL: MiMalloc = MiMalloc;
2121
- Both `MiMalloc` and `&Heap` implement `core::alloc::Allocator` on Rust 1.100+
2222
(or on an older nightly with the `nightly` feature). For speed, `allocate` returns the
2323
requested size instead of the full usable size; to use the full capacity, request
24-
`good_size(n)` bytes upfront (or use `sys::mi_umalloc`).
24+
`good_size(n)` bytes upfront, or use `MiMallocExcess` that returns the full usable size.
2525
- Helpers such as `collect`, `option_set`, `stats_print` and `stats_json`.
2626

2727
## Arenas

‎contrib/rust/src/allocator.rs‎

Lines changed: 116 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@ terms of the MIT license. A copy of the license can be found in the file
55
"LICENSE" at the root of this distribution.
66
-----------------------------------------------------------------------------*/
77
use crate::heap::realloc_in;
8-
use crate::{free_sized, realloc_aligned, Heap, MiMalloc};
8+
use crate::{free_sized, realloc_aligned, sys, Heap, MiMalloc, MAX_ALIGN_SIZE};
99
use core::alloc::{AllocError, Allocator, GlobalAlloc, Layout};
10+
use core::mem::size_of;
1011
use core::ptr::NonNull;
1112

1213
#[inline(always)]
@@ -24,8 +25,8 @@ unsafe fn zero_tail(ptr: *mut u8, old_size: usize, new_size: usize) -> *mut u8 {
2425
ptr
2526
}
2627

27-
// Reports the requested size to stay as fast as `GlobalAlloc`; use `good_size` upfront
28-
// (or `sys::mi_umalloc`) to get the full usable size (issue #1513).
28+
// Reports the requested size to stay as fast as `GlobalAlloc`; use `good_size` upfront,
29+
// or `MiMallocExcess`, to get the full usable size (issue #1513).
2930
unsafe impl Allocator for MiMalloc {
3031
#[inline]
3132
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
@@ -133,3 +134,115 @@ unsafe impl Allocator for &Heap {
133134
)
134135
}
135136
}
137+
138+
/// As [`MiMalloc`] but `allocate` returns the full usable size by requesting `good_size` bytes.
139+
/// This can be useful for vector or buffer allocations to maximise the usable memory and reduce reallocations.
140+
#[derive(Clone, Copy, Debug, Default)]
141+
pub struct MiMallocExcess;
142+
143+
// As `mi_good_size` for sizes up to `MI_SMALL_SIZE_MAX` (in words, see `mi_bin`); a mismatch only wastes space as we allocate the returned size.
144+
// (If the size classes ever change, we catch this in the tests where we verify `small_good_wsize` against `mi_good_size`.)
145+
#[inline(always)]
146+
pub(crate) const fn small_good_wsize(size: usize) -> usize {
147+
const ALIGN_WSIZE: usize = MAX_ALIGN_SIZE / size_of::<usize>();
148+
let wsize = crate::wsize_from_size(size);
149+
if wsize <= 1 {
150+
1
151+
} else if size <= 16 {
152+
(wsize + 1) & !1
153+
} else if size <= 64 {
154+
(wsize + ALIGN_WSIZE - 1) & !(ALIGN_WSIZE - 1)
155+
} else {
156+
// 4 size classes per power of two
157+
let w = wsize - 1;
158+
let shift = (usize::BITS - 1 - w.leading_zeros()) - 2;
159+
((w >> shift) + 1) << shift
160+
}
161+
}
162+
163+
#[inline(always)]
164+
fn small_alloc(layout: Layout, zero: bool) -> Option<Result<NonNull<[u8]>, AllocError>> {
165+
if layout.align() > MAX_ALIGN_SIZE || layout.size() > sys::MI_SMALL_SIZE_MAX {
166+
return None;
167+
}
168+
let wsize = small_good_wsize(layout.size());
169+
let p = unsafe {
170+
if zero {
171+
sys::mi_wzalloc_small(wsize)
172+
} else {
173+
sys::mi_wmalloc_small(wsize)
174+
}
175+
};
176+
Some(block(p.cast(), wsize * size_of::<usize>()))
177+
}
178+
179+
#[inline(always)]
180+
fn good_layout(layout: Layout) -> Layout {
181+
let size = crate::good_size(layout.size());
182+
unsafe { Layout::from_size_align_unchecked(size, layout.align()) }
183+
}
184+
185+
unsafe impl Allocator for MiMallocExcess {
186+
#[inline]
187+
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
188+
if let Some(r) = small_alloc(layout, false) {
189+
return r;
190+
}
191+
let layout = good_layout(layout);
192+
block(unsafe { MiMalloc.alloc(layout) }, layout.size())
193+
}
194+
195+
#[inline]
196+
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
197+
if let Some(r) = small_alloc(layout, true) {
198+
return r;
199+
}
200+
let layout = good_layout(layout);
201+
block(unsafe { MiMalloc.alloc_zeroed(layout) }, layout.size())
202+
}
203+
204+
#[inline]
205+
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
206+
unsafe { free_sized(ptr.as_ptr(), layout) }
207+
}
208+
209+
#[inline]
210+
unsafe fn grow(
211+
&self,
212+
ptr: NonNull<u8>,
213+
_old: Layout,
214+
new: Layout,
215+
) -> Result<NonNull<[u8]>, AllocError> {
216+
let size = crate::good_size(new.size());
217+
block(
218+
unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) },
219+
size,
220+
)
221+
}
222+
223+
#[inline]
224+
unsafe fn grow_zeroed(
225+
&self,
226+
ptr: NonNull<u8>,
227+
old: Layout,
228+
new: Layout,
229+
) -> Result<NonNull<[u8]>, AllocError> {
230+
let size = crate::good_size(new.size());
231+
let p = unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) };
232+
block(unsafe { zero_tail(p, old.size(), size) }, size)
233+
}
234+
235+
#[inline]
236+
unsafe fn shrink(
237+
&self,
238+
ptr: NonNull<u8>,
239+
_old: Layout,
240+
new: Layout,
241+
) -> Result<NonNull<[u8]>, AllocError> {
242+
let size = crate::good_size(new.size());
243+
block(
244+
unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) },
245+
size,
246+
)
247+
}
248+
}

‎contrib/rust/src/lib.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,8 @@ terms of the MIT license. A copy of the license can be found in the file
2727
#[allow(clippy::incompatible_msrv)]
2828
mod allocator;
2929
mod arena;
30+
#[cfg(any(feature = "nightly", allocator_api_stable))]
31+
pub use allocator::MiMallocExcess;
3032
mod heap;
3133
pub use mimalloc_sys as sys;
3234

@@ -39,7 +41,7 @@ use core::mem::size_of;
3941
use core::ptr::{self, NonNull};
4042

4143
// As `MI_MAX_ALIGN_SIZE`
42-
const MAX_ALIGN_SIZE: usize = 16;
44+
pub(crate) const MAX_ALIGN_SIZE: usize = 16;
4345

4446
// Fast check if `mi_malloc(size)` is already `align`-aligned (a subset of `mi_malloc_is_naturally_aligned`)
4547
#[inline(always)]
@@ -49,7 +51,7 @@ pub(crate) const fn is_malloc_aligned(size: usize, align: usize) -> bool {
4951

5052
// As `_mi_wsize_from_size`
5153
#[inline(always)]
52-
const fn wsize_from_size(size: usize) -> usize {
54+
pub(crate) const fn wsize_from_size(size: usize) -> usize {
5355
(size + size_of::<usize>() - 1) / size_of::<usize>()
5456
}
5557

‎contrib/rust/tests/allocator.rs‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,52 @@ fn grow_zeroed() {
6666
}
6767
}
6868
}
69+
70+
#[test]
71+
fn excess_allocator_api() {
72+
use core::alloc::{Allocator, Layout};
73+
use mimalloc::{good_size, usable_size, MiMallocExcess};
74+
let a = MiMallocExcess;
75+
// returned sizes match `good_size` (unless padding is enabled)
76+
let exact = good_size(0) == 8;
77+
for (size, align) in [
78+
(0, 1),
79+
(100, 8),
80+
(1000, 8),
81+
(5000, 16),
82+
(100, 64),
83+
(300_000, 4096),
84+
] {
85+
let p = a
86+
.allocate_zeroed(Layout::from_size_align(size, align).unwrap())
87+
.unwrap();
88+
let q = p.cast::<u8>().as_ptr();
89+
assert!(p.len() >= size && (!exact || p.len() == good_size(size)));
90+
assert!(p.len() <= unsafe { usable_size(q) });
91+
assert!((0..p.len()).all(|i| unsafe { q.add(i).read() } == 0));
92+
assert_eq!(q as usize % align, 0);
93+
let (old, new) = (
94+
Layout::from_size_align(p.len(), align).unwrap(),
95+
Layout::from_size_align(p.len() + 1, align).unwrap(),
96+
);
97+
let r = unsafe { a.grow_zeroed(p.cast(), old, new) }.unwrap();
98+
let q = r.cast::<u8>().as_ptr();
99+
assert!(r.len() >= new.size() && (!exact || r.len() == good_size(new.size())));
100+
assert!(r.len() <= unsafe { usable_size(q) });
101+
assert!((old.size()..r.len()).all(|i| unsafe { q.add(i).read() } == 0));
102+
unsafe { a.deallocate(r.cast(), Layout::from_size_align(r.len(), align).unwrap()) };
103+
}
104+
for size in 0..=mimalloc::sys::MI_SMALL_SIZE_MAX {
105+
let layout = Layout::from_size_align(size, 1).unwrap();
106+
let p = a.allocate(layout).unwrap();
107+
let len = unsafe { usable_size(p.cast::<u8>().as_ptr()) };
108+
assert!(p.len() >= size && p.len() <= len && (!exact || p.len() == good_size(size)));
109+
unsafe { a.deallocate(p.cast(), Layout::from_size_align(p.len(), 1).unwrap()) };
110+
}
111+
// `Vec` ignores the excess for now
112+
let mut v = Vec::with_capacity_in(100, a);
113+
v.extend(0..10_000u32);
114+
v.truncate(10);
115+
v.shrink_to_fit();
116+
assert_eq!(v[9], 9);
117+
}

0 commit comments

Comments
 (0)