Skip to content

Commit f288cd2

Browse files
committed
Support custom allocators in Box
Remove `Box::leak_with_alloc` Add leak-test for box with allocator Rename `AllocErr` to `AllocError` in leak-test Add `Box::alloc` and adjust examples to use the new API
1 parent 59dafb8 commit f288cd2

29 files changed

+574
-212
lines changed

library/alloc/src/alloc.rs

+15-4
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,13 @@
22
33
#![stable(feature = "alloc_module", since = "1.28.0")]
44

5-
use core::intrinsics::{self, min_align_of_val, size_of_val};
6-
use core::ptr::{self, NonNull, Unique};
5+
#[cfg(not(test))]
6+
use core::intrinsics;
7+
use core::intrinsics::{min_align_of_val, size_of_val};
8+
9+
use core::ptr::Unique;
10+
#[cfg(not(test))]
11+
use core::ptr::{self, NonNull};
712

813
#[stable(feature = "alloc_module", since = "1.28.0")]
914
#[doc(inline)]
@@ -40,8 +45,12 @@ extern "Rust" {
4045
/// accessed through the [free functions in `alloc`](index.html#functions).
4146
#[unstable(feature = "allocator_api", issue = "32838")]
4247
#[derive(Copy, Clone, Default, Debug)]
48+
#[cfg(not(test))]
4349
pub struct Global;
4450

51+
#[cfg(test)]
52+
pub use std::alloc::Global;
53+
4554
/// Allocate memory with the global allocator.
4655
///
4756
/// This function forwards calls to the [`GlobalAlloc::alloc`] method
@@ -145,6 +154,7 @@ pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
145154
unsafe { __rust_alloc_zeroed(layout.size(), layout.align()) }
146155
}
147156

157+
#[cfg(not(test))]
148158
impl Global {
149159
#[inline]
150160
fn alloc_impl(&self, layout: Layout, zeroed: bool) -> Result<NonNull<[u8]>, AllocError> {
@@ -208,6 +218,7 @@ impl Global {
208218
}
209219

210220
#[unstable(feature = "allocator_api", issue = "32838")]
221+
#[cfg(not(test))]
211222
unsafe impl AllocRef for Global {
212223
#[inline]
213224
fn alloc(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
@@ -314,12 +325,12 @@ unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
314325
// well.
315326
// For example if `Box` is changed to `struct Box<T: ?Sized, A: AllocRef>(Unique<T>, A)`,
316327
// this function has to be changed to `fn box_free<T: ?Sized, A: AllocRef>(Unique<T>, A)` as well.
317-
pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
328+
pub(crate) unsafe fn box_free<T: ?Sized, A: AllocRef>(ptr: Unique<T>, alloc: A) {
318329
unsafe {
319330
let size = size_of_val(ptr.as_ref());
320331
let align = min_align_of_val(ptr.as_ref());
321332
let layout = Layout::from_size_align_unchecked(size, align);
322-
Global.dealloc(ptr.cast().into(), layout)
333+
alloc.dealloc(ptr.cast().into(), layout)
323334
}
324335
}
325336

0 commit comments

Comments
 (0)