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