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;
9use core::marker::PhantomData;
10#[cfg(not(no_global_oom_handling))]
11use core::marker::Unsize;
12use core::mem;
13#[cfg(not(no_global_oom_handling))]
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/// use std::mem::{size_of, size_of_val};
34/// let size_of_ptr = size_of::<*const ()>();
35/// assert_eq!(size_of_ptr, size_of_val(&five));
36/// assert_eq!(size_of_ptr, size_of_val(&thin_slice));
37/// ```
38#[unstable(feature = "thin_box", issue = "92791")]
39pub struct ThinBox<T: ?Sized> {
40// This is essentially `WithHeader<<T as Pointee>::Metadata>`,
41 // but that would be invariant in `T`, and we want covariance.
42ptr: WithOpaqueHeader,
43 _marker: PhantomData<T>,
44}
4546/// `ThinBox<T>` is `Send` if `T` is `Send` because the data is owned.
47#[unstable(feature = "thin_box", issue = "92791")]
48unsafe impl<T: ?Sized + Send> Send for ThinBox<T> {}
4950/// `ThinBox<T>` is `Sync` if `T` is `Sync` because the data is owned.
51#[unstable(feature = "thin_box", issue = "92791")]
52unsafe impl<T: ?Sized + Sync> Sync for ThinBox<T> {}
5354#[unstable(feature = "thin_box", issue = "92791")]
55impl<T> ThinBox<T> {
56/// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
57 /// the stack.
58 ///
59 /// # Examples
60 ///
61 /// ```
62 /// #![feature(thin_box)]
63 /// use std::boxed::ThinBox;
64 ///
65 /// let five = ThinBox::new(5);
66 /// ```
67 ///
68 /// [`Metadata`]: core::ptr::Pointee::Metadata
69#[cfg(not(no_global_oom_handling))]
70pub fn new(value: T) -> Self {
71let meta = ptr::metadata(&value);
72let ptr = WithOpaqueHeader::new(meta, value);
73 ThinBox { ptr, _marker: PhantomData }
74 }
7576/// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
77 /// the stack. Returns an error if allocation fails, instead of aborting.
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// #![feature(allocator_api)]
83 /// #![feature(thin_box)]
84 /// use std::boxed::ThinBox;
85 ///
86 /// let five = ThinBox::try_new(5)?;
87 /// # Ok::<(), std::alloc::AllocError>(())
88 /// ```
89 ///
90 /// [`Metadata`]: core::ptr::Pointee::Metadata
91pub fn try_new(value: T) -> Result<Self, core::alloc::AllocError> {
92let meta = ptr::metadata(&value);
93 WithOpaqueHeader::try_new(meta, value).map(|ptr| ThinBox { ptr, _marker: PhantomData })
94 }
95}
9697#[unstable(feature = "thin_box", issue = "92791")]
98impl<Dyn: ?Sized> ThinBox<Dyn> {
99/// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
100 /// the stack.
101 ///
102 /// # Examples
103 ///
104 /// ```
105 /// #![feature(thin_box)]
106 /// use std::boxed::ThinBox;
107 ///
108 /// let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]);
109 /// ```
110 ///
111 /// [`Metadata`]: core::ptr::Pointee::Metadata
112#[cfg(not(no_global_oom_handling))]
113pub fn new_unsize<T>(value: T) -> Self
114where
115T: Unsize<Dyn>,
116 {
117if mem::size_of::<T>() == 0 {
118let ptr = WithOpaqueHeader::new_unsize_zst::<Dyn, T>(value);
119 ThinBox { ptr, _marker: PhantomData }
120 } else {
121let meta = ptr::metadata(&value as &Dyn);
122let ptr = WithOpaqueHeader::new(meta, value);
123 ThinBox { ptr, _marker: PhantomData }
124 }
125 }
126}
127128#[unstable(feature = "thin_box", issue = "92791")]
129impl<T: ?Sized + Debug> Debug for ThinBox<T> {
130fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
131 Debug::fmt(self.deref(), f)
132 }
133}
134135#[unstable(feature = "thin_box", issue = "92791")]
136impl<T: ?Sized + Display> Display for ThinBox<T> {
137fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
138 Display::fmt(self.deref(), f)
139 }
140}
141142#[unstable(feature = "thin_box", issue = "92791")]
143impl<T: ?Sized> Deref for ThinBox<T> {
144type Target = T;
145146fn deref(&self) -> &T {
147let value = self.data();
148let metadata = self.meta();
149let pointer = ptr::from_raw_parts(value as *const (), metadata);
150unsafe { &*pointer }
151 }
152}
153154#[unstable(feature = "thin_box", issue = "92791")]
155impl<T: ?Sized> DerefMut for ThinBox<T> {
156fn deref_mut(&mut self) -> &mut T {
157let value = self.data();
158let metadata = self.meta();
159let pointer = ptr::from_raw_parts_mut::<T>(value as *mut (), metadata);
160unsafe { &mut *pointer }
161 }
162}
163164#[unstable(feature = "thin_box", issue = "92791")]
165impl<T: ?Sized> Drop for ThinBox<T> {
166fn drop(&mut self) {
167unsafe {
168let value = self.deref_mut();
169let value = value as *mut T;
170self.with_header().drop::<T>(value);
171 }
172 }
173}
174175#[unstable(feature = "thin_box", issue = "92791")]
176impl<T: ?Sized> ThinBox<T> {
177fn meta(&self) -> <T as Pointee>::Metadata {
178// Safety:
179 // - 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> {
224 WithHeader::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 };
241242unsafe {
243// Note: It's UB to pass a layout with a zero size to `alloc::alloc`, so
244 // we use `layout.dangling()` for this case, which should have a valid
245 // alignment for both `T` and `H`.
246let ptr = if layout.size() == 0 {
247// Some paranoia checking, mostly so that the ThinBox tests are
248 // more able to catch issues.
249debug_assert!(value_offset == 0 && T::IS_ZST && H::IS_ZST);
250 layout.dangling()
251 } else {
252let ptr = 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`.
258let ptr = ptr.add(value_offset) as *mut _;
259260 NonNull::new_unchecked(ptr)
261 };
262263let result = WithHeader(ptr, PhantomData);
264 ptr::write(result.header(), header);
265 ptr::write(result.value().cast(), value);
266267 result
268 }
269 }
270271/// Non-panicking version of `new`.
272 /// Any error is returned as `Err(core::alloc::AllocError)`.
273fn try_new<T>(header: H, value: T) -> Result<WithHeader<H>, core::alloc::AllocError> {
274let value_layout = Layout::new::<T>();
275let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
276return Err(core::alloc::AllocError);
277 };
278279unsafe {
280// Note: It's UB to pass a layout with a zero size to `alloc::alloc`, so
281 // we use `layout.dangling()` for this case, which should have a valid
282 // alignment for both `T` and `H`.
283let ptr = if layout.size() == 0 {
284// Some paranoia checking, mostly so that the ThinBox tests are
285 // more able to catch issues.
286debug_assert!(
287 value_offset == 0 && mem::size_of::<T>() == 0 && mem::size_of::<H>() == 0
288);
289 layout.dangling()
290 } else {
291let ptr = alloc::alloc(layout);
292if ptr.is_null() {
293return Err(core::alloc::AllocError);
294 }
295296// Safety:
297 // - The size is at least `aligned_header_size`.
298let ptr = ptr.add(value_offset) as *mut _;
299300 NonNull::new_unchecked(ptr)
301 };
302303let result = WithHeader(ptr, PhantomData);
304 ptr::write(result.header(), header);
305 ptr::write(result.value().cast(), value);
306307Ok(result)
308 }
309 }
310311// `Dyn` is `?Sized` type like `[u32]`, and `T` is ZST type like `[u32; 0]`.
312#[cfg(not(no_global_oom_handling))]
313fn new_unsize_zst<Dyn, T>(value: T) -> WithHeader<H>
314where
315Dyn: Pointee<Metadata = H> + ?Sized,
316 T: Unsize<Dyn>,
317 {
318assert!(mem::size_of::<T>() == 0);
319320const fn max(a: usize, b: usize) -> usize {
321if a > b { a } else { b }
322 }
323324// Compute a pointer to the right metadata. This will point to the beginning
325 // of the header, past the padding, so the assigned type makes sense.
326 // It also ensures that the address at the end of the header is sufficiently
327 // aligned for T.
328let alloc: &<Dyn as Pointee>::Metadata = const {
329// FIXME: just call `WithHeader::alloc_layout` with size reset to 0.
330 // Currently that's blocked on `Layout::extend` not being `const fn`.
331332let alloc_align =
333 max(mem::align_of::<T>(), mem::align_of::<<Dyn as Pointee>::Metadata>());
334335let alloc_size =
336 max(mem::align_of::<T>(), mem::size_of::<<Dyn as Pointee>::Metadata>());
337338unsafe {
339// SAFETY: align is power of two because it is the maximum of two alignments.
340let alloc: *mut u8 = const_allocate(alloc_size, alloc_align);
341342let metadata_offset =
343 alloc_size.checked_sub(mem::size_of::<<Dyn as Pointee>::Metadata>()).unwrap();
344// SAFETY: adding offset within the allocation.
345let metadata_ptr: *mut <Dyn as Pointee>::Metadata =
346 alloc.add(metadata_offset).cast();
347// SAFETY: `*metadata_ptr` is within the allocation.
348metadata_ptr.write(ptr::metadata::<Dyn>(ptr::dangling::<T>() as *const Dyn));
349350// SAFETY: we have just written the metadata.
351&*(metadata_ptr)
352 }
353 };
354355// SAFETY: `alloc` points to `<Dyn as Pointee>::Metadata`, so addition stays in-bounds.
356let value_ptr =
357unsafe { (alloc as *const <Dyn as Pointee>::Metadata).add(1) }.cast::<T>().cast_mut();
358debug_assert!(value_ptr.is_aligned());
359 mem::forget(value);
360 WithHeader(NonNull::new(value_ptr.cast()).unwrap(), PhantomData)
361 }
362363// Safety:
364 // - Assumes that either `value` can be dereferenced, or is the
365 // `NonNull::dangling()` we use when both `T` and `H` are ZSTs.
366unsafe fn drop<T: ?Sized>(&self, value: *mut T) {
367struct DropGuard<H> {
368 ptr: NonNull<u8>,
369 value_layout: Layout,
370 _marker: PhantomData<H>,
371 }
372373impl<H> Drop for DropGuard<H> {
374fn drop(&mut self) {
375// All ZST are allocated statically.
376if self.value_layout.size() == 0 {
377return;
378 }
379380unsafe {
381// SAFETY: Layout must have been computable if we're in drop
382let (layout, value_offset) =
383 WithHeader::<H>::alloc_layout(self.value_layout).unwrap_unchecked();
384385// Since we only allocate for non-ZSTs, the layout size cannot be zero.
386debug_assert!(layout.size() != 0);
387 alloc::dealloc(self.ptr.as_ptr().sub(value_offset), layout);
388 }
389 }
390 }
391392unsafe {
393// `_guard` will deallocate the memory when dropped, even if `drop_in_place` unwinds.
394let _guard = DropGuard {
395 ptr: self.0,
396 value_layout: Layout::for_value_raw(value),
397 _marker: PhantomData::<H>,
398 };
399400// We only drop the value because the Pointee trait requires that the metadata is copy
401 // aka trivially droppable.
402ptr::drop_in_place::<T>(value);
403 }
404 }
405406fn header(&self) -> *mut H {
407// Safety:
408 // - At least `size_of::<H>()` bytes are allocated ahead of the pointer.
409 // - We know that H will be aligned because the middle pointer is aligned to the greater
410 // of the alignment of the header and the data and the header size includes the padding
411 // needed to align the header. Subtracting the header size from the aligned data pointer
412 // will always result in an aligned header pointer, it just may not point to the
413 // beginning of the allocation.
414let hp = unsafe { self.0.as_ptr().sub(Self::header_size()) as *mut H };
415debug_assert!(hp.is_aligned());
416 hp
417 }
418419fn value(&self) -> *mut u8 {
420self.0.as_ptr()
421 }
422423const fn header_size() -> usize {
424 mem::size_of::<H>()
425 }
426427fn alloc_layout(value_layout: Layout) -> Result<(Layout, usize), LayoutError> {
428 Layout::new::<H>().extend(value_layout)
429 }
430}
431432#[unstable(feature = "thin_box", issue = "92791")]
433impl<T: ?Sized + Error> Error for ThinBox<T> {
434fn source(&self) -> Option<&(dyn Error + 'static)> {
435self.deref().source()
436 }
437}