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