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