Skip to main content

alloc/boxed/
thin.rs

1//! Based on
2//! <https://github.com/matthieu-m/rfc2580/blob/b58d1d3cba0d4b5e859d3617ea2d0943aaa31329/examples/thin.rs>
3//! by matthieu-m
4
5use 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::{DropGuard, SizedTypeProperties};
15use core::ops::{Deref, DerefMut};
16use core::ptr::{self, NonNull, Pointee};
17
18use crate::alloc::{self, Layout, LayoutError};
19
20/// 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.
41    ptr: WithOpaqueHeader,
42    _marker: PhantomData<T>,
43}
44
45/// `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> Send for ThinBox<T> {}
48
49/// `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> Sync for ThinBox<T> {}
52
53#[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))]
69    pub fn new(value: T) -> Self {
70        let meta = ptr::metadata(&value);
71        let ptr = WithOpaqueHeader::new(meta, value);
72        ThinBox { ptr, _marker: PhantomData }
73    }
74
75    /// 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(allocator_api)]
82    /// #![feature(thin_box)]
83    /// use std::boxed::ThinBox;
84    ///
85    /// let five = ThinBox::try_new(5)?;
86    /// # Ok::<(), std::alloc::AllocError>(())
87    /// ```
88    ///
89    /// [`Metadata`]: core::ptr::Pointee::Metadata
90    pub fn try_new(value: T) -> Result<Self, core::alloc::AllocError> {
91        let meta = ptr::metadata(&value);
92        WithOpaqueHeader::try_new(meta, value).map(|ptr| ThinBox { ptr, _marker: PhantomData })
93    }
94}
95
96#[unstable(feature = "thin_box", issue = "92791")]
97impl<Dyn: ?Sized> ThinBox<Dyn> {
98    /// Moves a type to the heap with its [`Metadata`] stored in the heap allocation instead of on
99    /// the stack.
100    ///
101    /// # Examples
102    ///
103    /// ```
104    /// #![feature(thin_box)]
105    /// use std::boxed::ThinBox;
106    ///
107    /// let thin_slice = ThinBox::<[i32]>::new_unsize([1, 2, 3, 4]);
108    /// ```
109    ///
110    /// [`Metadata`]: core::ptr::Pointee::Metadata
111    #[cfg(not(no_global_oom_handling))]
112    pub fn new_unsize<T>(value: T) -> Self
113    where
114        T: Unsize<Dyn>,
115    {
116        if T::IS_ZST {
117            let ptr = WithOpaqueHeader::new_unsize_zst::<Dyn, T>(value);
118            ThinBox { ptr, _marker: PhantomData }
119        } else {
120            let meta = ptr::metadata(&value as &Dyn);
121            let ptr = WithOpaqueHeader::new(meta, value);
122            ThinBox { ptr, _marker: PhantomData }
123        }
124    }
125}
126
127#[unstable(feature = "thin_box", issue = "92791")]
128impl<T: ?Sized + Debug> Debug for ThinBox<T> {
129    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
130        Debug::fmt(self.deref(), f)
131    }
132}
133
134#[unstable(feature = "thin_box", issue = "92791")]
135impl<T: ?Sized + Display> Display for ThinBox<T> {
136    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
137        Display::fmt(self.deref(), f)
138    }
139}
140
141#[unstable(feature = "thin_box", issue = "92791")]
142impl<T: ?Sized> Deref for ThinBox<T> {
143    type Target = T;
144
145    fn deref(&self) -> &T {
146        let value = self.data();
147        let metadata = self.meta();
148        let pointer = ptr::from_raw_parts(value as *const (), metadata);
149        // SAFETY: &ThinBox<T> points to a valid pointer for T.
150        unsafe { &*pointer }
151    }
152}
153
154#[unstable(feature = "thin_box", issue = "92791")]
155impl<T: ?Sized> DerefMut for ThinBox<T> {
156    fn deref_mut(&mut self) -> &mut T {
157        let value = self.data();
158        let metadata = self.meta();
159        let pointer = ptr::from_raw_parts_mut::<T>(value as *mut (), metadata);
160        // SAFETY: &mut ThinBox<T> points to a valid and unique pointer for T.
161        unsafe { &mut *pointer }
162    }
163}
164
165#[unstable(feature = "thin_box", issue = "92791")]
166impl<T: ?Sized> Drop for ThinBox<T> {
167    fn drop(&mut self) {
168        // ignore-tidy-undocumented-unsafe
169        unsafe {
170            let value = self.deref_mut();
171            let value = value as *mut T;
172            self.with_header().drop::<T>(value);
173        }
174    }
175}
176
177#[unstable(feature = "thin_box", issue = "92791")]
178impl<T: ?Sized> ThinBox<T> {
179    fn meta(&self) -> <T as Pointee>::Metadata {
180        // SAFETY: NonNull and valid.
181        unsafe { *self.with_header().header() }
182    }
183
184    fn data(&self) -> *mut u8 {
185        self.with_header().value()
186    }
187
188    fn with_header(&self) -> &WithHeader<<T as Pointee>::Metadata> {
189        // SAFETY: both types are transparent to `NonNull<u8>`
190        unsafe { &*((&raw const self.ptr) as *const WithHeader<_>) }
191    }
192}
193
194/// A pointer to type-erased data, guaranteed to either be:
195/// 1. `NonNull::dangling()`, in the case where both the pointee (`T`) and
196///    metadata (`H`) are ZSTs.
197/// 2. A pointer to a valid `T` that has a header `H` directly before the
198///    pointed-to location.
199#[repr(transparent)]
200struct WithHeader<H>(NonNull<u8>, PhantomData<H>);
201
202/// An opaque representation of `WithHeader<H>` to avoid the
203/// projection invariance of `<T as Pointee>::Metadata`.
204#[repr(transparent)]
205struct WithOpaqueHeader(NonNull<u8>);
206
207impl WithOpaqueHeader {
208    #[cfg(not(no_global_oom_handling))]
209    fn new<H, T>(header: H, value: T) -> Self {
210        let ptr = WithHeader::new(header, value);
211        Self(ptr.0)
212    }
213
214    #[cfg(not(no_global_oom_handling))]
215    fn new_unsize_zst<Dyn, T>(value: T) -> Self
216    where
217        Dyn: ?Sized,
218        T: Unsize<Dyn>,
219    {
220        let ptr = WithHeader::<<Dyn as Pointee>::Metadata>::new_unsize_zst::<Dyn, T>(value);
221        Self(ptr.0)
222    }
223
224    fn try_new<H, T>(header: H, value: T) -> Result<Self, core::alloc::AllocError> {
225        WithHeader::try_new(header, value).map(|ptr| Self(ptr.0))
226    }
227}
228
229impl<H> WithHeader<H> {
230    #[cfg(not(no_global_oom_handling))]
231    fn new<T>(header: H, value: T) -> WithHeader<H> {
232        let value_layout = Layout::new::<T>();
233        let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
234            // We pass an empty layout here because we do not know which layout caused the
235            // arithmetic overflow in `Layout::extend` and `handle_alloc_error` takes `Layout` as
236            // its argument rather than `Result<Layout, LayoutError>`, also this function has been
237            // stable since 1.28 ._.
238            //
239            // On the other hand, look at this gorgeous turbofish!
240            alloc::handle_alloc_error(Layout::new::<()>());
241        };
242
243        // ignore-tidy-undocumented-unsafe
244        unsafe {
245            // Note: It's UB to pass a layout with a zero size to `alloc::alloc`, so
246            // we use `layout.dangling()` for this case, which should have a valid
247            // alignment for both `T` and `H`.
248            let ptr = if layout.size() == 0 {
249                // Some paranoia checking, mostly so that the ThinBox tests are
250                // more able to catch issues.
251                if 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);
252                layout.dangling_ptr()
253            } else {
254                let ptr = alloc::alloc(layout);
255                if ptr.is_null() {
256                    alloc::handle_alloc_error(layout);
257                }
258                // Safety:
259                // - The size is at least `aligned_header_size`.
260                let ptr = ptr.add(value_offset) as *mut _;
261
262                NonNull::new_unchecked(ptr)
263            };
264
265            let result = WithHeader(ptr, PhantomData);
266            ptr::write(result.header(), header);
267            ptr::write(result.value().cast(), value);
268
269            result
270        }
271    }
272
273    /// Non-panicking version of `new`.
274    /// Any error is returned as `Err(core::alloc::AllocError)`.
275    fn try_new<T>(header: H, value: T) -> Result<WithHeader<H>, core::alloc::AllocError> {
276        let value_layout = Layout::new::<T>();
277        let Ok((layout, value_offset)) = Self::alloc_layout(value_layout) else {
278            return Err(core::alloc::AllocError);
279        };
280
281        // ignore-tidy-undocumented-unsafe
282        unsafe {
283            // Note: It's UB to pass a layout with a zero size to `alloc::alloc`, so
284            // we use `layout.dangling()` for this case, which should have a valid
285            // alignment for both `T` and `H`.
286            let ptr = if layout.size() == 0 {
287                // Some paranoia checking, mostly so that the ThinBox tests are
288                // more able to catch issues.
289                if 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);
290                layout.dangling_ptr()
291            } else {
292                let ptr = alloc::alloc(layout);
293                if ptr.is_null() {
294                    return Err(core::alloc::AllocError);
295                }
296
297                // Safety:
298                // - The size is at least `aligned_header_size`.
299                let ptr = ptr.add(value_offset) as *mut _;
300
301                NonNull::new_unchecked(ptr)
302            };
303
304            let result = WithHeader(ptr, PhantomData);
305            ptr::write(result.header(), header);
306            ptr::write(result.value().cast(), value);
307
308            Ok(result)
309        }
310    }
311
312    // `Dyn` is `?Sized` type like `[u32]`, and `T` is ZST type like `[u32; 0]`.
313    #[cfg(not(no_global_oom_handling))]
314    fn new_unsize_zst<Dyn, T>(value: T) -> WithHeader<H>
315    where
316        Dyn: Pointee<Metadata = H> + ?Sized,
317        T: Unsize<Dyn>,
318    {
319        if !T::IS_ZST { ::core::panicking::panic("assertion failed: T::IS_ZST") };assert!(T::IS_ZST);
320
321        const fn max(a: usize, b: usize) -> usize {
322            if a > b { a } else { b }
323        }
324
325        // Compute a pointer to the right metadata. This will point to the beginning
326        // of the header, past the padding, so the assigned type makes sense.
327        // It also ensures that the address at the end of the header is sufficiently
328        // aligned for T.
329        let alloc: &<Dyn as Pointee>::Metadata = const {
330            // FIXME: just call `WithHeader::alloc_layout` with size reset to 0.
331            // Currently that's blocked on `Layout::extend` not being `const fn`.
332
333            let alloc_align = max(align_of::<T>(), align_of::<<Dyn as Pointee>::Metadata>());
334
335            let alloc_size = max(align_of::<T>(), size_of::<<Dyn as Pointee>::Metadata>());
336
337            // SAFETY: align is power of two because it is the maximum of two alignments.
338            let alloc: *mut u8 = unsafe { const_allocate(alloc_size, alloc_align) };
339
340            let metadata_offset =
341                alloc_size.checked_sub(size_of::<<Dyn as Pointee>::Metadata>()).unwrap();
342            let metadata_ptr: *mut <Dyn as Pointee>::Metadata =
343                // SAFETY: adding offset within the allocation.
344                unsafe { alloc.add(metadata_offset).cast() };
345            // SAFETY: `*metadata_ptr` is within the allocation.
346            unsafe {
347                metadata_ptr.write(ptr::metadata::<Dyn>(ptr::dangling::<T>() as *const Dyn));
348            }
349            // SAFETY: valid heap allocation
350            unsafe { const_make_global(alloc) };
351            // SAFETY: we have just written the metadata.
352            unsafe { &*metadata_ptr }
353        };
354
355        let value_ptr =
356            // SAFETY: `alloc` points to `<Dyn as Pointee>::Metadata`, so addition stays in-bounds.
357            unsafe { (alloc as *const <Dyn as Pointee>::Metadata).add(1) }.cast::<T>().cast_mut();
358        if true {
    if !value_ptr.is_aligned() {
        ::core::panicking::panic("assertion failed: value_ptr.is_aligned()")
    };
};debug_assert!(value_ptr.is_aligned());
359        mem::forget(value);
360        WithHeader(NonNull::new(value_ptr.cast()).unwrap(), PhantomData)
361    }
362
363    // Safety:
364    // - Assumes that either `value` can be dereferenced, or is the
365    //   `NonNull::dangling()` we use when both `T` and `H` are ZSTs.
366    unsafe fn drop<T: ?Sized>(&self, value: *mut T) {
367        // SAFETY: Caller ensures `value` is valid.
368        let value_layout = unsafe { Layout::for_value_raw(value) };
369
370        let _guard;
371
372        // All ZST are allocated statically.
373        if value_layout.size() != 0 {
374            _guard = DropGuard::new(self.0, |ptr| {
375                let layout = WithHeader::<H>::alloc_layout(value_layout);
376                // SAFETY: Layout must have been computable if we're in this callback
377                let (layout, value_offset) = unsafe { layout.unwrap_unchecked() };
378                // Since we only allocate for non-ZSTs, the layout size cannot be zero.
379                if true {
    {
        match (&layout.size(), &0) {
            (left_val, right_val) => {
                if *left_val == *right_val {
                    let kind = ::core::panicking::AssertKind::Ne;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_ne!(layout.size(), 0);
380                // SAFETY: We own the allocation with `layout` at `ptr - value_offset`.
381                unsafe { alloc::dealloc(ptr.as_ptr().sub(value_offset), layout) };
382            });
383        }
384
385        // We only drop the value because the Pointee trait requires that the metadata is copy
386        // aka trivially droppable.
387        // SAFETY: We're the only droppers of `value` and it's not dropped again.
388        unsafe { ptr::drop_in_place::<T>(value) };
389    }
390
391    fn header(&self) -> *mut H {
392        // SAFETY:
393        //  - At least `size_of::<H>()` bytes are allocated ahead of the pointer.
394        //  - We know that H will be aligned because the middle pointer is aligned to the greater
395        //    of the alignment of the header and the data and the header size includes the padding
396        //    needed to align the header. Subtracting the header size from the aligned data pointer
397        //    will always result in an aligned header pointer, it just may not point to the
398        //    beginning of the allocation.
399        let hp = unsafe { self.0.as_ptr().sub(Self::header_size()) as *mut H };
400        if true {
    if !hp.is_aligned() {
        ::core::panicking::panic("assertion failed: hp.is_aligned()")
    };
};debug_assert!(hp.is_aligned());
401        hp
402    }
403
404    fn value(&self) -> *mut u8 {
405        self.0.as_ptr()
406    }
407
408    const fn header_size() -> usize {
409        size_of::<H>()
410    }
411
412    fn alloc_layout(value_layout: Layout) -> Result<(Layout, usize), LayoutError> {
413        Layout::new::<H>().extend(value_layout)
414    }
415}
416
417#[unstable(feature = "thin_box", issue = "92791")]
418impl<T: ?Sized + Error> Error for ThinBox<T> {
419    fn source(&self) -> Option<&(dyn Error + 'static)> {
420        self.deref().source()
421    }
422}
423
424#[cfg(not(no_global_oom_handling))]
425#[unstable(feature = "thin_box", issue = "92791")]
426impl<T> From<T> for ThinBox<T> {
427    #[inline(always)]
428    fn from(value: T) -> Self {
429        Self::new(value)
430    }
431}