Skip to main content

alloc/
boxed.rs

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