Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 8 additions & 6 deletions library/alloc/src/boxed/thin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,19 +132,21 @@ impl<T: ?Sized> ThinBox<T> {
}
}

struct WithHeader<H>(*mut u8, PhantomData<H>);
struct WithHeader<H>(NonNull<u8>, PhantomData<H>);

impl<H> WithHeader<H> {
fn new<T>(header: H, value: T) -> Option<WithHeader<H>> {
let layout = Self::alloc_layout(mem::size_of::<T>(), mem::align_of::<T>());
let aligned_header_size = Self::aligned_header_size(layout.align());

unsafe {
let ptr = NonNull::new(alloc::alloc(layout))?;
let ptr = alloc::alloc(layout);

// Safety:
// - The size is at least `aligned_header_size`.
let ptr = ptr.as_ptr().offset(aligned_header_size as isize) as *mut _;
let ptr = ptr.offset(aligned_header_size as isize) as *mut _;

let ptr = NonNull::new(ptr)?;

let result = WithHeader(ptr, PhantomData);
ptr::write(result.header(), header);
Expand All @@ -162,18 +164,18 @@ impl<H> WithHeader<H> {
let aligned_header_size = Self::aligned_header_size(layout.align());

ptr::drop_in_place::<T>(value as *mut T);
alloc::dealloc(self.0.offset(-(aligned_header_size as isize)), layout);
alloc::dealloc(self.0.as_ptr().offset(-(aligned_header_size as isize)), layout);
}
}

fn header(&self) -> *mut H {
// Safety:
// - At least `size_of::<H>()` bytes are allocated ahead of the pointer.
unsafe { self.0.offset(-(Self::header_size() as isize)) as *mut H }
unsafe { self.0.as_ptr().offset(-(Self::header_size() as isize)) as *mut H }
}

fn value(&self) -> *mut u8 {
self.0
self.0.as_ptr()
}

fn header_size() -> usize {
Expand Down
2 changes: 2 additions & 0 deletions library/alloc/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
#![feature(const_trait_impl)]
#![feature(const_str_from_utf8)]
#![feature(nonnull_slice_from_raw_parts)]
#![feature(thin_box)]

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
Expand All @@ -56,6 +57,7 @@ mod rc;
mod slice;
mod str;
mod string;
mod thin_box;
mod vec;
mod vec_deque;

Expand Down
25 changes: 25 additions & 0 deletions library/alloc/tests/thin_box.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use core::mem;

use alloc::boxed::ThinBox;

#[test]
fn want_niche_optimization() {
assert_eq!(
mem::size_of::<Option<ThinBox<[i32]>>>(),
mem::size_of::<ThinBox<[i32]>>(),
);
}

fn want_thin() {
assert_eq!(
mem::size_of::<ThinBox<[i32]>>(),
mem::size_of::<*mut ()>(),
);

trait Tr {}

assert_eq!(
mem::size_of::<ThinBox<dyn Tr>>(),
mem::size_of::<*mut ()>(),
);
}