1//! Based on
2//! <https://github.com/matthieu-m/rfc2580/blob/b58d1d3cba0d4b5e859d3617ea2d0943aaa31329/examples/thin.rs>
3//! by matthieu-m
45use core::error::Error;
6use core::fmt::{self, Debug, Display, Formatter};
7#[cfg(not(no_global_oom_handling))]
8use core::intrinsics::{const_allocate, const_make_global};
9use core::marker::PhantomData;
10#[cfg(not(no_global_oom_handling))]
11use core::marker::Unsize;
12#[cfg(not(no_global_oom_handling))]
13use core::mem;
14use core::mem::SizedTypeProperties;
15use core::ops::{Deref, DerefMut};
16use core::ptr::{self, NonNull, Pointee};
1718use crate::alloc::{self, Layout, LayoutError};
1920/// ThinBox.
21///
22/// A thin pointer for heap allocation, regardless of T.
23///
24/// # Examples
25///
26/// ```
27/// #![feature(thin_box)]
28/// use std::boxed::ThinBox;
29///
30/// let five = ThinBox::new(5);
31/// let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]);
32///
33/// let size_of_ptr = size_of::<*const ()>();
34/// assert_eq!(size_of_ptr, size_of_val(&five));
35/// assert_eq!(size_of_ptr, size_of_val(&thin_slice));
36/// ```
37#[unstable(feature = "thin_box", issue = "92791")]
38pub struct ThinBox<T: ?Sized> {
39// This is essentially `WithHeader<<T as Pointee>::Metadata>`,
40 // but that would be invariant in `T`, and we want covariance.
41ptr: WithOpaqueHeader,
42 _marker: PhantomData<T>,
43}
4445/// `ThinBox<T>` is `Send` if `T` is `Send` because the data is owned.
46#[unstable(feature = "thin_box", issue = "92791")]
47unsafe impl<T: ?Sized + Send> Sendfor ThinBox<T> {}
4849/// `ThinBox<T>` is `Sync` if `T` is `Sync` because the data is owned.
50#[unstable(feature = "thin_box", issue = "92791")]
51unsafe impl<T: ?Sized + Sync> Syncfor ThinBox<T> {}
5253#[unstable(feature = "thin_box", issue = "92791")]
54impl<T> ThinBox<T> {
55/// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
56 /// the stack.
57 ///
58 /// # Examples
59 ///
60 /// ```
61 /// #![feature(thin_box)]
62 /// use std::boxed::ThinBox;
63 ///
64 /// let five = ThinBox::new(5);
65 /// ```
66 ///
67 /// [`Metadata`]: core::ptr::Pointee::Metadata
68#[cfg(not(no_global_oom_handling))]
69pub fn new(value: T) -> Self {
70let meta = ptr::metadata(&value);
71let ptr = WithOpaqueHeader::new(meta, value);
72ThinBox { ptr, _marker: PhantomData }
73 }
7475/// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
76 /// the stack. Returns an error if allocation fails, instead of aborting.
77 ///
78 /// # Examples
79 ///
80 /// ```
81 /// #![feature(thin_box)]
82 /// use std::boxed::ThinBox;
83 ///
84 /// let five = ThinBox::try_new(5)?;
85 /// # Ok::<(), std::alloc::AllocError>(())
86 /// ```
87 ///
88 /// [`Metadata`]: core::ptr::Pointee::Metadata
89pub fn try_new(value: T) -> Result<Self, core::alloc::AllocError> {
90let meta = ptr::metadata(&value);
91WithOpaqueHeader::try_new(meta, value).map(|ptr| ThinBox { ptr, _marker: PhantomData })
92 }
93}
9495#[unstable(feature = "thin_box", issue = "92791")]
96impl<Dyn: ?Sized> ThinBox<Dyn> {
97/// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
98 /// the stack.
99 ///
100 /// # Examples
101 ///
102 /// ```
103 /// #![feature(thin_box)]
104 /// use std::boxed::ThinBox;
105 ///
106 /// let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]);
107 /// ```
108 ///
109 /// [`Metadata`]: core::ptr::Pointee::Metadata
110#[cfg(not(no_global_oom_handling))]
111pub fn new_unsize<T>(value: T) -> Self
112where
113T: Unsize<Dyn>,
114 {
115if T::IS_ZST {
116let ptr = WithOpaqueHeader::new_unsize_zst::<Dyn, T>(value);
117ThinBox { ptr, _marker: PhantomData }
118 } else {
119let meta = ptr::metadata(&valueas &Dyn);
120let ptr = WithOpaqueHeader::new(meta, value);
121ThinBox { ptr, _marker: PhantomData }
122 }
123 }
124}
125126#[unstable(feature = "thin_box", issue = "92791")]
127impl<T: ?Sized + Debug> Debugfor ThinBox<T> {
128fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
129 Debug::fmt(self.deref(), f)
130 }
131}
132133#[unstable(feature = "thin_box", issue = "92791")]
134impl<T: ?Sized + Display> Displayfor ThinBox<T> {
135fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
136 Display::fmt(self.deref(), f)
137 }
138}
139140#[unstable(feature = "thin_box", issue = "92791")]
141impl<T: ?Sized> Dereffor ThinBox<T> {
142type Target = T;
143144fn deref(&self) -> &T {
145let value = self.data();
146let metadata = self.meta();
147let pointer = ptr::from_raw_parts(valueas *const (), metadata);
148// SAFETY: &ThinBox<T> points to a valid pointer for T.
149unsafe { &*pointer }
150 }
151}
152153#[unstable(feature = "thin_box", issue = "92791")]
154impl<T: ?Sized> DerefMutfor ThinBox<T> {
155fn deref_mut(&mut self) -> &mut T {
156let value = self.data();
157let metadata = self.meta();
158let pointer = ptr::from_raw_parts_mut::<T>(valueas *mut (), metadata);
159// SAFETY: &mut ThinBox<T> points to a valid and unique pointer for T.
160unsafe { &mut *pointer }
161 }
162}
163164#[unstable(feature = "thin_box", issue = "92791")]
165impl<T: ?Sized> Dropfor ThinBox<T> {
166fn drop(&mut self) {
167let value = self.deref_mut();
168let value = valueas *mut T;
169// SAFETY: `value` is valid for reads and writes for our `T`.
170unsafe {
171self.with_header().drop::<T>(value);
172 }
173 }
174}
175176#[unstable(feature = "thin_box", issue = "92791")]
177impl<T: ?Sized> ThinBox<T> {
178fn meta(&self) -> <T as Pointee>::Metadata {
179// SAFETY: NonNull and valid.
180unsafe { *self.with_header().header() }
181 }
182183fn data(&self) -> *mut u8 {
184self.with_header().value()
185 }
186187fn with_header(&self) -> &WithHeader<<T as Pointee>::Metadata> {
188// SAFETY: both types are transparent to `NonNull<u8>`
189unsafe { &*((&raw const self.ptr) as *const WithHeader<_>) }
190 }
191}
192193/// A pointer to type-erased data, guaranteed to either be:
194/// 1. `NonNull::dangling()`, in the case where both the pointee (`T`) and
195/// metadata (`H`) are ZSTs.
196/// 2. A pointer to a valid `T` that has a header `H` directly before the
197/// pointed-to location.
198#[repr(transparent)]
199struct WithHeader<H>(NonNull<u8>, PhantomData<H>);
200201/// An opaque representation of `WithHeader<H>` to avoid the
202/// projection invariance of `<T as Pointee>::Metadata`.
203#[repr(transparent)]
204struct WithOpaqueHeader(NonNull<u8>);
205206impl WithOpaqueHeader {
207#[cfg(not(no_global_oom_handling))]
208fn new<H, T>(header: H, value: T) -> Self {
209let ptr = WithHeader::new(header, value);
210Self(ptr.0)
211 }
212213#[cfg(not(no_global_oom_handling))]
214fn new_unsize_zst<Dyn, T>(value: T) -> Self
215where
216Dyn: ?Sized,
217 T: Unsize<Dyn>,
218 {
219let ptr = WithHeader::<<Dyn as Pointee>::Metadata>::new_unsize_zst::<Dyn, T>(value);
220Self(ptr.0)
221 }
222223fn try_new<H, T>(header: H, value: T) -> Result<Self, core::alloc::AllocError> {
224WithHeader::try_new(header, value).map(|ptr| Self(ptr.0))
225 }
226}
227228impl<H> WithHeader<H> {
229#[cfg(not(no_global_oom_handling))]
230fn new<T>(header: H, value: T) -> WithHeader<H> {
231let value_layout = Layout::new::<T>();
232let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
233// We pass an empty layout here because we do not know which layout caused the
234 // arithmetic overflow in `Layout::extend` and `handle_alloc_error` takes `Layout` as
235 // its argument rather than `Result<Layout, LayoutError>`, also this function has been
236 // stable since 1.28 ._.
237 //
238 // On the other hand, look at this gorgeous turbofish!
239alloc::handle_alloc_error(Layout::new::<()>());
240 };
241242// Note: It's UB to pass a layout with a zero size to `alloc::alloc`, so
243 // we use `layout.dangling()` for this case, which should have a valid
244 // alignment for both `T` and `H`.
245let ptr = if layout.size() == 0 {
246// Some paranoia checking, mostly so that the ThinBox tests are
247 // more able to catch issues.
248if true {
if !(value_offset == 0 && T::IS_ZST && H::IS_ZST) {
::core::panicking::panic("assertion failed: value_offset == 0 && T::IS_ZST && H::IS_ZST")
};
};debug_assert!(value_offset == 0 && T::IS_ZST && H::IS_ZST);
249layout.dangling_ptr()
250 } else {
251// SAFETY: We check above that the layout size is nonzero.
252let ptr = unsafe { alloc::alloc(layout) };
253if ptr.is_null() {
254 alloc::handle_alloc_error(layout);
255 }
256// SAFETY:
257 // - The size is at least `aligned_header_size`.
258unsafe {
259let ptr = ptr.add(value_offset) as *mut _;
260261NonNull::new_unchecked(ptr)
262 }
263 };
264265let result = WithHeader(ptr, PhantomData);
266267// SAFETY: `result.header()` promises to give us a valid place for writing
268 // the header, and `result.value()` promises the same for the value.
269unsafe {
270 ptr::write(result.header(), header);
271 ptr::write(result.value().cast(), value);
272 }
273274result275 }
276277/// Non-panicking version of `new`.
278 /// Any error is returned as `Err(core::alloc::AllocError)`.
279fn try_new<T>(header: H, value: T) -> Result<WithHeader<H>, core::alloc::AllocError> {
280let value_layout = Layout::new::<T>();
281let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
282return Err(core::alloc::AllocError);
283 };
284285// Note: It's UB to pass a layout with a zero size to `alloc::alloc`, so
286 // we use `layout.dangling()` for this case, which should have a valid
287 // alignment for both `T` and `H`.
288let ptr = if layout.size() == 0 {
289// Some paranoia checking, mostly so that the ThinBox tests are
290 // more able to catch issues.
291if true {
if !(value_offset == 0 && T::IS_ZST && H::IS_ZST) {
::core::panicking::panic("assertion failed: value_offset == 0 && T::IS_ZST && H::IS_ZST")
};
};debug_assert!(value_offset == 0 && T::IS_ZST && H::IS_ZST);
292layout.dangling_ptr()
293 } else {
294// SAFETY: We check above that the layout size is nonzero.
295let ptr = unsafe { alloc::alloc(layout) };
296if ptr.is_null() {
297return Err(core::alloc::AllocError);
298 }
299300// SAFETY:
301 // - The size is at least `aligned_header_size`.
302unsafe {
303let ptr = ptr.add(value_offset) as *mut _;
304305NonNull::new_unchecked(ptr)
306 }
307 };
308309let result = WithHeader(ptr, PhantomData);
310311// SAFETY: `result.header()` promises to give us a valid place for writing
312 // the header, and `result.value()` promises the same for the value.
313unsafe {
314 ptr::write(result.header(), header);
315 ptr::write(result.value().cast(), value);
316 }
317318Ok(result)
319 }
320321// `Dyn` is `?Sized` type like `[u32]`, and `T` is ZST type like `[u32; 0]`.
322#[cfg(not(no_global_oom_handling))]
323fn new_unsize_zst<Dyn, T>(value: T) -> WithHeader<H>
324where
325Dyn: Pointee<Metadata = H> + ?Sized,
326 T: Unsize<Dyn>,
327 {
328if !T::IS_ZST { ::core::panicking::panic("assertion failed: T::IS_ZST") };assert!(T::IS_ZST);
329330const fn max(a: usize, b: usize) -> usize {
331if a > b { a } else { b }
332 }
333334// Compute a pointer to the right metadata. This will point to the beginning
335 // of the header, past the padding, so the assigned type makes sense.
336 // It also ensures that the address at the end of the header is sufficiently
337 // aligned for T.
338let alloc: &<Dyn as Pointee>::Metadata = const {
339// FIXME: just call `WithHeader::alloc_layout` with size reset to 0.
340 // Currently that's blocked on `Layout::extend` not being `const fn`.
341342let alloc_align = max(align_of::<T>(), align_of::<<Dyn as Pointee>::Metadata>());
343344let alloc_size = max(align_of::<T>(), size_of::<<Dyn as Pointee>::Metadata>());
345346// SAFETY: align is power of two because it is the maximum of two alignments.
347let alloc: *mut u8 = unsafe { const_allocate(alloc_size, alloc_align) };
348349let metadata_offset =
350alloc_size.checked_sub(size_of::<<Dyn as Pointee>::Metadata>()).unwrap();
351let metadata_ptr: *mut <Dyn as Pointee>::Metadata =
352// SAFETY: adding offset within the allocation.
353unsafe { alloc.add(metadata_offset).cast() };
354// SAFETY: `*metadata_ptr` is within the allocation.
355unsafe {
356metadata_ptr.write(ptr::metadata::<Dyn>(ptr::dangling::<T>() as *const Dyn));
357 }
358// SAFETY: valid heap allocation
359unsafe { const_make_global(alloc) };
360// SAFETY: we have just written the metadata.
361unsafe { &*metadata_ptr }
362 };
363364let value_ptr =
365// SAFETY: `alloc` points to `<Dyn as Pointee>::Metadata`, so addition stays in-bounds.
366unsafe { (allocas *const <Dyn as Pointee>::Metadata).add(1) }.cast::<T>().cast_mut();
367if true {
if !value_ptr.is_aligned() {
::core::panicking::panic("assertion failed: value_ptr.is_aligned()")
};
};debug_assert!(value_ptr.is_aligned());
368 mem::forget(value);
369WithHeader(NonNull::new(value_ptr.cast()).unwrap(), PhantomData)
370 }
371372/// # Safety
373 ///
374 /// `value` must point to an undropped owned `T`, and `self` must not be
375 /// accessed again after this is called.
376unsafe fn drop<T: ?Sized>(&self, value: *mut T) {
377struct DropGuard<H> {
378 ptr: NonNull<u8>,
379 value_layout: Layout,
380 _marker: PhantomData<H>,
381 }
382383impl<H> Dropfor DropGuard<H> {
384fn drop(&mut self) {
385// All ZST are allocated statically.
386if self.value_layout.size() == 0 {
387return;
388 }
389390let (layout, value_offset) =
391// SAFETY: Layout must have been computable if we're in drop
392unsafe { WithHeader::<H>::alloc_layout(self.value_layout).unwrap_unchecked() };
393394// Since we only allocate for non-ZSTs, the layout size cannot be zero.
395if true {
if !(layout.size() != 0) {
::core::panicking::panic("assertion failed: layout.size() != 0")
};
};debug_assert!(layout.size() != 0);
396// SAFETY: We own the allocation with `layout` at `ptr - value_offset`.
397unsafe { alloc::dealloc(self.ptr.as_ptr().sub(value_offset), layout) };
398 }
399 }
400401// `_guard` will deallocate the memory when dropped, even if `drop_in_place` unwinds.
402let _guard = DropGuard {
403 ptr: self.0,
404// SAFETY: Caller ensures `value` is valid.
405value_layout: unsafe { Layout::for_value_raw(value) },
406 _marker: PhantomData::<H>,
407 };
408409// We only drop the value because the Pointee trait requires that the metadata is copy
410 // aka trivially droppable.
411 // SAFETY: We're the only droppers of `value` and it's not dropped again.
412unsafe { ptr::drop_in_place::<T>(value) };
413 }
414415fn header(&self) -> *mut H {
416// SAFETY:
417 // - At least `size_of::<H>()` bytes are allocated ahead of the pointer.
418 // - We know that H will be aligned because the middle pointer is aligned to the greater
419 // of the alignment of the header and the data and the header size includes the padding
420 // needed to align the header. Subtracting the header size from the aligned data pointer
421 // will always result in an aligned header pointer, it just may not point to the
422 // beginning of the allocation.
423let hp = unsafe { self.0.as_ptr().sub(Self::header_size()) as *mut H };
424if true {
if !hp.is_aligned() {
::core::panicking::panic("assertion failed: hp.is_aligned()")
};
};debug_assert!(hp.is_aligned());
425hp426 }
427428fn value(&self) -> *mut u8 {
429self.0.as_ptr()
430 }
431432const fn header_size() -> usize {
433size_of::<H>()
434 }
435436fn alloc_layout(value_layout: Layout) -> Result<(Layout, usize), LayoutError> {
437Layout::new::<H>().extend(value_layout)
438 }
439}
440441#[unstable(feature = "thin_box", issue = "92791")]
442impl<T: ?Sized + Error> Errorfor ThinBox<T> {
443fn source(&self) -> Option<&(dyn Error + 'static)> {
444self.deref().source()
445 }
446}
447448#[cfg(not(no_global_oom_handling))]
449#[unstable(feature = "thin_box", issue = "92791")]
450impl<T> From<T> for ThinBox<T> {
451#[inline(always)]
452fn from(value: T) -> Self {
453Self::new(value)
454 }
455}