Skip to content

Commit ab1c863

Browse files
committed
Associate an allocator to boxes
This turns `Box<T>` into `Box<T, A: Alloc = Global>`. This is a minimalist change to achieve this, not touching anything that could have backwards incompatible consequences like requiring type annotations in places where they currently aren't required, per rust-lang#50822 (comment)
1 parent baba500 commit ab1c863

12 files changed

+174
-81
lines changed

src/liballoc/alloc.rs

+10-7
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,14 @@ extern "Rust" {
4040
/// This type implements the [`Alloc`] trait by forwarding calls
4141
/// to the allocator registered with the `#[global_allocator]` attribute
4242
/// if there is one, or the `std` crate’s default.
43+
#[cfg(not(test))]
4344
#[unstable(feature = "allocator_api", issue = "32838")]
4445
#[derive(Copy, Clone, Default, Debug)]
4546
pub struct Global;
4647

48+
#[cfg(test)]
49+
pub use std::alloc::Global;
50+
4751
/// Allocate memory with the global allocator.
4852
///
4953
/// This function forwards calls to the [`GlobalAlloc::alloc`] method
@@ -116,6 +120,7 @@ pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
116120
__rust_alloc_zeroed(layout.size(), layout.align())
117121
}
118122

123+
#[cfg(not(test))]
119124
#[unstable(feature = "allocator_api", issue = "32838")]
120125
unsafe impl Alloc for Global {
121126
#[inline]
@@ -154,25 +159,23 @@ unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
154159
align as *mut u8
155160
} else {
156161
let layout = Layout::from_size_align_unchecked(size, align);
157-
let ptr = alloc(layout);
158-
if !ptr.is_null() {
159-
ptr
160-
} else {
161-
handle_alloc_error(layout)
162+
match Global.alloc(layout) {
163+
Ok(ptr) => ptr.as_ptr(),
164+
Err(_) => handle_alloc_error(layout),
162165
}
163166
}
164167
}
165168

166169
#[cfg_attr(not(test), lang = "box_free")]
167170
#[inline]
168-
pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
171+
pub(crate) unsafe fn box_free<T: ?Sized, A: Alloc>(ptr: Unique<T>, mut a: A) {
169172
let ptr = ptr.as_ptr();
170173
let size = size_of_val(&*ptr);
171174
let align = min_align_of_val(&*ptr);
172175
// We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
173176
if size != 0 {
174177
let layout = Layout::from_size_align_unchecked(size, align);
175-
dealloc(ptr as *mut u8, layout);
178+
a.dealloc(NonNull::new_unchecked(ptr).cast(), layout);
176179
}
177180
}
178181

0 commit comments

Comments
 (0)