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