Skip to content

Commit aa19e43

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 #50822 (comment)
1 parent bef62cc commit aa19e43

14 files changed

+193
-99
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
@@ -147,6 +151,7 @@ pub unsafe fn alloc_zeroed(layout: Layout) -> *mut u8 {
147151
__rust_alloc_zeroed(layout.size(), layout.align())
148152
}
149153

154+
#[cfg(not(test))]
150155
#[unstable(feature = "allocator_api", issue = "32838")]
151156
unsafe impl Alloc for Global {
152157
#[inline]
@@ -185,25 +190,23 @@ unsafe fn exchange_malloc(size: usize, align: usize) -> *mut u8 {
185190
align as *mut u8
186191
} else {
187192
let layout = Layout::from_size_align_unchecked(size, align);
188-
let ptr = alloc(layout);
189-
if !ptr.is_null() {
190-
ptr
191-
} else {
192-
handle_alloc_error(layout)
193+
match Global.alloc(layout) {
194+
Ok(ptr) => ptr.as_ptr(),
195+
Err(_) => handle_alloc_error(layout),
193196
}
194197
}
195198
}
196199

197200
#[cfg_attr(not(test), lang = "box_free")]
198201
#[inline]
199-
pub(crate) unsafe fn box_free<T: ?Sized>(ptr: Unique<T>) {
202+
pub(crate) unsafe fn box_free<T: ?Sized, A: Alloc>(ptr: Unique<T>, mut a: A) {
200203
let ptr = ptr.as_ptr();
201204
let size = size_of_val(&*ptr);
202205
let align = min_align_of_val(&*ptr);
203206
// We do not allocate for Box<T> when T is ZST, so deallocation is also not necessary.
204207
if size != 0 {
205208
let layout = Layout::from_size_align_unchecked(size, align);
206-
dealloc(ptr as *mut u8, layout);
209+
a.dealloc(NonNull::new_unchecked(ptr).cast(), layout);
207210
}
208211
}
209212

0 commit comments

Comments
 (0)