Skip to main content

alloc/
boxed.rs

1//! The `Box<T>` type for heap allocation.
2//!
3//! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
4//! heap allocation in Rust. Boxes provide ownership for this allocation, and
5//! drop their contents when they go out of scope. Boxes also ensure that they
6//! never allocate more than `isize::MAX` bytes.
7//!
8//! # Examples
9//!
10//! Move a value from the stack to the heap by creating a [`Box`]:
11//!
12//! ```
13//! let val: u8 = 5;
14//! let boxed: Box<u8> = Box::new(val);
15//! ```
16//!
17//! Move a value from a [`Box`] back to the stack by [dereferencing]:
18//!
19//! ```
20//! let boxed: Box<u8> = Box::new(5);
21//! let val: u8 = *boxed;
22//! ```
23//!
24//! Creating a recursive data structure:
25//!
26//! ```
27//! # #[allow(dead_code)]
28//! #[derive(Debug)]
29//! enum List<T> {
30//!     Cons(T, Box<List<T>>),
31//!     Nil,
32//! }
33//!
34//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
35//! println!("{list:?}");
36//! ```
37//!
38//! This will print `Cons(1, Cons(2, Nil))`.
39//!
40//! Recursive structures must be boxed, because if the definition of `Cons`
41//! looked like this:
42//!
43//! ```compile_fail,E0072
44//! # enum List<T> {
45//! Cons(T, List<T>),
46//! # }
47//! ```
48//!
49//! It wouldn't work. This is because the size of a `List` depends on how many
50//! elements are in the list, and so we don't know how much memory to allocate
51//! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
52//! big `Cons` needs to be.
53//!
54//! # Memory layout
55//!
56//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for its allocation. It is
57//! valid to convert both ways between a [`Box`] and a raw pointer allocated with the [`Global`]
58//! allocator, given that the [`Layout`] used with the allocator is correct for the type and the raw
59//! pointer points to a valid value of the right type. More precisely, a `value: *mut T` that has
60//! been allocated with the [`Global`] allocator with `Layout::for_value(&*value)` may be converted
61//! into a box using [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut T`
62//! obtained from [`Box::<T>::into_raw`] may be deallocated using the [`Global`] allocator with
63//! [`Layout::for_value(&*value)`].
64//!
65//! For zero-sized values, the `Box` pointer has to be non-null and sufficiently aligned. The
66//! recommended way to build a Box to a ZST if `Box::new` cannot be used is to use
67//! [`ptr::NonNull::dangling`].
68//!
69//! On top of these basic layout requirements, a `Box<T>` must point to a valid value of `T`.
70//!
71//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
72//! as a single pointer and is also ABI-compatible with C pointers
73//! (i.e. the C type `T*`). This means that if you have extern "C"
74//! Rust functions that will be called from C, you can define those
75//! Rust functions using `Box<T>` types, and use `T*` as corresponding
76//! type on the C side. As an example, consider this C header which
77//! declares functions that create and destroy some kind of `Foo`
78//! value:
79//!
80//! ```c
81//! /* C header */
82//!
83//! /* Returns ownership to the caller */
84//! struct Foo* foo_new(void);
85//!
86//! /* Takes ownership from the caller; no-op when invoked with null */
87//! void foo_delete(struct Foo*);
88//! ```
89//!
90//! These two functions might be implemented in Rust as follows. Here, the
91//! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
92//! the ownership constraints. Note also that the nullable argument to
93//! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
94//! cannot be null.
95//!
96//! ```
97//! #[repr(C)]
98//! pub struct Foo;
99//!
100//! #[unsafe(no_mangle)]
101//! pub extern "C" fn foo_new() -> Box<Foo> {
102//!     Box::new(Foo)
103//! }
104//!
105//! #[unsafe(no_mangle)]
106//! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
107//! ```
108//!
109//! Even though `Box<T>` has the same representation and C ABI as a C pointer,
110//! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
111//! and expect things to work. `Box<T>` values will always be fully aligned,
112//! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
113//! free the value with the global allocator. In general, the best practice
114//! is to only use `Box<T>` for pointers that originated from the global
115//! allocator.
116//!
117//! **Important.** At least at present, you should avoid using
118//! `Box<T>` types for functions that are defined in C but invoked
119//! from Rust. In those cases, you should directly mirror the C types
120//! as closely as possible. Using types like `Box<T>` where the C
121//! definition is just using `T*` can lead to undefined behavior, as
122//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
123//!
124//! # Considerations for unsafe code
125//!
126//! **Warning: This section is not normative and is subject to change, possibly
127//! being relaxed in the future! It is a simplified summary of the rules
128//! currently implemented in the compiler.**
129//!
130//! The aliasing rules for `Box<T>` are the same as for `&mut T`. `Box<T>`
131//! asserts uniqueness over its content. Using raw pointers derived from a box
132//! after that box has been mutated through, moved or borrowed as `&mut T`
133//! is not allowed. For more guidance on working with box from unsafe code, see
134//! [rust-lang/unsafe-code-guidelines#326][ucg#326].
135//!
136//! # Editions
137//!
138//! A special case exists for the implementation of `IntoIterator` for arrays on the Rust 2021
139//! edition, as documented [here][array]. Unfortunately, it was later found that a similar
140//! workaround should be added for boxed slices, and this was applied in the 2024 edition.
141//!
142//! Specifically, `IntoIterator` is implemented for `Box<[T]>` on all editions, but specific calls
143//! to `into_iter()` for boxed slices will defer to the slice implementation on editions before
144//! 2024:
145//!
146//! ```rust,edition2021
147//! // Rust 2015, 2018, and 2021:
148//!
149//! # #![allow(boxed_slice_into_iter)] // override our `deny(warnings)`
150//! let boxed_slice: Box<[i32]> = vec![0; 3].into_boxed_slice();
151//!
152//! // This creates a slice iterator, producing references to each value.
153//! for item in boxed_slice.into_iter().enumerate() {
154//!     let (i, x): (usize, &i32) = item;
155//!     println!("boxed_slice[{i}] = {x}");
156//! }
157//!
158//! // The `boxed_slice_into_iter` lint suggests this change for future compatibility:
159//! for item in boxed_slice.iter().enumerate() {
160//!     let (i, x): (usize, &i32) = item;
161//!     println!("boxed_slice[{i}] = {x}");
162//! }
163//!
164//! // You can explicitly iterate a boxed slice by value using `IntoIterator::into_iter`
165//! for item in IntoIterator::into_iter(boxed_slice).enumerate() {
166//!     let (i, x): (usize, i32) = item;
167//!     println!("boxed_slice[{i}] = {x}");
168//! }
169//! ```
170//!
171//! Similar to the array implementation, this may be modified in the future to remove this override,
172//! and it's best to avoid relying on this edition-dependent behavior if you wish to preserve
173//! compatibility with future versions of the compiler.
174//!
175//! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
176//! [ucg#326]: https://github.com/rust-lang/unsafe-code-guidelines/issues/326
177//! [dereferencing]: core::ops::Deref
178//! [`Box::<T>::from_raw(value)`]: Box::from_raw
179//! [`Global`]: crate::alloc::Global
180//! [`Layout`]: crate::alloc::Layout
181//! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
182//! [valid]: ptr#safety
183
184#![stable(feature = "rust1", since = "1.0.0")]
185
186use core::borrow::{Borrow, BorrowMut};
187use core::clone::CloneToUninit;
188use core::cmp::Ordering;
189use core::error::{self, Error};
190use core::fmt;
191use core::future::Future;
192use core::hash::{Hash, Hasher};
193use core::marker::{Tuple, Unsize};
194#[cfg(not(no_global_oom_handling))]
195use core::mem::MaybeUninit;
196use core::mem::{self, SizedTypeProperties};
197use core::ops::{
198    AsyncFn, AsyncFnMut, AsyncFnOnce, CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut,
199    DerefPure, DispatchFromDyn, LegacyReceiver,
200};
201#[cfg(not(no_global_oom_handling))]
202use core::ops::{Residual, Try};
203use core::pin::{Pin, PinCoerceUnsized};
204use core::ptr::{self, NonNull, Unique};
205use core::task::{Context, Poll};
206
207#[cfg(not(no_global_oom_handling))]
208use crate::alloc::handle_alloc_error;
209use crate::alloc::{AllocError, Allocator, Global, Layout};
210use crate::raw_vec::RawVec;
211#[cfg(not(no_global_oom_handling))]
212use crate::str::from_boxed_utf8_unchecked;
213
214/// Conversion related impls for `Box<_>` (`From`, `downcast`, etc)
215mod convert;
216/// Iterator related impls for `Box<_>`.
217mod iter;
218/// [`ThinBox`] implementation.
219mod thin;
220
221#[unstable(feature = "thin_box", issue = "92791")]
222pub use thin::ThinBox;
223
224/// A pointer type that uniquely owns a heap allocation of type `T`.
225///
226/// See the [module-level documentation](../../std/boxed/index.html) for more.
227#[lang = "owned_box"]
228#[fundamental]
229#[stable(feature = "rust1", since = "1.0.0")]
230#[rustc_insignificant_dtor]
231#[doc(search_unbox)]
232// The declaration of the `Box` struct must be kept in sync with the
233// compiler or ICEs will happen.
234pub struct Box<
235    T: ?Sized,
236    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
237>(Unique<T>, A);
238
239/// Monomorphic function for allocating an uninit `Box`.
240#[inline]
241// The is a separate function to avoid doing it in every generic version, but it
242// looks small to the mir inliner (particularly in panic=abort) so leave it to
243// the backend to decide whether pulling it in everywhere is worth doing.
244#[rustc_no_mir_inline]
245#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
246#[cfg(not(no_global_oom_handling))]
247fn box_new_uninit(layout: Layout) -> *mut u8 {
248    match Global.allocate(layout) {
249        Ok(ptr) => ptr.as_mut_ptr(),
250        Err(_) => handle_alloc_error(layout),
251    }
252}
253
254/// Helper for `vec!`.
255///
256/// This is unsafe, but has to be marked as safe or else we couldn't use it in `vec!`.
257#[doc(hidden)]
258#[unstable(feature = "liballoc_internals", issue = "none")]
259#[inline(always)]
260#[cfg(not(no_global_oom_handling))]
261#[rustc_diagnostic_item = "box_assume_init_into_vec_unsafe"]
262pub fn box_assume_init_into_vec_unsafe<T, const N: usize>(
263    b: Box<MaybeUninit<[T; N]>>,
264) -> crate::vec::Vec<T> {
265    unsafe { (b.assume_init() as Box<[T]>).into_vec() }
266}
267
268impl<T> Box<T> {
269    /// Allocates memory on the heap and then places `x` into it.
270    ///
271    /// This doesn't actually allocate if `T` is zero-sized.
272    ///
273    /// # Examples
274    ///
275    /// ```
276    /// let five = Box::new(5);
277    /// ```
278    #[cfg(not(no_global_oom_handling))]
279    #[ferrocene::prevalidated]
280    #[inline(always)]
281    #[stable(feature = "rust1", since = "1.0.0")]
282    #[must_use]
283    #[rustc_diagnostic_item = "box_new"]
284    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
285    pub fn new(x: T) -> Self {
286        // This is `Box::new_uninit` but inlined to avoid build time regressions.
287        let ptr = box_new_uninit(<T as SizedTypeProperties>::LAYOUT) as *mut T;
288        // Nothing below can panic so we do not have to worry about deallocating `ptr`.
289        // SAFETY: we just allocated the box to store `x`.
290        unsafe { core::intrinsics::write_via_move(ptr, x) };
291        // SAFETY: we just initialized `b`.
292        unsafe { mem::transmute(ptr) }
293    }
294
295    /// Constructs a new box with uninitialized contents.
296    ///
297    /// # Examples
298    ///
299    /// ```
300    /// let mut five = Box::<u32>::new_uninit();
301    /// // Deferred initialization:
302    /// five.write(5);
303    /// let five = unsafe { five.assume_init() };
304    ///
305    /// assert_eq!(*five, 5)
306    /// ```
307    #[cfg(not(no_global_oom_handling))]
308    #[stable(feature = "new_uninit", since = "1.82.0")]
309    #[must_use]
310    #[inline(always)]
311    #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
312    pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
313        // This is the same as `Self::new_uninit_in(Global)`, but manually inlined (just like
314        // `Box::new`).
315
316        // SAFETY:
317        // - If `allocate` succeeds, the returned pointer exactly matches what `Box` needs.
318        unsafe { mem::transmute(box_new_uninit(<T as SizedTypeProperties>::LAYOUT)) }
319    }
320
321    /// Constructs a new `Box` with uninitialized contents, with the memory
322    /// being filled with `0` bytes.
323    ///
324    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
325    /// of this method.
326    ///
327    /// # Examples
328    ///
329    /// ```
330    /// let zero = Box::<u32>::new_zeroed();
331    /// let zero = unsafe { zero.assume_init() };
332    ///
333    /// assert_eq!(*zero, 0)
334    /// ```
335    ///
336    /// [zeroed]: mem::MaybeUninit::zeroed
337    #[cfg(not(no_global_oom_handling))]
338    #[inline]
339    #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
340    #[must_use]
341    pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
342        Self::new_zeroed_in(Global)
343    }
344
345    /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
346    /// `x` will be pinned in memory and unable to be moved.
347    ///
348    /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
349    /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
350    /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
351    /// construct a (pinned) `Box` in a different way than with [`Box::new`].
352    #[cfg(not(no_global_oom_handling))]
353    #[stable(feature = "pin", since = "1.33.0")]
354    #[must_use]
355    #[inline(always)]
356    pub fn pin(x: T) -> Pin<Box<T>> {
357        Box::new(x).into()
358    }
359
360    /// Allocates memory on the heap then places `x` into it,
361    /// returning an error if the allocation fails
362    ///
363    /// This doesn't actually allocate if `T` is zero-sized.
364    ///
365    /// # Examples
366    ///
367    /// ```
368    /// #![feature(allocator_api)]
369    ///
370    /// let five = Box::try_new(5)?;
371    /// # Ok::<(), std::alloc::AllocError>(())
372    /// ```
373    #[unstable(feature = "allocator_api", issue = "32838")]
374    #[inline]
375    pub fn try_new(x: T) -> Result<Self, AllocError> {
376        Self::try_new_in(x, Global)
377    }
378
379    /// Constructs a new box with uninitialized contents on the heap,
380    /// returning an error if the allocation fails
381    ///
382    /// # Examples
383    ///
384    /// ```
385    /// #![feature(allocator_api)]
386    ///
387    /// let mut five = Box::<u32>::try_new_uninit()?;
388    /// // Deferred initialization:
389    /// five.write(5);
390    /// let five = unsafe { five.assume_init() };
391    ///
392    /// assert_eq!(*five, 5);
393    /// # Ok::<(), std::alloc::AllocError>(())
394    /// ```
395    #[unstable(feature = "allocator_api", issue = "32838")]
396    #[inline]
397    pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
398        Box::try_new_uninit_in(Global)
399    }
400
401    /// Constructs a new `Box` with uninitialized contents, with the memory
402    /// being filled with `0` bytes on the heap
403    ///
404    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
405    /// of this method.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// #![feature(allocator_api)]
411    ///
412    /// let zero = Box::<u32>::try_new_zeroed()?;
413    /// let zero = unsafe { zero.assume_init() };
414    ///
415    /// assert_eq!(*zero, 0);
416    /// # Ok::<(), std::alloc::AllocError>(())
417    /// ```
418    ///
419    /// [zeroed]: mem::MaybeUninit::zeroed
420    #[unstable(feature = "allocator_api", issue = "32838")]
421    #[inline]
422    pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
423        Box::try_new_zeroed_in(Global)
424    }
425
426    /// Maps the value in a box, reusing the allocation if possible.
427    ///
428    /// `f` is called on the value in the box, and the result is returned, also boxed.
429    ///
430    /// Note: this is an associated function, which means that you have
431    /// to call it as `Box::map(b, f)` instead of `b.map(f)`. This
432    /// is so that there is no conflict with a method on the inner type.
433    ///
434    /// # Examples
435    ///
436    /// ```
437    /// #![feature(smart_pointer_try_map)]
438    ///
439    /// let b = Box::new(7);
440    /// let new = Box::map(b, |i| i + 7);
441    /// assert_eq!(*new, 14);
442    /// ```
443    #[cfg(not(no_global_oom_handling))]
444    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
445    pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> Box<U> {
446        if size_of::<T>() == size_of::<U>() && align_of::<T>() == align_of::<U>() {
447            let (value, allocation) = Box::take(this);
448            Box::write(
449                unsafe { mem::transmute::<Box<MaybeUninit<T>>, Box<MaybeUninit<U>>>(allocation) },
450                f(value),
451            )
452        } else {
453            Box::new(f(*this))
454        }
455    }
456
457    /// Attempts to map the value in a box, reusing the allocation if possible.
458    ///
459    /// `f` is called on the value in the box, and if the operation succeeds, the result is
460    /// returned, also boxed.
461    ///
462    /// Note: this is an associated function, which means that you have
463    /// to call it as `Box::try_map(b, f)` instead of `b.try_map(f)`. This
464    /// is so that there is no conflict with a method on the inner type.
465    ///
466    /// # Examples
467    ///
468    /// ```
469    /// #![feature(smart_pointer_try_map)]
470    ///
471    /// let b = Box::new(7);
472    /// let new = Box::try_map(b, u32::try_from).unwrap();
473    /// assert_eq!(*new, 7);
474    /// ```
475    #[cfg(not(no_global_oom_handling))]
476    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
477    pub fn try_map<R>(
478        this: Self,
479        f: impl FnOnce(T) -> R,
480    ) -> <R::Residual as Residual<Box<R::Output>>>::TryType
481    where
482        R: Try,
483        R::Residual: Residual<Box<R::Output>>,
484    {
485        if size_of::<T>() == size_of::<R::Output>() && align_of::<T>() == align_of::<R::Output>() {
486            let (value, allocation) = Box::take(this);
487            try {
488                Box::write(
489                    unsafe {
490                        mem::transmute::<Box<MaybeUninit<T>>, Box<MaybeUninit<R::Output>>>(
491                            allocation,
492                        )
493                    },
494                    f(value)?,
495                )
496            }
497        } else {
498            try { Box::new(f(*this)?) }
499        }
500    }
501}
502
503impl<T, A: Allocator> Box<T, A> {
504    /// Allocates memory in the given allocator then places `x` into it.
505    ///
506    /// This doesn't actually allocate if `T` is zero-sized.
507    ///
508    /// # Examples
509    ///
510    /// ```
511    /// #![feature(allocator_api)]
512    ///
513    /// use std::alloc::System;
514    ///
515    /// let five = Box::new_in(5, System);
516    /// ```
517    #[cfg(not(no_global_oom_handling))]
518    #[unstable(feature = "allocator_api", issue = "32838")]
519    #[must_use]
520    #[inline]
521    pub fn new_in(x: T, alloc: A) -> Self
522    where
523        A: Allocator,
524    {
525        let mut boxed = Self::new_uninit_in(alloc);
526        boxed.write(x);
527        unsafe { boxed.assume_init() }
528    }
529
530    /// Allocates memory in the given allocator then places `x` into it,
531    /// returning an error if the allocation fails
532    ///
533    /// This doesn't actually allocate if `T` is zero-sized.
534    ///
535    /// # Examples
536    ///
537    /// ```
538    /// #![feature(allocator_api)]
539    ///
540    /// use std::alloc::System;
541    ///
542    /// let five = Box::try_new_in(5, System)?;
543    /// # Ok::<(), std::alloc::AllocError>(())
544    /// ```
545    #[unstable(feature = "allocator_api", issue = "32838")]
546    #[inline]
547    pub fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
548    where
549        A: Allocator,
550    {
551        let mut boxed = Self::try_new_uninit_in(alloc)?;
552        boxed.write(x);
553        unsafe { Ok(boxed.assume_init()) }
554    }
555
556    /// Constructs a new box with uninitialized contents in the provided allocator.
557    ///
558    /// # Examples
559    ///
560    /// ```
561    /// #![feature(allocator_api)]
562    ///
563    /// use std::alloc::System;
564    ///
565    /// let mut five = Box::<u32, _>::new_uninit_in(System);
566    /// // Deferred initialization:
567    /// five.write(5);
568    /// let five = unsafe { five.assume_init() };
569    ///
570    /// assert_eq!(*five, 5)
571    /// ```
572    #[unstable(feature = "allocator_api", issue = "32838")]
573    #[cfg(not(no_global_oom_handling))]
574    #[must_use]
575    pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
576    where
577        A: Allocator,
578    {
579        let layout = Layout::new::<mem::MaybeUninit<T>>();
580        // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
581        // That would make code size bigger.
582        match Box::try_new_uninit_in(alloc) {
583            Ok(m) => m,
584            Err(_) => handle_alloc_error(layout),
585        }
586    }
587
588    /// Constructs a new box with uninitialized contents in the provided allocator,
589    /// returning an error if the allocation fails
590    ///
591    /// # Examples
592    ///
593    /// ```
594    /// #![feature(allocator_api)]
595    ///
596    /// use std::alloc::System;
597    ///
598    /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
599    /// // Deferred initialization:
600    /// five.write(5);
601    /// let five = unsafe { five.assume_init() };
602    ///
603    /// assert_eq!(*five, 5);
604    /// # Ok::<(), std::alloc::AllocError>(())
605    /// ```
606    #[unstable(feature = "allocator_api", issue = "32838")]
607    pub fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
608    where
609        A: Allocator,
610    {
611        let ptr = if T::IS_ZST {
612            NonNull::dangling()
613        } else {
614            let layout = Layout::new::<mem::MaybeUninit<T>>();
615            alloc.allocate(layout)?.cast()
616        };
617        unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
618    }
619
620    /// Constructs a new `Box` with uninitialized contents, with the memory
621    /// being filled with `0` bytes in the provided allocator.
622    ///
623    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
624    /// of this method.
625    ///
626    /// # Examples
627    ///
628    /// ```
629    /// #![feature(allocator_api)]
630    ///
631    /// use std::alloc::System;
632    ///
633    /// let zero = Box::<u32, _>::new_zeroed_in(System);
634    /// let zero = unsafe { zero.assume_init() };
635    ///
636    /// assert_eq!(*zero, 0)
637    /// ```
638    ///
639    /// [zeroed]: mem::MaybeUninit::zeroed
640    #[unstable(feature = "allocator_api", issue = "32838")]
641    #[cfg(not(no_global_oom_handling))]
642    #[must_use]
643    pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
644    where
645        A: Allocator,
646    {
647        let layout = Layout::new::<mem::MaybeUninit<T>>();
648        // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
649        // That would make code size bigger.
650        match Box::try_new_zeroed_in(alloc) {
651            Ok(m) => m,
652            Err(_) => handle_alloc_error(layout),
653        }
654    }
655
656    /// Constructs a new `Box` with uninitialized contents, with the memory
657    /// being filled with `0` bytes in the provided allocator,
658    /// returning an error if the allocation fails,
659    ///
660    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
661    /// of this method.
662    ///
663    /// # Examples
664    ///
665    /// ```
666    /// #![feature(allocator_api)]
667    ///
668    /// use std::alloc::System;
669    ///
670    /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
671    /// let zero = unsafe { zero.assume_init() };
672    ///
673    /// assert_eq!(*zero, 0);
674    /// # Ok::<(), std::alloc::AllocError>(())
675    /// ```
676    ///
677    /// [zeroed]: mem::MaybeUninit::zeroed
678    #[unstable(feature = "allocator_api", issue = "32838")]
679    pub fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
680    where
681        A: Allocator,
682    {
683        let ptr = if T::IS_ZST {
684            NonNull::dangling()
685        } else {
686            let layout = Layout::new::<mem::MaybeUninit<T>>();
687            alloc.allocate_zeroed(layout)?.cast()
688        };
689        unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
690    }
691
692    /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
693    /// `x` will be pinned in memory and unable to be moved.
694    ///
695    /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin_in(x, alloc)`
696    /// does the same as <code>[Box::into_pin]\([Box::new_in]\(x, alloc))</code>. Consider using
697    /// [`into_pin`](Box::into_pin) if you already have a `Box<T, A>`, or if you want to
698    /// construct a (pinned) `Box` in a different way than with [`Box::new_in`].
699    ///
700    /// # Examples
701    ///
702    /// ```
703    /// #![feature(allocator_api)]
704    /// use std::alloc::System;
705    ///
706    /// let x = Box::pin_in(1, System);
707    /// ```
708    #[cfg(not(no_global_oom_handling))]
709    #[unstable(feature = "allocator_api", issue = "32838")]
710    #[must_use]
711    #[inline(always)]
712    pub fn pin_in(x: T, alloc: A) -> Pin<Self>
713    where
714        A: 'static + Allocator,
715    {
716        Self::into_pin(Self::new_in(x, alloc))
717    }
718
719    /// Converts a `Box<T>` into a `Box<[T]>`
720    ///
721    /// This conversion does not allocate on the heap and happens in place.
722    #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
723    pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
724        let (raw, alloc) = Box::into_raw_with_allocator(boxed);
725        unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
726    }
727
728    /// Consumes the `Box`, returning the wrapped value.
729    ///
730    /// # Examples
731    ///
732    /// ```
733    /// #![feature(box_into_inner)]
734    ///
735    /// let c = Box::new(5);
736    ///
737    /// assert_eq!(Box::into_inner(c), 5);
738    /// ```
739    #[unstable(feature = "box_into_inner", issue = "80437")]
740    #[inline]
741    pub fn into_inner(boxed: Self) -> T {
742        *boxed
743    }
744
745    /// Consumes the `Box` without consuming its allocation, returning the wrapped value and a `Box`
746    /// to the uninitialized memory where the wrapped value used to live.
747    ///
748    /// This can be used together with [`write`](Box::write) to reuse the allocation for multiple
749    /// boxed values.
750    ///
751    /// # Examples
752    ///
753    /// ```
754    /// #![feature(box_take)]
755    ///
756    /// let c = Box::new(5);
757    ///
758    /// // take the value out of the box
759    /// let (value, uninit) = Box::take(c);
760    /// assert_eq!(value, 5);
761    ///
762    /// // reuse the box for a second value
763    /// let c = Box::write(uninit, 6);
764    /// assert_eq!(*c, 6);
765    /// ```
766    #[unstable(feature = "box_take", issue = "147212")]
767    pub fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>) {
768        unsafe {
769            let (raw, alloc) = Box::into_non_null_with_allocator(boxed);
770            let value = raw.read();
771            let uninit = Box::from_non_null_in(raw.cast_uninit(), alloc);
772            (value, uninit)
773        }
774    }
775}
776
777impl<T: ?Sized + CloneToUninit> Box<T> {
778    /// Allocates memory on the heap then clones `src` into it.
779    ///
780    /// This doesn't actually allocate if `src` is zero-sized.
781    ///
782    /// # Examples
783    ///
784    /// ```
785    /// #![feature(clone_from_ref)]
786    ///
787    /// let hello: Box<str> = Box::clone_from_ref("hello");
788    /// ```
789    #[cfg(not(no_global_oom_handling))]
790    #[unstable(feature = "clone_from_ref", issue = "149075")]
791    #[must_use]
792    #[inline]
793    pub fn clone_from_ref(src: &T) -> Box<T> {
794        Box::clone_from_ref_in(src, Global)
795    }
796
797    /// Allocates memory on the heap then clones `src` into it, returning an error if allocation fails.
798    ///
799    /// This doesn't actually allocate if `src` is zero-sized.
800    ///
801    /// # Examples
802    ///
803    /// ```
804    /// #![feature(clone_from_ref)]
805    /// #![feature(allocator_api)]
806    ///
807    /// let hello: Box<str> = Box::try_clone_from_ref("hello")?;
808    /// # Ok::<(), std::alloc::AllocError>(())
809    /// ```
810    #[unstable(feature = "clone_from_ref", issue = "149075")]
811    //#[unstable(feature = "allocator_api", issue = "32838")]
812    #[must_use]
813    #[inline]
814    pub fn try_clone_from_ref(src: &T) -> Result<Box<T>, AllocError> {
815        Box::try_clone_from_ref_in(src, Global)
816    }
817}
818
819impl<T: ?Sized + CloneToUninit, A: Allocator> Box<T, A> {
820    /// Allocates memory in the given allocator then clones `src` into it.
821    ///
822    /// This doesn't actually allocate if `src` is zero-sized.
823    ///
824    /// # Examples
825    ///
826    /// ```
827    /// #![feature(clone_from_ref)]
828    /// #![feature(allocator_api)]
829    ///
830    /// use std::alloc::System;
831    ///
832    /// let hello: Box<str, System> = Box::clone_from_ref_in("hello", System);
833    /// ```
834    #[cfg(not(no_global_oom_handling))]
835    #[unstable(feature = "clone_from_ref", issue = "149075")]
836    //#[unstable(feature = "allocator_api", issue = "32838")]
837    #[must_use]
838    #[inline]
839    pub fn clone_from_ref_in(src: &T, alloc: A) -> Box<T, A> {
840        let layout = Layout::for_value::<T>(src);
841        match Box::try_clone_from_ref_in(src, alloc) {
842            Ok(bx) => bx,
843            Err(_) => handle_alloc_error(layout),
844        }
845    }
846
847    /// Allocates memory in the given allocator then clones `src` into it, returning an error if allocation fails.
848    ///
849    /// This doesn't actually allocate if `src` is zero-sized.
850    ///
851    /// # Examples
852    ///
853    /// ```
854    /// #![feature(clone_from_ref)]
855    /// #![feature(allocator_api)]
856    ///
857    /// use std::alloc::System;
858    ///
859    /// let hello: Box<str, System> = Box::try_clone_from_ref_in("hello", System)?;
860    /// # Ok::<(), std::alloc::AllocError>(())
861    /// ```
862    #[unstable(feature = "clone_from_ref", issue = "149075")]
863    //#[unstable(feature = "allocator_api", issue = "32838")]
864    #[must_use]
865    #[inline]
866    pub fn try_clone_from_ref_in(src: &T, alloc: A) -> Result<Box<T, A>, AllocError> {
867        struct DeallocDropGuard<'a, A: Allocator>(Layout, &'a A, NonNull<u8>);
868        impl<'a, A: Allocator> Drop for DeallocDropGuard<'a, A> {
869            fn drop(&mut self) {
870                let &mut DeallocDropGuard(layout, alloc, ptr) = self;
871                // Safety: `ptr` was allocated by `*alloc` with layout `layout`
872                unsafe {
873                    alloc.deallocate(ptr, layout);
874                }
875            }
876        }
877        let layout = Layout::for_value::<T>(src);
878        let (ptr, guard) = if layout.size() == 0 {
879            (layout.dangling_ptr(), None)
880        } else {
881            // Safety: layout is non-zero-sized
882            let ptr = alloc.allocate(layout)?.cast();
883            (ptr, Some(DeallocDropGuard(layout, &alloc, ptr)))
884        };
885        let ptr = ptr.as_ptr();
886        // Safety: `*ptr` is newly allocated, correctly aligned to `align_of_val(src)`,
887        // and is valid for writes for `size_of_val(src)`.
888        // If this panics, then `guard` will deallocate for us (if allocation occuured)
889        unsafe {
890            <T as CloneToUninit>::clone_to_uninit(src, ptr);
891        }
892        // Defuse the deallocate guard
893        core::mem::forget(guard);
894        // Safety: We just initialized `*ptr` as a clone of `src`
895        Ok(unsafe { Box::from_raw_in(ptr.with_metadata_of(src), alloc) })
896    }
897}
898
899impl<T> Box<[T]> {
900    /// Constructs a new boxed slice with uninitialized contents.
901    ///
902    /// # Examples
903    ///
904    /// ```
905    /// let mut values = Box::<[u32]>::new_uninit_slice(3);
906    /// // Deferred initialization:
907    /// values[0].write(1);
908    /// values[1].write(2);
909    /// values[2].write(3);
910    /// let values = unsafe { values.assume_init() };
911    ///
912    /// assert_eq!(*values, [1, 2, 3])
913    /// ```
914    #[cfg(not(no_global_oom_handling))]
915    #[stable(feature = "new_uninit", since = "1.82.0")]
916    #[must_use]
917    pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
918        unsafe { RawVec::with_capacity(len).into_box(len) }
919    }
920
921    /// Constructs a new boxed slice with uninitialized contents, with the memory
922    /// being filled with `0` bytes.
923    ///
924    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
925    /// of this method.
926    ///
927    /// # Examples
928    ///
929    /// ```
930    /// let values = Box::<[u32]>::new_zeroed_slice(3);
931    /// let values = unsafe { values.assume_init() };
932    ///
933    /// assert_eq!(*values, [0, 0, 0])
934    /// ```
935    ///
936    /// [zeroed]: mem::MaybeUninit::zeroed
937    #[cfg(not(no_global_oom_handling))]
938    #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
939    #[must_use]
940    pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
941        unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
942    }
943
944    /// Constructs a new boxed slice with uninitialized contents. Returns an error if
945    /// the allocation fails.
946    ///
947    /// # Examples
948    ///
949    /// ```
950    /// #![feature(allocator_api)]
951    ///
952    /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
953    /// // Deferred initialization:
954    /// values[0].write(1);
955    /// values[1].write(2);
956    /// values[2].write(3);
957    /// let values = unsafe { values.assume_init() };
958    ///
959    /// assert_eq!(*values, [1, 2, 3]);
960    /// # Ok::<(), std::alloc::AllocError>(())
961    /// ```
962    #[unstable(feature = "allocator_api", issue = "32838")]
963    #[inline]
964    pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
965        let ptr = if T::IS_ZST || len == 0 {
966            NonNull::dangling()
967        } else {
968            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
969                Ok(l) => l,
970                Err(_) => return Err(AllocError),
971            };
972            Global.allocate(layout)?.cast()
973        };
974        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
975    }
976
977    /// Constructs a new boxed slice with uninitialized contents, with the memory
978    /// being filled with `0` bytes. Returns an error if the allocation fails.
979    ///
980    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
981    /// of this method.
982    ///
983    /// # Examples
984    ///
985    /// ```
986    /// #![feature(allocator_api)]
987    ///
988    /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
989    /// let values = unsafe { values.assume_init() };
990    ///
991    /// assert_eq!(*values, [0, 0, 0]);
992    /// # Ok::<(), std::alloc::AllocError>(())
993    /// ```
994    ///
995    /// [zeroed]: mem::MaybeUninit::zeroed
996    #[unstable(feature = "allocator_api", issue = "32838")]
997    #[inline]
998    pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
999        let ptr = if T::IS_ZST || len == 0 {
1000            NonNull::dangling()
1001        } else {
1002            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1003                Ok(l) => l,
1004                Err(_) => return Err(AllocError),
1005            };
1006            Global.allocate_zeroed(layout)?.cast()
1007        };
1008        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
1009    }
1010}
1011
1012impl<T, A: Allocator> Box<[T], A> {
1013    /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
1014    ///
1015    /// # Examples
1016    ///
1017    /// ```
1018    /// #![feature(allocator_api)]
1019    ///
1020    /// use std::alloc::System;
1021    ///
1022    /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
1023    /// // Deferred initialization:
1024    /// values[0].write(1);
1025    /// values[1].write(2);
1026    /// values[2].write(3);
1027    /// let values = unsafe { values.assume_init() };
1028    ///
1029    /// assert_eq!(*values, [1, 2, 3])
1030    /// ```
1031    #[cfg(not(no_global_oom_handling))]
1032    #[unstable(feature = "allocator_api", issue = "32838")]
1033    #[must_use]
1034    pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
1035        unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
1036    }
1037
1038    /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
1039    /// with the memory being filled with `0` bytes.
1040    ///
1041    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1042    /// of this method.
1043    ///
1044    /// # Examples
1045    ///
1046    /// ```
1047    /// #![feature(allocator_api)]
1048    ///
1049    /// use std::alloc::System;
1050    ///
1051    /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
1052    /// let values = unsafe { values.assume_init() };
1053    ///
1054    /// assert_eq!(*values, [0, 0, 0])
1055    /// ```
1056    ///
1057    /// [zeroed]: mem::MaybeUninit::zeroed
1058    #[cfg(not(no_global_oom_handling))]
1059    #[unstable(feature = "allocator_api", issue = "32838")]
1060    #[must_use]
1061    pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
1062        unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
1063    }
1064
1065    /// Constructs a new boxed slice with uninitialized contents in the provided allocator. Returns an error if
1066    /// the allocation fails.
1067    ///
1068    /// # Examples
1069    ///
1070    /// ```
1071    /// #![feature(allocator_api)]
1072    ///
1073    /// use std::alloc::System;
1074    ///
1075    /// let mut values = Box::<[u32], _>::try_new_uninit_slice_in(3, System)?;
1076    /// // Deferred initialization:
1077    /// values[0].write(1);
1078    /// values[1].write(2);
1079    /// values[2].write(3);
1080    /// let values = unsafe { values.assume_init() };
1081    ///
1082    /// assert_eq!(*values, [1, 2, 3]);
1083    /// # Ok::<(), std::alloc::AllocError>(())
1084    /// ```
1085    #[unstable(feature = "allocator_api", issue = "32838")]
1086    #[inline]
1087    pub fn try_new_uninit_slice_in(
1088        len: usize,
1089        alloc: A,
1090    ) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError> {
1091        let ptr = if T::IS_ZST || len == 0 {
1092            NonNull::dangling()
1093        } else {
1094            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1095                Ok(l) => l,
1096                Err(_) => return Err(AllocError),
1097            };
1098            alloc.allocate(layout)?.cast()
1099        };
1100        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) }
1101    }
1102
1103    /// Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory
1104    /// being filled with `0` bytes. Returns an error if the allocation fails.
1105    ///
1106    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1107    /// of this method.
1108    ///
1109    /// # Examples
1110    ///
1111    /// ```
1112    /// #![feature(allocator_api)]
1113    ///
1114    /// use std::alloc::System;
1115    ///
1116    /// let values = Box::<[u32], _>::try_new_zeroed_slice_in(3, System)?;
1117    /// let values = unsafe { values.assume_init() };
1118    ///
1119    /// assert_eq!(*values, [0, 0, 0]);
1120    /// # Ok::<(), std::alloc::AllocError>(())
1121    /// ```
1122    ///
1123    /// [zeroed]: mem::MaybeUninit::zeroed
1124    #[unstable(feature = "allocator_api", issue = "32838")]
1125    #[inline]
1126    pub fn try_new_zeroed_slice_in(
1127        len: usize,
1128        alloc: A,
1129    ) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError> {
1130        let ptr = if T::IS_ZST || len == 0 {
1131            NonNull::dangling()
1132        } else {
1133            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1134                Ok(l) => l,
1135                Err(_) => return Err(AllocError),
1136            };
1137            alloc.allocate_zeroed(layout)?.cast()
1138        };
1139        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) }
1140    }
1141
1142    /// Converts the boxed slice into a boxed array.
1143    ///
1144    /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
1145    ///
1146    /// If `N` is not exactly equal to the length of `self`, then this method returns `None`.
1147    ///
1148    /// # Examples
1149    ///
1150    /// ```
1151    /// #![feature(alloc_slice_into_array)]
1152    /// let box_slice: Box<[i32]> = Box::new([1, 2, 3]);
1153    ///
1154    /// let box_array: Box<[i32; 3]> = box_slice.into_array().unwrap();
1155    /// ```
1156    #[unstable(feature = "alloc_slice_into_array", issue = "148082")]
1157    #[inline]
1158    #[must_use]
1159    pub fn into_array<const N: usize>(self) -> Option<Box<[T; N], A>> {
1160        if self.len() == N {
1161            let (ptr, alloc) = Self::into_raw_with_allocator(self);
1162            let ptr = ptr as *mut [T; N];
1163
1164            // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length.
1165            let me = unsafe { Box::from_raw_in(ptr, alloc) };
1166            Some(me)
1167        } else {
1168            None
1169        }
1170    }
1171}
1172
1173impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
1174    /// Converts to `Box<T, A>`.
1175    ///
1176    /// # Safety
1177    ///
1178    /// As with [`MaybeUninit::assume_init`],
1179    /// it is up to the caller to guarantee that the value
1180    /// really is in an initialized state.
1181    /// Calling this when the content is not yet fully initialized
1182    /// causes immediate undefined behavior.
1183    ///
1184    /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1185    ///
1186    /// # Examples
1187    ///
1188    /// ```
1189    /// let mut five = Box::<u32>::new_uninit();
1190    /// // Deferred initialization:
1191    /// five.write(5);
1192    /// let five: Box<u32> = unsafe { five.assume_init() };
1193    ///
1194    /// assert_eq!(*five, 5)
1195    /// ```
1196    #[stable(feature = "new_uninit", since = "1.82.0")]
1197    #[inline(always)]
1198    pub unsafe fn assume_init(self) -> Box<T, A> {
1199        // This is used in the `vec!` macro, so we optimize for minimal IR generation
1200        // even in debug builds.
1201        // SAFETY: `Box<T>` and `Box<MaybeUninit<T>>` have the same layout.
1202        unsafe { core::intrinsics::transmute_unchecked(self) }
1203    }
1204
1205    /// Writes the value and converts to `Box<T, A>`.
1206    ///
1207    /// This method converts the box similarly to [`Box::assume_init`] but
1208    /// writes `value` into it before conversion thus guaranteeing safety.
1209    /// In some scenarios use of this method may improve performance because
1210    /// the compiler may be able to optimize copying from stack.
1211    ///
1212    /// # Examples
1213    ///
1214    /// ```
1215    /// let big_box = Box::<[usize; 1024]>::new_uninit();
1216    ///
1217    /// let mut array = [0; 1024];
1218    /// for (i, place) in array.iter_mut().enumerate() {
1219    ///     *place = i;
1220    /// }
1221    ///
1222    /// // The optimizer may be able to elide this copy, so previous code writes
1223    /// // to heap directly.
1224    /// let big_box = Box::write(big_box, array);
1225    ///
1226    /// for (i, x) in big_box.iter().enumerate() {
1227    ///     assert_eq!(*x, i);
1228    /// }
1229    /// ```
1230    #[stable(feature = "box_uninit_write", since = "1.87.0")]
1231    #[inline]
1232    pub fn write(mut boxed: Self, value: T) -> Box<T, A> {
1233        unsafe {
1234            (*boxed).write(value);
1235            boxed.assume_init()
1236        }
1237    }
1238}
1239
1240impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
1241    /// Converts to `Box<[T], A>`.
1242    ///
1243    /// # Safety
1244    ///
1245    /// As with [`MaybeUninit::assume_init`],
1246    /// it is up to the caller to guarantee that the values
1247    /// really are in an initialized state.
1248    /// Calling this when the content is not yet fully initialized
1249    /// causes immediate undefined behavior.
1250    ///
1251    /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1252    ///
1253    /// # Examples
1254    ///
1255    /// ```
1256    /// let mut values = Box::<[u32]>::new_uninit_slice(3);
1257    /// // Deferred initialization:
1258    /// values[0].write(1);
1259    /// values[1].write(2);
1260    /// values[2].write(3);
1261    /// let values = unsafe { values.assume_init() };
1262    ///
1263    /// assert_eq!(*values, [1, 2, 3])
1264    /// ```
1265    #[stable(feature = "new_uninit", since = "1.82.0")]
1266    #[inline]
1267    pub unsafe fn assume_init(self) -> Box<[T], A> {
1268        let (raw, alloc) = Box::into_raw_with_allocator(self);
1269        unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
1270    }
1271}
1272
1273impl<T: ?Sized> Box<T> {
1274    /// Constructs a box from a raw pointer.
1275    ///
1276    /// After calling this function, the raw pointer is owned by the
1277    /// resulting `Box`. Specifically, the `Box` destructor will call
1278    /// the destructor of `T` and free the allocated memory. For this
1279    /// to be safe, the memory must have been allocated in accordance
1280    /// with the [memory layout] used by `Box` .
1281    ///
1282    /// # Safety
1283    ///
1284    /// This function is unsafe because improper use may lead to
1285    /// memory problems. For example, a double-free may occur if the
1286    /// function is called twice on the same raw pointer.
1287    ///
1288    /// The raw pointer must point to a block of memory allocated by the global allocator.
1289    ///
1290    /// The safety conditions are described in the [memory layout] section.
1291    /// Note that the [considerations for unsafe code] apply to all `Box<T>` values.
1292    ///
1293    /// # Examples
1294    ///
1295    /// Recreate a `Box` which was previously converted to a raw pointer
1296    /// using [`Box::into_raw`]:
1297    /// ```
1298    /// let x = Box::new(5);
1299    /// let ptr = Box::into_raw(x);
1300    /// let x = unsafe { Box::from_raw(ptr) };
1301    /// ```
1302    /// Manually create a `Box` from scratch by using the global allocator:
1303    /// ```
1304    /// use std::alloc::{alloc, Layout};
1305    ///
1306    /// unsafe {
1307    ///     let ptr = alloc(Layout::new::<i32>()) as *mut i32;
1308    ///     // In general .write is required to avoid attempting to destruct
1309    ///     // the (uninitialized) previous contents of `ptr`, though for this
1310    ///     // simple example `*ptr = 5` would have worked as well.
1311    ///     ptr.write(5);
1312    ///     let x = Box::from_raw(ptr);
1313    /// }
1314    /// ```
1315    ///
1316    /// [memory layout]: self#memory-layout
1317    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1318    #[stable(feature = "box_raw", since = "1.4.0")]
1319    #[inline]
1320    #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
1321    pub unsafe fn from_raw(raw: *mut T) -> Self {
1322        unsafe { Self::from_raw_in(raw, Global) }
1323    }
1324
1325    /// Constructs a box from a `NonNull` pointer.
1326    ///
1327    /// After calling this function, the `NonNull` pointer is owned by
1328    /// the resulting `Box`. Specifically, the `Box` destructor will call
1329    /// the destructor of `T` and free the allocated memory. For this
1330    /// to be safe, the memory must have been allocated in accordance
1331    /// with the [memory layout] used by `Box` .
1332    ///
1333    /// # Safety
1334    ///
1335    /// This function is unsafe because improper use may lead to
1336    /// memory problems. For example, a double-free may occur if the
1337    /// function is called twice on the same `NonNull` pointer.
1338    ///
1339    /// The non-null pointer must point to a block of memory allocated by the global allocator.
1340    ///
1341    /// The safety conditions are described in the [memory layout] section.
1342    /// Note that the [considerations for unsafe code] apply to all `Box<T>` values.
1343    ///
1344    /// # Examples
1345    ///
1346    /// Recreate a `Box` which was previously converted to a `NonNull`
1347    /// pointer using [`Box::into_non_null`]:
1348    /// ```
1349    /// #![feature(box_vec_non_null)]
1350    ///
1351    /// let x = Box::new(5);
1352    /// let non_null = Box::into_non_null(x);
1353    /// let x = unsafe { Box::from_non_null(non_null) };
1354    /// ```
1355    /// Manually create a `Box` from scratch by using the global allocator:
1356    /// ```
1357    /// #![feature(box_vec_non_null)]
1358    ///
1359    /// use std::alloc::{alloc, Layout};
1360    /// use std::ptr::NonNull;
1361    ///
1362    /// unsafe {
1363    ///     let non_null = NonNull::new(alloc(Layout::new::<i32>()).cast::<i32>())
1364    ///         .expect("allocation failed");
1365    ///     // In general .write is required to avoid attempting to destruct
1366    ///     // the (uninitialized) previous contents of `non_null`.
1367    ///     non_null.write(5);
1368    ///     let x = Box::from_non_null(non_null);
1369    /// }
1370    /// ```
1371    ///
1372    /// [memory layout]: self#memory-layout
1373    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1374    #[unstable(feature = "box_vec_non_null", issue = "130364")]
1375    #[inline]
1376    #[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"]
1377    pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self {
1378        unsafe { Self::from_raw(ptr.as_ptr()) }
1379    }
1380
1381    /// Consumes the `Box`, returning a wrapped raw pointer.
1382    ///
1383    /// The pointer will be properly aligned and non-null.
1384    ///
1385    /// After calling this function, the caller is responsible for the
1386    /// memory previously managed by the `Box`. In particular, the
1387    /// caller should properly destroy `T` and release the memory, taking
1388    /// into account the [memory layout] used by `Box`. The easiest way to
1389    /// do this is to convert the raw pointer back into a `Box` with the
1390    /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1391    /// the cleanup.
1392    ///
1393    /// Note: this is an associated function, which means that you have
1394    /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1395    /// is so that there is no conflict with a method on the inner type.
1396    ///
1397    /// # Examples
1398    /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1399    /// for automatic cleanup:
1400    /// ```
1401    /// let x = Box::new(String::from("Hello"));
1402    /// let ptr = Box::into_raw(x);
1403    /// let x = unsafe { Box::from_raw(ptr) };
1404    /// ```
1405    /// Manual cleanup by explicitly running the destructor and deallocating
1406    /// the memory:
1407    /// ```
1408    /// use std::alloc::{dealloc, Layout};
1409    /// use std::ptr;
1410    ///
1411    /// let x = Box::new(String::from("Hello"));
1412    /// let ptr = Box::into_raw(x);
1413    /// unsafe {
1414    ///     ptr::drop_in_place(ptr);
1415    ///     dealloc(ptr as *mut u8, Layout::new::<String>());
1416    /// }
1417    /// ```
1418    /// Note: This is equivalent to the following:
1419    /// ```
1420    /// let x = Box::new(String::from("Hello"));
1421    /// let ptr = Box::into_raw(x);
1422    /// unsafe {
1423    ///     drop(Box::from_raw(ptr));
1424    /// }
1425    /// ```
1426    ///
1427    /// [memory layout]: self#memory-layout
1428    #[must_use = "losing the pointer will leak memory"]
1429    #[stable(feature = "box_raw", since = "1.4.0")]
1430    #[inline]
1431    pub fn into_raw(b: Self) -> *mut T {
1432        // Avoid `into_raw_with_allocator` as that interacts poorly with Miri's Stacked Borrows.
1433        let mut b = mem::ManuallyDrop::new(b);
1434        // We go through the built-in deref for `Box`, which is crucial for Miri to recognize this
1435        // operation for it's alias tracking.
1436        &raw mut **b
1437    }
1438
1439    /// Consumes the `Box`, returning a wrapped `NonNull` pointer.
1440    ///
1441    /// The pointer will be properly aligned.
1442    ///
1443    /// After calling this function, the caller is responsible for the
1444    /// memory previously managed by the `Box`. In particular, the
1445    /// caller should properly destroy `T` and release the memory, taking
1446    /// into account the [memory layout] used by `Box`. The easiest way to
1447    /// do this is to convert the `NonNull` pointer back into a `Box` with the
1448    /// [`Box::from_non_null`] function, allowing the `Box` destructor to
1449    /// perform the cleanup.
1450    ///
1451    /// Note: this is an associated function, which means that you have
1452    /// to call it as `Box::into_non_null(b)` instead of `b.into_non_null()`.
1453    /// This is so that there is no conflict with a method on the inner type.
1454    ///
1455    /// # Examples
1456    /// Converting the `NonNull` pointer back into a `Box` with [`Box::from_non_null`]
1457    /// for automatic cleanup:
1458    /// ```
1459    /// #![feature(box_vec_non_null)]
1460    ///
1461    /// let x = Box::new(String::from("Hello"));
1462    /// let non_null = Box::into_non_null(x);
1463    /// let x = unsafe { Box::from_non_null(non_null) };
1464    /// ```
1465    /// Manual cleanup by explicitly running the destructor and deallocating
1466    /// the memory:
1467    /// ```
1468    /// #![feature(box_vec_non_null)]
1469    ///
1470    /// use std::alloc::{dealloc, Layout};
1471    ///
1472    /// let x = Box::new(String::from("Hello"));
1473    /// let non_null = Box::into_non_null(x);
1474    /// unsafe {
1475    ///     non_null.drop_in_place();
1476    ///     dealloc(non_null.as_ptr().cast::<u8>(), Layout::new::<String>());
1477    /// }
1478    /// ```
1479    /// Note: This is equivalent to the following:
1480    /// ```
1481    /// #![feature(box_vec_non_null)]
1482    ///
1483    /// let x = Box::new(String::from("Hello"));
1484    /// let non_null = Box::into_non_null(x);
1485    /// unsafe {
1486    ///     drop(Box::from_non_null(non_null));
1487    /// }
1488    /// ```
1489    ///
1490    /// [memory layout]: self#memory-layout
1491    #[must_use = "losing the pointer will leak memory"]
1492    #[unstable(feature = "box_vec_non_null", issue = "130364")]
1493    #[inline]
1494    pub fn into_non_null(b: Self) -> NonNull<T> {
1495        // SAFETY: `Box` is guaranteed to be non-null.
1496        unsafe { NonNull::new_unchecked(Self::into_raw(b)) }
1497    }
1498}
1499
1500impl<T: ?Sized, A: Allocator> Box<T, A> {
1501    /// Constructs a box from a raw pointer in the given allocator.
1502    ///
1503    /// After calling this function, the raw pointer is owned by the
1504    /// resulting `Box`. Specifically, the `Box` destructor will call
1505    /// the destructor of `T` and free the allocated memory. For this
1506    /// to be safe, the memory must have been allocated in accordance
1507    /// with the [memory layout] used by `Box` .
1508    ///
1509    /// # Safety
1510    ///
1511    /// This function is unsafe because improper use may lead to
1512    /// memory problems. For example, a double-free may occur if the
1513    /// function is called twice on the same raw pointer.
1514    ///
1515    /// The raw pointer must point to a block of memory allocated by `alloc`.
1516    ///
1517    /// The safety conditions are described in the [memory layout] section.
1518    /// Note that the [considerations for unsafe code] apply to all `Box<T, A>` values.
1519    ///
1520    /// # Examples
1521    ///
1522    /// Recreate a `Box` which was previously converted to a raw pointer
1523    /// using [`Box::into_raw_with_allocator`]:
1524    /// ```
1525    /// #![feature(allocator_api)]
1526    ///
1527    /// use std::alloc::System;
1528    ///
1529    /// let x = Box::new_in(5, System);
1530    /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1531    /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1532    /// ```
1533    /// Manually create a `Box` from scratch by using the system allocator:
1534    /// ```
1535    /// #![feature(allocator_api, slice_ptr_get)]
1536    ///
1537    /// use std::alloc::{Allocator, Layout, System};
1538    ///
1539    /// unsafe {
1540    ///     let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1541    ///     // In general .write is required to avoid attempting to destruct
1542    ///     // the (uninitialized) previous contents of `ptr`, though for this
1543    ///     // simple example `*ptr = 5` would have worked as well.
1544    ///     ptr.write(5);
1545    ///     let x = Box::from_raw_in(ptr, System);
1546    /// }
1547    /// # Ok::<(), std::alloc::AllocError>(())
1548    /// ```
1549    ///
1550    /// [memory layout]: self#memory-layout
1551    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1552    #[unstable(feature = "allocator_api", issue = "32838")]
1553    #[inline]
1554    pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1555        Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1556    }
1557
1558    /// Constructs a box from a `NonNull` pointer in the given allocator.
1559    ///
1560    /// After calling this function, the `NonNull` pointer is owned by
1561    /// the resulting `Box`. Specifically, the `Box` destructor will call
1562    /// the destructor of `T` and free the allocated memory. For this
1563    /// to be safe, the memory must have been allocated in accordance
1564    /// with the [memory layout] used by `Box` .
1565    ///
1566    /// # Safety
1567    ///
1568    /// This function is unsafe because improper use may lead to
1569    /// memory problems. For example, a double-free may occur if the
1570    /// function is called twice on the same raw pointer.
1571    ///
1572    /// The non-null pointer must point to a block of memory allocated by `alloc`.
1573    ///
1574    /// The safety conditions are described in the [memory layout] section.
1575    /// Note that the [considerations for unsafe code] apply to all `Box<T, A>` values.
1576    ///
1577    /// # Examples
1578    ///
1579    /// Recreate a `Box` which was previously converted to a `NonNull` pointer
1580    /// using [`Box::into_non_null_with_allocator`]:
1581    /// ```
1582    /// #![feature(allocator_api)]
1583    ///
1584    /// use std::alloc::System;
1585    ///
1586    /// let x = Box::new_in(5, System);
1587    /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1588    /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1589    /// ```
1590    /// Manually create a `Box` from scratch by using the system allocator:
1591    /// ```
1592    /// #![feature(allocator_api)]
1593    ///
1594    /// use std::alloc::{Allocator, Layout, System};
1595    ///
1596    /// unsafe {
1597    ///     let non_null = System.allocate(Layout::new::<i32>())?.cast::<i32>();
1598    ///     // In general .write is required to avoid attempting to destruct
1599    ///     // the (uninitialized) previous contents of `non_null`.
1600    ///     non_null.write(5);
1601    ///     let x = Box::from_non_null_in(non_null, System);
1602    /// }
1603    /// # Ok::<(), std::alloc::AllocError>(())
1604    /// ```
1605    ///
1606    /// [memory layout]: self#memory-layout
1607    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1608    #[unstable(feature = "allocator_api", issue = "32838")]
1609    // #[unstable(feature = "box_vec_non_null", issue = "130364")]
1610    #[inline]
1611    pub unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Self {
1612        // SAFETY: guaranteed by the caller.
1613        unsafe { Box::from_raw_in(raw.as_ptr(), alloc) }
1614    }
1615
1616    /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1617    ///
1618    /// The pointer will be properly aligned and non-null.
1619    ///
1620    /// After calling this function, the caller is responsible for the
1621    /// memory previously managed by the `Box`. In particular, the
1622    /// caller should properly destroy `T` and release the memory, taking
1623    /// into account the [memory layout] used by `Box`. The easiest way to
1624    /// do this is to convert the raw pointer back into a `Box` with the
1625    /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1626    /// the cleanup.
1627    ///
1628    /// Note: this is an associated function, which means that you have
1629    /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1630    /// is so that there is no conflict with a method on the inner type.
1631    ///
1632    /// # Examples
1633    /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1634    /// for automatic cleanup:
1635    /// ```
1636    /// #![feature(allocator_api)]
1637    ///
1638    /// use std::alloc::System;
1639    ///
1640    /// let x = Box::new_in(String::from("Hello"), System);
1641    /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1642    /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1643    /// ```
1644    /// Manual cleanup by explicitly running the destructor and deallocating
1645    /// the memory:
1646    /// ```
1647    /// #![feature(allocator_api)]
1648    ///
1649    /// use std::alloc::{Allocator, Layout, System};
1650    /// use std::ptr::{self, NonNull};
1651    ///
1652    /// let x = Box::new_in(String::from("Hello"), System);
1653    /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1654    /// unsafe {
1655    ///     ptr::drop_in_place(ptr);
1656    ///     let non_null = NonNull::new_unchecked(ptr);
1657    ///     alloc.deallocate(non_null.cast(), Layout::new::<String>());
1658    /// }
1659    /// ```
1660    ///
1661    /// [memory layout]: self#memory-layout
1662    #[must_use = "losing the pointer will leak memory"]
1663    #[unstable(feature = "allocator_api", issue = "32838")]
1664    #[inline]
1665    pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1666        let mut b = mem::ManuallyDrop::new(b);
1667        // We carefully get the raw pointer out in a way that Miri's aliasing model understands what
1668        // is happening: using the primitive "deref" of `Box`. In case `A` is *not* `Global`, we
1669        // want *no* aliasing requirements here!
1670        // In case `A` *is* `Global`, this does not quite have the right behavior; `into_raw`
1671        // works around that.
1672        let ptr = &raw mut **b;
1673        let alloc = unsafe { ptr::read(&b.1) };
1674        (ptr, alloc)
1675    }
1676
1677    /// Consumes the `Box`, returning a wrapped `NonNull` pointer and the allocator.
1678    ///
1679    /// The pointer will be properly aligned.
1680    ///
1681    /// After calling this function, the caller is responsible for the
1682    /// memory previously managed by the `Box`. In particular, the
1683    /// caller should properly destroy `T` and release the memory, taking
1684    /// into account the [memory layout] used by `Box`. The easiest way to
1685    /// do this is to convert the `NonNull` pointer back into a `Box` with the
1686    /// [`Box::from_non_null_in`] function, allowing the `Box` destructor to
1687    /// perform the cleanup.
1688    ///
1689    /// Note: this is an associated function, which means that you have
1690    /// to call it as `Box::into_non_null_with_allocator(b)` instead of
1691    /// `b.into_non_null_with_allocator()`. This is so that there is no
1692    /// conflict with a method on the inner type.
1693    ///
1694    /// # Examples
1695    /// Converting the `NonNull` pointer back into a `Box` with
1696    /// [`Box::from_non_null_in`] for automatic cleanup:
1697    /// ```
1698    /// #![feature(allocator_api)]
1699    ///
1700    /// use std::alloc::System;
1701    ///
1702    /// let x = Box::new_in(String::from("Hello"), System);
1703    /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1704    /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1705    /// ```
1706    /// Manual cleanup by explicitly running the destructor and deallocating
1707    /// the memory:
1708    /// ```
1709    /// #![feature(allocator_api)]
1710    ///
1711    /// use std::alloc::{Allocator, Layout, System};
1712    ///
1713    /// let x = Box::new_in(String::from("Hello"), System);
1714    /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1715    /// unsafe {
1716    ///     non_null.drop_in_place();
1717    ///     alloc.deallocate(non_null.cast::<u8>(), Layout::new::<String>());
1718    /// }
1719    /// ```
1720    ///
1721    /// [memory layout]: self#memory-layout
1722    #[must_use = "losing the pointer will leak memory"]
1723    #[unstable(feature = "allocator_api", issue = "32838")]
1724    // #[unstable(feature = "box_vec_non_null", issue = "130364")]
1725    #[inline]
1726    pub fn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A) {
1727        let (ptr, alloc) = Box::into_raw_with_allocator(b);
1728        // SAFETY: `Box` is guaranteed to be non-null.
1729        unsafe { (NonNull::new_unchecked(ptr), alloc) }
1730    }
1731
1732    #[unstable(
1733        feature = "ptr_internals",
1734        issue = "none",
1735        reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1736    )]
1737    #[inline]
1738    #[doc(hidden)]
1739    pub fn into_unique(b: Self) -> (Unique<T>, A) {
1740        let (ptr, alloc) = Box::into_raw_with_allocator(b);
1741        unsafe { (Unique::from(&mut *ptr), alloc) }
1742    }
1743
1744    /// Returns a raw mutable pointer to the `Box`'s contents.
1745    ///
1746    /// The caller must ensure that the `Box` outlives the pointer this
1747    /// function returns, or else it will end up dangling.
1748    ///
1749    /// This method guarantees that for the purpose of the aliasing model, this method
1750    /// does not materialize a reference to the underlying memory, and thus the returned pointer
1751    /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
1752    /// Note that calling other methods that materialize references to the memory
1753    /// may still invalidate this pointer.
1754    /// See the example below for how this guarantee can be used.
1755    ///
1756    /// # Examples
1757    ///
1758    /// Due to the aliasing guarantee, the following code is legal:
1759    ///
1760    /// ```rust
1761    /// #![feature(box_as_ptr)]
1762    ///
1763    /// unsafe {
1764    ///     let mut b = Box::new(0);
1765    ///     let ptr1 = Box::as_mut_ptr(&mut b);
1766    ///     ptr1.write(1);
1767    ///     let ptr2 = Box::as_mut_ptr(&mut b);
1768    ///     ptr2.write(2);
1769    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1770    ///     ptr1.write(3);
1771    /// }
1772    /// ```
1773    ///
1774    /// [`as_mut_ptr`]: Self::as_mut_ptr
1775    /// [`as_ptr`]: Self::as_ptr
1776    #[unstable(feature = "box_as_ptr", issue = "129090")]
1777    #[rustc_never_returns_null_ptr]
1778    #[rustc_as_ptr]
1779    #[inline]
1780    pub fn as_mut_ptr(b: &mut Self) -> *mut T {
1781        // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1782        // any references.
1783        &raw mut **b
1784    }
1785
1786    /// Returns a raw pointer to the `Box`'s contents.
1787    ///
1788    /// The caller must ensure that the `Box` outlives the pointer this
1789    /// function returns, or else it will end up dangling.
1790    ///
1791    /// The caller must also ensure that the memory the pointer (non-transitively) points to
1792    /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1793    /// derived from it. If you need to mutate the contents of the `Box`, use [`as_mut_ptr`].
1794    ///
1795    /// This method guarantees that for the purpose of the aliasing model, this method
1796    /// does not materialize a reference to the underlying memory, and thus the returned pointer
1797    /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
1798    /// Note that calling other methods that materialize mutable references to the memory,
1799    /// as well as writing to this memory, may still invalidate this pointer.
1800    /// See the example below for how this guarantee can be used.
1801    ///
1802    /// # Examples
1803    ///
1804    /// Due to the aliasing guarantee, the following code is legal:
1805    ///
1806    /// ```rust
1807    /// #![feature(box_as_ptr)]
1808    ///
1809    /// unsafe {
1810    ///     let mut v = Box::new(0);
1811    ///     let ptr1 = Box::as_ptr(&v);
1812    ///     let ptr2 = Box::as_mut_ptr(&mut v);
1813    ///     let _val = ptr2.read();
1814    ///     // No write to this memory has happened yet, so `ptr1` is still valid.
1815    ///     let _val = ptr1.read();
1816    ///     // However, once we do a write...
1817    ///     ptr2.write(1);
1818    ///     // ... `ptr1` is no longer valid.
1819    ///     // This would be UB: let _val = ptr1.read();
1820    /// }
1821    /// ```
1822    ///
1823    /// [`as_mut_ptr`]: Self::as_mut_ptr
1824    /// [`as_ptr`]: Self::as_ptr
1825    #[unstable(feature = "box_as_ptr", issue = "129090")]
1826    #[rustc_never_returns_null_ptr]
1827    #[rustc_as_ptr]
1828    #[inline]
1829    pub fn as_ptr(b: &Self) -> *const T {
1830        // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1831        // any references.
1832        &raw const **b
1833    }
1834
1835    /// Returns a reference to the underlying allocator.
1836    ///
1837    /// Note: this is an associated function, which means that you have
1838    /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1839    /// is so that there is no conflict with a method on the inner type.
1840    #[unstable(feature = "allocator_api", issue = "32838")]
1841    #[inline]
1842    pub fn allocator(b: &Self) -> &A {
1843        &b.1
1844    }
1845
1846    /// Consumes and leaks the `Box`, returning a mutable reference,
1847    /// `&'a mut T`.
1848    ///
1849    /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
1850    /// has only static references, or none at all, then this may be chosen to be
1851    /// `'static`.
1852    ///
1853    /// This function is mainly useful for data that lives for the remainder of
1854    /// the program's life. Dropping the returned reference will cause a memory
1855    /// leak. If this is not acceptable, the reference should first be wrapped
1856    /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1857    /// then be dropped which will properly destroy `T` and release the
1858    /// allocated memory.
1859    ///
1860    /// Note: this is an associated function, which means that you have
1861    /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1862    /// is so that there is no conflict with a method on the inner type.
1863    ///
1864    /// # Examples
1865    ///
1866    /// Simple usage:
1867    ///
1868    /// ```
1869    /// let x = Box::new(41);
1870    /// let static_ref: &'static mut usize = Box::leak(x);
1871    /// *static_ref += 1;
1872    /// assert_eq!(*static_ref, 42);
1873    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1874    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1875    /// # drop(unsafe { Box::from_raw(static_ref) });
1876    /// ```
1877    ///
1878    /// Unsized data:
1879    ///
1880    /// ```
1881    /// let x = vec![1, 2, 3].into_boxed_slice();
1882    /// let static_ref = Box::leak(x);
1883    /// static_ref[0] = 4;
1884    /// assert_eq!(*static_ref, [4, 2, 3]);
1885    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1886    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1887    /// # drop(unsafe { Box::from_raw(static_ref) });
1888    /// ```
1889    #[stable(feature = "box_leak", since = "1.26.0")]
1890    #[inline]
1891    pub fn leak<'a>(b: Self) -> &'a mut T
1892    where
1893        A: 'a,
1894    {
1895        let (ptr, alloc) = Box::into_raw_with_allocator(b);
1896        mem::forget(alloc);
1897        unsafe { &mut *ptr }
1898    }
1899
1900    /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1901    /// `*boxed` will be pinned in memory and unable to be moved.
1902    ///
1903    /// This conversion does not allocate on the heap and happens in place.
1904    ///
1905    /// This is also available via [`From`].
1906    ///
1907    /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1908    /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1909    /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1910    /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1911    ///
1912    /// # Notes
1913    ///
1914    /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1915    /// as it'll introduce an ambiguity when calling `Pin::from`.
1916    /// A demonstration of such a poor impl is shown below.
1917    ///
1918    /// ```compile_fail
1919    /// # use std::pin::Pin;
1920    /// struct Foo; // A type defined in this crate.
1921    /// impl From<Box<()>> for Pin<Foo> {
1922    ///     fn from(_: Box<()>) -> Pin<Foo> {
1923    ///         Pin::new(Foo)
1924    ///     }
1925    /// }
1926    ///
1927    /// let foo = Box::new(());
1928    /// let bar = Pin::from(foo);
1929    /// ```
1930    #[stable(feature = "box_into_pin", since = "1.63.0")]
1931    pub fn into_pin(boxed: Self) -> Pin<Self>
1932    where
1933        A: 'static,
1934    {
1935        // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1936        // when `T: !Unpin`, so it's safe to pin it directly without any
1937        // additional requirements.
1938        unsafe { Pin::new_unchecked(boxed) }
1939    }
1940}
1941
1942#[stable(feature = "rust1", since = "1.0.0")]
1943unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1944    #[inline]
1945    fn drop(&mut self) {
1946        // the T in the Box is dropped by the compiler before the destructor is run
1947
1948        let ptr = self.0;
1949
1950        unsafe {
1951            let layout = Layout::for_value_raw(ptr.as_ptr());
1952            if layout.size() != 0 {
1953                self.1.deallocate(From::from(ptr.cast()), layout);
1954            }
1955        }
1956    }
1957}
1958
1959#[cfg(not(no_global_oom_handling))]
1960#[stable(feature = "rust1", since = "1.0.0")]
1961impl<T: Default> Default for Box<T> {
1962    /// Creates a `Box<T>`, with the `Default` value for `T`.
1963    #[inline]
1964    fn default() -> Self {
1965        let mut x: Box<mem::MaybeUninit<T>> = Box::new_uninit();
1966        unsafe {
1967            // SAFETY: `x` is valid for writing and has the same layout as `T`.
1968            // If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
1969            // does not have a destructor.
1970            //
1971            // We use `ptr::write` as `MaybeUninit::write` creates
1972            // extra stack copies of `T` in debug mode.
1973            //
1974            // See https://github.com/rust-lang/rust/issues/136043 for more context.
1975            ptr::write(&raw mut *x as *mut T, T::default());
1976            // SAFETY: `x` was just initialized above.
1977            x.assume_init()
1978        }
1979    }
1980}
1981
1982#[cfg(not(no_global_oom_handling))]
1983#[stable(feature = "rust1", since = "1.0.0")]
1984impl<T> Default for Box<[T]> {
1985    /// Creates an empty `[T]` inside a `Box`.
1986    #[inline]
1987    fn default() -> Self {
1988        let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1989        Box(ptr, Global)
1990    }
1991}
1992
1993#[cfg(not(no_global_oom_handling))]
1994#[stable(feature = "default_box_extra", since = "1.17.0")]
1995impl Default for Box<str> {
1996    #[inline]
1997    fn default() -> Self {
1998        // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1999        let ptr: Unique<str> = unsafe {
2000            let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
2001            Unique::new_unchecked(bytes.as_ptr() as *mut str)
2002        };
2003        Box(ptr, Global)
2004    }
2005}
2006
2007#[cfg(not(no_global_oom_handling))]
2008#[stable(feature = "pin_default_impls", since = "1.91.0")]
2009impl<T> Default for Pin<Box<T>>
2010where
2011    T: ?Sized,
2012    Box<T>: Default,
2013{
2014    #[inline]
2015    fn default() -> Self {
2016        Box::into_pin(Box::<T>::default())
2017    }
2018}
2019
2020#[cfg(not(no_global_oom_handling))]
2021#[stable(feature = "rust1", since = "1.0.0")]
2022impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
2023    /// Returns a new box with a `clone()` of this box's contents.
2024    ///
2025    /// # Examples
2026    ///
2027    /// ```
2028    /// let x = Box::new(5);
2029    /// let y = x.clone();
2030    ///
2031    /// // The value is the same
2032    /// assert_eq!(x, y);
2033    ///
2034    /// // But they are unique objects
2035    /// assert_ne!(&*x as *const i32, &*y as *const i32);
2036    /// ```
2037    #[inline]
2038    fn clone(&self) -> Self {
2039        // Pre-allocate memory to allow writing the cloned value directly.
2040        let mut boxed = Self::new_uninit_in(self.1.clone());
2041        unsafe {
2042            (**self).clone_to_uninit(boxed.as_mut_ptr().cast());
2043            boxed.assume_init()
2044        }
2045    }
2046
2047    /// Copies `source`'s contents into `self` without creating a new allocation.
2048    ///
2049    /// # Examples
2050    ///
2051    /// ```
2052    /// let x = Box::new(5);
2053    /// let mut y = Box::new(10);
2054    /// let yp: *const i32 = &*y;
2055    ///
2056    /// y.clone_from(&x);
2057    ///
2058    /// // The value is the same
2059    /// assert_eq!(x, y);
2060    ///
2061    /// // And no allocation occurred
2062    /// assert_eq!(yp, &*y);
2063    /// ```
2064    #[inline]
2065    fn clone_from(&mut self, source: &Self) {
2066        (**self).clone_from(&(**source));
2067    }
2068}
2069
2070#[cfg(not(no_global_oom_handling))]
2071#[stable(feature = "box_slice_clone", since = "1.3.0")]
2072impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2073    fn clone(&self) -> Self {
2074        let alloc = Box::allocator(self).clone();
2075        self.to_vec_in(alloc).into_boxed_slice()
2076    }
2077
2078    /// Copies `source`'s contents into `self` without creating a new allocation,
2079    /// so long as the two are of the same length.
2080    ///
2081    /// # Examples
2082    ///
2083    /// ```
2084    /// let x = Box::new([5, 6, 7]);
2085    /// let mut y = Box::new([8, 9, 10]);
2086    /// let yp: *const [i32] = &*y;
2087    ///
2088    /// y.clone_from(&x);
2089    ///
2090    /// // The value is the same
2091    /// assert_eq!(x, y);
2092    ///
2093    /// // And no allocation occurred
2094    /// assert_eq!(yp, &*y);
2095    /// ```
2096    fn clone_from(&mut self, source: &Self) {
2097        if self.len() == source.len() {
2098            self.clone_from_slice(&source);
2099        } else {
2100            *self = source.clone();
2101        }
2102    }
2103}
2104
2105#[cfg(not(no_global_oom_handling))]
2106#[stable(feature = "box_slice_clone", since = "1.3.0")]
2107impl Clone for Box<str> {
2108    fn clone(&self) -> Self {
2109        // this makes a copy of the data
2110        let buf: Box<[u8]> = self.as_bytes().into();
2111        unsafe { from_boxed_utf8_unchecked(buf) }
2112    }
2113}
2114
2115#[stable(feature = "rust1", since = "1.0.0")]
2116impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
2117    #[inline]
2118    fn eq(&self, other: &Self) -> bool {
2119        PartialEq::eq(&**self, &**other)
2120    }
2121    #[inline]
2122    fn ne(&self, other: &Self) -> bool {
2123        PartialEq::ne(&**self, &**other)
2124    }
2125}
2126
2127#[stable(feature = "rust1", since = "1.0.0")]
2128impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
2129    #[inline]
2130    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2131        PartialOrd::partial_cmp(&**self, &**other)
2132    }
2133    #[inline]
2134    fn lt(&self, other: &Self) -> bool {
2135        PartialOrd::lt(&**self, &**other)
2136    }
2137    #[inline]
2138    fn le(&self, other: &Self) -> bool {
2139        PartialOrd::le(&**self, &**other)
2140    }
2141    #[inline]
2142    fn ge(&self, other: &Self) -> bool {
2143        PartialOrd::ge(&**self, &**other)
2144    }
2145    #[inline]
2146    fn gt(&self, other: &Self) -> bool {
2147        PartialOrd::gt(&**self, &**other)
2148    }
2149}
2150
2151#[stable(feature = "rust1", since = "1.0.0")]
2152impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
2153    #[inline]
2154    fn cmp(&self, other: &Self) -> Ordering {
2155        Ord::cmp(&**self, &**other)
2156    }
2157}
2158
2159#[stable(feature = "rust1", since = "1.0.0")]
2160impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
2161
2162#[stable(feature = "rust1", since = "1.0.0")]
2163impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
2164    fn hash<H: Hasher>(&self, state: &mut H) {
2165        (**self).hash(state);
2166    }
2167}
2168
2169#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
2170impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
2171    fn finish(&self) -> u64 {
2172        (**self).finish()
2173    }
2174    fn write(&mut self, bytes: &[u8]) {
2175        (**self).write(bytes)
2176    }
2177    fn write_u8(&mut self, i: u8) {
2178        (**self).write_u8(i)
2179    }
2180    fn write_u16(&mut self, i: u16) {
2181        (**self).write_u16(i)
2182    }
2183    fn write_u32(&mut self, i: u32) {
2184        (**self).write_u32(i)
2185    }
2186    fn write_u64(&mut self, i: u64) {
2187        (**self).write_u64(i)
2188    }
2189    fn write_u128(&mut self, i: u128) {
2190        (**self).write_u128(i)
2191    }
2192    fn write_usize(&mut self, i: usize) {
2193        (**self).write_usize(i)
2194    }
2195    fn write_i8(&mut self, i: i8) {
2196        (**self).write_i8(i)
2197    }
2198    fn write_i16(&mut self, i: i16) {
2199        (**self).write_i16(i)
2200    }
2201    fn write_i32(&mut self, i: i32) {
2202        (**self).write_i32(i)
2203    }
2204    fn write_i64(&mut self, i: i64) {
2205        (**self).write_i64(i)
2206    }
2207    fn write_i128(&mut self, i: i128) {
2208        (**self).write_i128(i)
2209    }
2210    fn write_isize(&mut self, i: isize) {
2211        (**self).write_isize(i)
2212    }
2213    fn write_length_prefix(&mut self, len: usize) {
2214        (**self).write_length_prefix(len)
2215    }
2216    fn write_str(&mut self, s: &str) {
2217        (**self).write_str(s)
2218    }
2219}
2220
2221#[stable(feature = "rust1", since = "1.0.0")]
2222impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
2223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2224        fmt::Display::fmt(&**self, f)
2225    }
2226}
2227
2228#[stable(feature = "rust1", since = "1.0.0")]
2229impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
2230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2231        fmt::Debug::fmt(&**self, f)
2232    }
2233}
2234
2235#[stable(feature = "rust1", since = "1.0.0")]
2236impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
2237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2238        // It's not possible to extract the inner Uniq directly from the Box,
2239        // instead we cast it to a *const which aliases the Unique
2240        let ptr: *const T = &**self;
2241        fmt::Pointer::fmt(&ptr, f)
2242    }
2243}
2244
2245#[stable(feature = "rust1", since = "1.0.0")]
2246impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
2247    type Target = T;
2248
2249    fn deref(&self) -> &T {
2250        &**self
2251    }
2252}
2253
2254#[stable(feature = "rust1", since = "1.0.0")]
2255impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
2256    fn deref_mut(&mut self) -> &mut T {
2257        &mut **self
2258    }
2259}
2260
2261#[unstable(feature = "deref_pure_trait", issue = "87121")]
2262unsafe impl<T: ?Sized, A: Allocator> DerefPure for Box<T, A> {}
2263
2264#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2265impl<T: ?Sized, A: Allocator> LegacyReceiver for Box<T, A> {}
2266
2267#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2268impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
2269    type Output = <F as FnOnce<Args>>::Output;
2270
2271    extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
2272        <F as FnOnce<Args>>::call_once(*self, args)
2273    }
2274}
2275
2276#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2277impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
2278    extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
2279        <F as FnMut<Args>>::call_mut(self, args)
2280    }
2281}
2282
2283#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2284impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2285    extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2286        <F as Fn<Args>>::call(self, args)
2287    }
2288}
2289
2290#[stable(feature = "async_closure", since = "1.85.0")]
2291impl<Args: Tuple, F: AsyncFnOnce<Args> + ?Sized, A: Allocator> AsyncFnOnce<Args> for Box<F, A> {
2292    type Output = F::Output;
2293    type CallOnceFuture = F::CallOnceFuture;
2294
2295    extern "rust-call" fn async_call_once(self, args: Args) -> Self::CallOnceFuture {
2296        F::async_call_once(*self, args)
2297    }
2298}
2299
2300#[stable(feature = "async_closure", since = "1.85.0")]
2301impl<Args: Tuple, F: AsyncFnMut<Args> + ?Sized, A: Allocator> AsyncFnMut<Args> for Box<F, A> {
2302    type CallRefFuture<'a>
2303        = F::CallRefFuture<'a>
2304    where
2305        Self: 'a;
2306
2307    extern "rust-call" fn async_call_mut(&mut self, args: Args) -> Self::CallRefFuture<'_> {
2308        F::async_call_mut(self, args)
2309    }
2310}
2311
2312#[stable(feature = "async_closure", since = "1.85.0")]
2313impl<Args: Tuple, F: AsyncFn<Args> + ?Sized, A: Allocator> AsyncFn<Args> for Box<F, A> {
2314    extern "rust-call" fn async_call(&self, args: Args) -> Self::CallRefFuture<'_> {
2315        F::async_call(self, args)
2316    }
2317}
2318
2319#[unstable(feature = "coerce_unsized", issue = "18598")]
2320impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2321
2322#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2323unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Box<T, A> {}
2324
2325// It is quite crucial that we only allow the `Global` allocator here.
2326// Handling arbitrary custom allocators (which can affect the `Box` layout heavily!)
2327// would need a lot of codegen and interpreter adjustments.
2328#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2329impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2330
2331#[stable(feature = "box_borrow", since = "1.1.0")]
2332impl<T: ?Sized, A: Allocator> Borrow<T> for Box<T, A> {
2333    fn borrow(&self) -> &T {
2334        &**self
2335    }
2336}
2337
2338#[stable(feature = "box_borrow", since = "1.1.0")]
2339impl<T: ?Sized, A: Allocator> BorrowMut<T> for Box<T, A> {
2340    fn borrow_mut(&mut self) -> &mut T {
2341        &mut **self
2342    }
2343}
2344
2345#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2346impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2347    fn as_ref(&self) -> &T {
2348        &**self
2349    }
2350}
2351
2352#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2353impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2354    fn as_mut(&mut self) -> &mut T {
2355        &mut **self
2356    }
2357}
2358
2359/* Nota bene
2360 *
2361 *  We could have chosen not to add this impl, and instead have written a
2362 *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2363 *  because Box<T> implements Unpin even when T does not, as a result of
2364 *  this impl.
2365 *
2366 *  We chose this API instead of the alternative for a few reasons:
2367 *      - Logically, it is helpful to understand pinning in regard to the
2368 *        memory region being pointed to. For this reason none of the
2369 *        standard library pointer types support projecting through a pin
2370 *        (Box<T> is the only pointer type in std for which this would be
2371 *        safe.)
2372 *      - It is in practice very useful to have Box<T> be unconditionally
2373 *        Unpin because of trait objects, for which the structural auto
2374 *        trait functionality does not apply (e.g., Box<dyn Foo> would
2375 *        otherwise not be Unpin).
2376 *
2377 *  Another type with the same semantics as Box but only a conditional
2378 *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2379 *  could have a method to project a Pin<T> from it.
2380 */
2381#[stable(feature = "pin", since = "1.33.0")]
2382impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> {}
2383
2384#[unstable(feature = "coroutine_trait", issue = "43122")]
2385impl<G: ?Sized + Coroutine<R> + Unpin, R, A: Allocator> Coroutine<R> for Box<G, A> {
2386    type Yield = G::Yield;
2387    type Return = G::Return;
2388
2389    fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2390        G::resume(Pin::new(&mut *self), arg)
2391    }
2392}
2393
2394#[unstable(feature = "coroutine_trait", issue = "43122")]
2395impl<G: ?Sized + Coroutine<R>, R, A: Allocator> Coroutine<R> for Pin<Box<G, A>>
2396where
2397    A: 'static,
2398{
2399    type Yield = G::Yield;
2400    type Return = G::Return;
2401
2402    fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2403        G::resume((*self).as_mut(), arg)
2404    }
2405}
2406
2407#[stable(feature = "futures_api", since = "1.36.0")]
2408impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A> {
2409    type Output = F::Output;
2410
2411    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2412        F::poll(Pin::new(&mut *self), cx)
2413    }
2414}
2415
2416#[stable(feature = "box_error", since = "1.8.0")]
2417impl<E: Error> Error for Box<E> {
2418    #[allow(deprecated)]
2419    fn cause(&self) -> Option<&dyn Error> {
2420        Error::cause(&**self)
2421    }
2422
2423    fn source(&self) -> Option<&(dyn Error + 'static)> {
2424        Error::source(&**self)
2425    }
2426
2427    fn provide<'b>(&'b self, request: &mut error::Request<'b>) {
2428        Error::provide(&**self, request);
2429    }
2430}
2431
2432#[unstable(feature = "allocator_api", issue = "32838")]
2433unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Box<T, A> {
2434    #[inline]
2435    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2436        (**self).allocate(layout)
2437    }
2438
2439    #[inline]
2440    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2441        (**self).allocate_zeroed(layout)
2442    }
2443
2444    #[inline]
2445    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
2446        // SAFETY: the safety contract must be upheld by the caller
2447        unsafe { (**self).deallocate(ptr, layout) }
2448    }
2449
2450    #[inline]
2451    unsafe fn grow(
2452        &self,
2453        ptr: NonNull<u8>,
2454        old_layout: Layout,
2455        new_layout: Layout,
2456    ) -> Result<NonNull<[u8]>, AllocError> {
2457        // SAFETY: the safety contract must be upheld by the caller
2458        unsafe { (**self).grow(ptr, old_layout, new_layout) }
2459    }
2460
2461    #[inline]
2462    unsafe fn grow_zeroed(
2463        &self,
2464        ptr: NonNull<u8>,
2465        old_layout: Layout,
2466        new_layout: Layout,
2467    ) -> Result<NonNull<[u8]>, AllocError> {
2468        // SAFETY: the safety contract must be upheld by the caller
2469        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
2470    }
2471
2472    #[inline]
2473    unsafe fn shrink(
2474        &self,
2475        ptr: NonNull<u8>,
2476        old_layout: Layout,
2477        new_layout: Layout,
2478    ) -> Result<NonNull<[u8]>, AllocError> {
2479        // SAFETY: the safety contract must be upheld by the caller
2480        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
2481    }
2482}