[Go to site: main page, start]

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    /// Converts a `Box<T>` into a `Box<[T]>`
721    ///
722    /// This conversion does not allocate on the heap and happens in place.
723    #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
724    pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
725        let (raw, alloc) = Box::into_raw_with_allocator(boxed);
726        // SAFETY: A pointer to T is also a valid pointer to [T; 1].
727        unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
728    }
729
730    /// Consumes the `Box`, returning the wrapped value.
731    ///
732    /// # Examples
733    ///
734    /// ```
735    /// #![feature(box_into_inner)]
736    ///
737    /// let c = Box::new(5);
738    ///
739    /// assert_eq!(Box::into_inner(c), 5);
740    /// ```
741    #[unstable(feature = "box_into_inner", issue = "80437")]
742    #[inline]
743    pub fn into_inner(boxed: Self) -> T {
744        *boxed
745    }
746
747    /// Consumes the `Box` without consuming its allocation, returning the wrapped value and a `Box`
748    /// to the uninitialized memory where the wrapped value used to live.
749    ///
750    /// This can be used together with [`write`](Box::write) to reuse the allocation for multiple
751    /// boxed values.
752    ///
753    /// # Examples
754    ///
755    /// ```
756    /// let c = Box::new(5);
757    ///
758    /// // take the value out of the box
759    /// let (value, uninit) = Box::take(c);
760    /// assert_eq!(value, 5);
761    ///
762    /// // reuse the box for a second value
763    /// let c = Box::write(uninit, 6);
764    /// assert_eq!(*c, 6);
765    /// ```
766    #[stable(feature = "box_take", since = "1.100.0")]
767    pub fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>) {
768        // SAFETY: Reading out an initialised value & leaving behind a
769        // box with uninit contents.
770        unsafe {
771            let (raw, alloc) = Box::into_non_null_with_allocator(boxed);
772            let value = raw.read();
773            let uninit = Box::from_non_null_in(raw.cast_uninit(), alloc);
774            (value, uninit)
775        }
776    }
777
778    /// Maps the value in a box, reusing the allocation if possible.
779    ///
780    /// `f` is called on the value in the box, and the result is returned, also boxed.
781    ///
782    /// Note: this is an associated function, which means that you have
783    /// to call it as `Box::map(b, f)` instead of `b.map(f)`. This
784    /// is so that there is no conflict with a method on the inner type.
785    ///
786    /// # Examples
787    ///
788    /// ```
789    /// let b = Box::new(7);
790    /// let new = Box::map(b, |i| i + 7);
791    /// assert_eq!(*new, 14);
792    /// ```
793    #[cfg(not(no_global_oom_handling))]
794    #[stable(feature = "smart_pointer_map", since = "1.100.0")]
795    pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> Box<U, A> {
796        let (value, allocation) = Box::take(this);
797        let (raw, alloc) = Box::into_non_null_with_allocator(allocation);
798        if size_of::<T>() == size_of::<U>() && align_of::<T>() == align_of::<U>() {
799            // SAFETY: We checked that the memory requirements are the same for both types
800            // and `raw` is already a valid pointer for the requisite memory.
801            let allocation = unsafe { Box::from_non_null_in(raw.cast::<MaybeUninit<U>>(), alloc) };
802            Box::write(allocation, f(value))
803        } else {
804            if size_of::<T>() != 0 {
805                // SAFETY: `raw` isn't dangling since it points to a non-zero-sized
806                // allocation and is never used again after this point.
807                unsafe { alloc.deallocate(raw.cast(), Layout::for_value(&value)) }
808            }
809            Box::new_in(f(value), alloc)
810        }
811    }
812
813    /// Attempts to map the value in a box, reusing the allocation if possible.
814    ///
815    /// `f` is called on the value in the box, and if the operation succeeds, the result is
816    /// returned, also boxed.
817    ///
818    /// Note: this is an associated function, which means that you have
819    /// to call it as `Box::try_map(b, f)` instead of `b.try_map(f)`. This
820    /// is so that there is no conflict with a method on the inner type.
821    ///
822    /// # Examples
823    ///
824    /// ```
825    /// #![feature(smart_pointer_try_map)]
826    ///
827    /// let b = Box::new(7);
828    /// let new = Box::try_map(b, u32::try_from).unwrap();
829    /// assert_eq!(*new, 7);
830    /// ```
831    #[cfg(not(no_global_oom_handling))]
832    #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
833    pub fn try_map<R>(
834        this: Self,
835        f: impl FnOnce(T) -> R,
836    ) -> <R::Residual as Residual<Box<R::Output, A>>>::TryType
837    where
838        R: Try,
839        R::Residual: Residual<Box<R::Output, A>>,
840    {
841        let (value, allocation) = Box::take(this);
842        let (raw, alloc) = Box::into_non_null_with_allocator(allocation);
843        if size_of::<T>() == size_of::<R::Output>() && align_of::<T>() == align_of::<R::Output>() {
844            let allocation =
845                // SAFETY: We checked that the memory requirements are the same for both types
846                // and `raw` is already a valid pointer for the requisite memory.
847                unsafe { Box::from_non_null_in(raw.cast::<MaybeUninit<R::Output>>(), alloc) };
848            try { Box::write(allocation, f(value)?) }
849        } else {
850            if size_of::<T>() != 0 {
851                // SAFETY: `raw` isn't dangling since it points to a non-zero-sized
852                // allocation and is never used again after this point.
853                unsafe { alloc.deallocate(raw.cast(), Layout::for_value(&value)) }
854            }
855            try { Box::new_in(f(value)?, alloc) }
856        }
857    }
858}
859
860impl<T: ?Sized + CloneToUninit> Box<T> {
861    /// Allocates memory on the heap then clones `src` into it.
862    ///
863    /// This doesn't actually allocate if `src` is zero-sized.
864    /// See the [memory layout] section for more details.
865    ///
866    /// # Examples
867    ///
868    /// ```
869    /// #![feature(clone_from_ref)]
870    ///
871    /// let hello: Box<str> = Box::clone_from_ref("hello");
872    /// ```
873    ///
874    /// [memory layout]: self#memory-layout
875    #[cfg(not(no_global_oom_handling))]
876    #[unstable(feature = "clone_from_ref", issue = "149075")]
877    #[must_use]
878    #[inline]
879    pub fn clone_from_ref(src: &T) -> Box<T> {
880        Box::clone_from_ref_in(src, Global)
881    }
882
883    /// Allocates memory on the heap then clones `src` into it, returning an error if allocation fails.
884    ///
885    /// This doesn't actually allocate if `src` is zero-sized.
886    /// See the [memory layout] section for more details.
887    ///
888    /// # Examples
889    ///
890    /// ```
891    /// #![feature(clone_from_ref)]
892    ///
893    /// let hello: Box<str> = Box::try_clone_from_ref("hello")?;
894    /// # Ok::<(), std::alloc::AllocError>(())
895    /// ```
896    ///
897    /// [memory layout]: self#memory-layout
898    #[unstable(feature = "clone_from_ref", issue = "149075")]
899    //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
900    #[inline]
901    pub fn try_clone_from_ref(src: &T) -> Result<Box<T>, AllocError> {
902        Box::try_clone_from_ref_in(src, Global)
903    }
904}
905
906impl<T: ?Sized + CloneToUninit, A: Allocator> Box<T, A> {
907    /// Allocates memory in the given allocator then clones `src` into it.
908    ///
909    /// This doesn't actually allocate if `src` is zero-sized.
910    /// See the [memory layout] section for more details.
911    ///
912    /// # Examples
913    ///
914    /// ```
915    /// #![feature(clone_from_ref)]
916    ///
917    /// use std::alloc::System;
918    ///
919    /// let hello: Box<str, System> = Box::clone_from_ref_in("hello", System);
920    /// ```
921    ///
922    /// [memory layout]: self#memory-layout
923    #[cfg(not(no_global_oom_handling))]
924    #[unstable(feature = "clone_from_ref", issue = "149075")]
925    //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
926    #[must_use]
927    #[inline]
928    pub fn clone_from_ref_in(src: &T, alloc: A) -> Box<T, A> {
929        let layout = Layout::for_value::<T>(src);
930        match Box::try_clone_from_ref_in(src, alloc) {
931            Ok(bx) => bx,
932            Err(_) => handle_alloc_error(layout),
933        }
934    }
935
936    /// Allocates memory in the given allocator then clones `src` into it, returning an error if allocation fails.
937    ///
938    /// This doesn't actually allocate if `src` is zero-sized.
939    /// See the [memory layout] section for more details.
940    ///
941    /// # Examples
942    ///
943    /// ```
944    /// #![feature(clone_from_ref)]
945    ///
946    /// use std::alloc::System;
947    ///
948    /// let hello: Box<str, System> = Box::try_clone_from_ref_in("hello", System)?;
949    /// # Ok::<(), std::alloc::AllocError>(())
950    /// ```
951    ///
952    /// [memory layout]: self#memory-layout
953    #[unstable(feature = "clone_from_ref", issue = "149075")]
954    //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
955    #[inline]
956    pub fn try_clone_from_ref_in(src: &T, alloc: A) -> Result<Box<T, A>, AllocError> {
957        struct DeallocDropGuard<'a, A: Allocator>(Layout, &'a A, NonNull<u8>);
958        impl<'a, A: Allocator> Drop for DeallocDropGuard<'a, A> {
959            fn drop(&mut self) {
960                let &mut DeallocDropGuard(layout, alloc, ptr) = self;
961                // SAFETY: `ptr` was allocated by `*alloc` with layout `layout`
962                unsafe {
963                    alloc.deallocate(ptr, layout);
964                }
965            }
966        }
967        let layout = Layout::for_value::<T>(src);
968        let (ptr, guard) = if layout.size() == 0 {
969            (layout.dangling_ptr(), None)
970        } else {
971            // Safety: layout is non-zero-sized
972            let ptr = alloc.allocate(layout)?.cast();
973            (ptr, Some(DeallocDropGuard(layout, &alloc, ptr)))
974        };
975        let ptr = ptr.as_ptr();
976        // SAFETY: `*ptr` is newly allocated (or a ZST), correctly aligned to
977        // `align_of_val(src)`, and is valid for writes for `size_of_val(src)`.
978        // If this panics, then `guard` will deallocate for us (if allocation occuured)
979        unsafe {
980            <T as CloneToUninit>::clone_to_uninit(src, ptr);
981        }
982        // Defuse the deallocate guard
983        core::mem::forget(guard);
984        // SAFETY: We just initialized `*ptr` as a clone of `src`
985        Ok(unsafe { Box::from_raw_in(ptr.with_metadata_of(src), alloc) })
986    }
987}
988
989impl<T> Box<[T]> {
990    /// Constructs a new boxed slice with uninitialized contents.
991    ///
992    /// # Examples
993    ///
994    /// ```
995    /// let mut values = Box::<[u32]>::new_uninit_slice(3);
996    /// // Deferred initialization:
997    /// values[0].write(1);
998    /// values[1].write(2);
999    /// values[2].write(3);
1000    /// let values = unsafe { values.assume_init() };
1001    ///
1002    /// assert_eq!(*values, [1, 2, 3])
1003    /// ```
1004    #[cfg(not(no_global_oom_handling))]
1005    #[stable(feature = "new_uninit", since = "1.82.0")]
1006    #[must_use]
1007    pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
1008        // SAFETY: `len` is exactly the capacity of this `RawVec`.
1009        unsafe { RawVec::with_capacity(len).into_box(len) }
1010    }
1011
1012    /// Constructs a new boxed slice with uninitialized contents, with the memory
1013    /// being filled with `0` bytes.
1014    ///
1015    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1016    /// of this method.
1017    ///
1018    /// # Examples
1019    ///
1020    /// ```
1021    /// let values = Box::<[u32]>::new_zeroed_slice(3);
1022    /// let values = unsafe { values.assume_init() };
1023    ///
1024    /// assert_eq!(*values, [0, 0, 0])
1025    /// ```
1026    ///
1027    /// [zeroed]: mem::MaybeUninit::zeroed
1028    #[cfg(not(no_global_oom_handling))]
1029    #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
1030    #[must_use]
1031    pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
1032        // SAFETY: `len` is exactly the capacity of this `RawVec`.
1033        unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
1034    }
1035
1036    /// Constructs a new boxed slice with uninitialized contents. Returns an error if
1037    /// the allocation fails.
1038    ///
1039    /// # Examples
1040    ///
1041    /// ```
1042    /// #![feature(allocator_ext)]
1043    ///
1044    /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
1045    /// // Deferred initialization:
1046    /// values[0].write(1);
1047    /// values[1].write(2);
1048    /// values[2].write(3);
1049    /// let values = unsafe { values.assume_init() };
1050    ///
1051    /// assert_eq!(*values, [1, 2, 3]);
1052    /// # Ok::<(), std::alloc::AllocError>(())
1053    /// ```
1054    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1055    #[inline]
1056    pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
1057        let ptr = if T::IS_ZST || len == 0 {
1058            NonNull::dangling()
1059        } else {
1060            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1061                Ok(l) => l,
1062                Err(_) => return Err(AllocError),
1063            };
1064            Global.allocate(layout)?.cast()
1065        };
1066        // SAFETY: `ptr` was just allocated with `Global` with the layout for an array of length
1067        // `len`, and the layout creation would have failed if `len` overflowed an isize.
1068        // `into_box` is sound to call since `len` corresponds to the length of the just-created
1069        // `RawVec`.
1070        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
1071    }
1072
1073    /// Constructs a new boxed slice with uninitialized contents, with the memory
1074    /// being filled with `0` bytes. Returns an error if the allocation fails.
1075    ///
1076    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1077    /// of this method.
1078    ///
1079    /// # Examples
1080    ///
1081    /// ```
1082    /// #![feature(allocator_ext)]
1083    ///
1084    /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
1085    /// let values = unsafe { values.assume_init() };
1086    ///
1087    /// assert_eq!(*values, [0, 0, 0]);
1088    /// # Ok::<(), std::alloc::AllocError>(())
1089    /// ```
1090    ///
1091    /// [zeroed]: mem::MaybeUninit::zeroed
1092    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1093    #[inline]
1094    pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
1095        let ptr = if T::IS_ZST || len == 0 {
1096            NonNull::dangling()
1097        } else {
1098            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1099                Ok(l) => l,
1100                Err(_) => return Err(AllocError),
1101            };
1102            Global.allocate_zeroed(layout)?.cast()
1103        };
1104        // SAFETY: `ptr` was just allocated with `Global` with the layout for an array of length
1105        // `len`, and the layout creation would have failed if `len` overflowed an isize.
1106        // `into_box` is sound to call since `len` corresponds to the length of the just-created
1107        // `RawVec`.
1108        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
1109    }
1110}
1111
1112impl<T, A: Allocator> Box<[T], A> {
1113    /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
1114    ///
1115    /// # Examples
1116    ///
1117    /// ```
1118    /// #![feature(allocator_ext)]
1119    ///
1120    /// use std::alloc::System;
1121    ///
1122    /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
1123    /// // Deferred initialization:
1124    /// values[0].write(1);
1125    /// values[1].write(2);
1126    /// values[2].write(3);
1127    /// let values = unsafe { values.assume_init() };
1128    ///
1129    /// assert_eq!(*values, [1, 2, 3])
1130    /// ```
1131    #[cfg(not(no_global_oom_handling))]
1132    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1133    #[must_use]
1134    pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
1135        // SAFETY: `len` is exactly the capacity of this `RawVec`.
1136        unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
1137    }
1138
1139    /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
1140    /// with the memory being filled with `0` bytes.
1141    ///
1142    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1143    /// of this method.
1144    ///
1145    /// # Examples
1146    ///
1147    /// ```
1148    /// #![feature(allocator_ext)]
1149    ///
1150    /// use std::alloc::System;
1151    ///
1152    /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
1153    /// let values = unsafe { values.assume_init() };
1154    ///
1155    /// assert_eq!(*values, [0, 0, 0])
1156    /// ```
1157    ///
1158    /// [zeroed]: mem::MaybeUninit::zeroed
1159    #[cfg(not(no_global_oom_handling))]
1160    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1161    #[must_use]
1162    pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
1163        // SAFETY: `len` is exactly the capacity of this `RawVec`.
1164        unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
1165    }
1166
1167    /// Constructs a new boxed slice with uninitialized contents in the provided allocator. Returns an error if
1168    /// the allocation fails.
1169    ///
1170    /// # Examples
1171    ///
1172    /// ```
1173    /// #![feature(allocator_ext)]
1174    ///
1175    /// use std::alloc::System;
1176    ///
1177    /// let mut values = Box::<[u32], _>::try_new_uninit_slice_in(3, System)?;
1178    /// // Deferred initialization:
1179    /// values[0].write(1);
1180    /// values[1].write(2);
1181    /// values[2].write(3);
1182    /// let values = unsafe { values.assume_init() };
1183    ///
1184    /// assert_eq!(*values, [1, 2, 3]);
1185    /// # Ok::<(), std::alloc::AllocError>(())
1186    /// ```
1187    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1188    #[inline]
1189    pub fn try_new_uninit_slice_in(
1190        len: usize,
1191        alloc: A,
1192    ) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError> {
1193        let ptr = if T::IS_ZST || len == 0 {
1194            NonNull::dangling()
1195        } else {
1196            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1197                Ok(l) => l,
1198                Err(_) => return Err(AllocError),
1199            };
1200            alloc.allocate(layout)?.cast()
1201        };
1202        // SAFETY: `ptr` was just allocated with `alloc` with the layout for an array of length
1203        // `len`, and the layout creation would have failed if `len` overflowed an isize.
1204        // `into_box` is sound to call since `len` corresponds to the length of the just-created
1205        // `RawVec`.
1206        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) }
1207    }
1208
1209    /// Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory
1210    /// being filled with `0` bytes. Returns an error if the allocation fails.
1211    ///
1212    /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1213    /// of this method.
1214    ///
1215    /// # Examples
1216    ///
1217    /// ```
1218    /// #![feature(allocator_ext)]
1219    ///
1220    /// use std::alloc::System;
1221    ///
1222    /// let values = Box::<[u32], _>::try_new_zeroed_slice_in(3, System)?;
1223    /// let values = unsafe { values.assume_init() };
1224    ///
1225    /// assert_eq!(*values, [0, 0, 0]);
1226    /// # Ok::<(), std::alloc::AllocError>(())
1227    /// ```
1228    ///
1229    /// [zeroed]: mem::MaybeUninit::zeroed
1230    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1231    #[inline]
1232    pub fn try_new_zeroed_slice_in(
1233        len: usize,
1234        alloc: A,
1235    ) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError> {
1236        let ptr = if T::IS_ZST || len == 0 {
1237            NonNull::dangling()
1238        } else {
1239            let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1240                Ok(l) => l,
1241                Err(_) => return Err(AllocError),
1242            };
1243            alloc.allocate_zeroed(layout)?.cast()
1244        };
1245        // SAFETY: `ptr` was just allocated with `alloc` with the layout for an array of length
1246        // `len`, and the layout creation would have failed if `len` overflowed an isize.
1247        // `into_box` is sound to call since `len` corresponds to the length of the just-created
1248        // `RawVec`.
1249        unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) }
1250    }
1251
1252    /// Converts the boxed slice into a boxed array.
1253    ///
1254    /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
1255    ///
1256    /// # Errors
1257    ///
1258    /// Returns the original `Box<[T]>` in the `Err` variant if `self.len()` does not equal `N`.
1259    ///
1260    /// # Examples
1261    ///
1262    /// ```
1263    /// #![feature(alloc_slice_into_array)]
1264    /// let box_slice: Box<[i32]> = Box::new([1, 2, 3]);
1265    ///
1266    /// let box_array: Box<[i32; 3]> = box_slice.into_array().unwrap();
1267    /// ```
1268    #[unstable(feature = "alloc_slice_into_array", issue = "148082")]
1269    #[inline]
1270    pub fn into_array<const N: usize>(self) -> Result<Box<[T; N], A>, Self> {
1271        if self.len() == N {
1272            let (ptr, alloc) = Self::into_raw_with_allocator(self);
1273            let ptr = ptr as *mut [T; N];
1274
1275            // 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.
1276            let me = unsafe { Box::from_raw_in(ptr, alloc) };
1277            Ok(me)
1278        } else {
1279            Err(self)
1280        }
1281    }
1282}
1283
1284impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
1285    /// Converts to `Box<T, A>`.
1286    ///
1287    /// # Safety
1288    ///
1289    /// As with [`MaybeUninit::assume_init`],
1290    /// it is up to the caller to guarantee that the value
1291    /// really is in an initialized state.
1292    /// Calling this when the content is not yet fully initialized
1293    /// causes immediate undefined behavior.
1294    ///
1295    /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1296    ///
1297    /// # Examples
1298    ///
1299    /// ```
1300    /// let mut five = Box::<u32>::new_uninit();
1301    /// // Deferred initialization:
1302    /// five.write(5);
1303    /// let five: Box<u32> = unsafe { five.assume_init() };
1304    ///
1305    /// assert_eq!(*five, 5)
1306    /// ```
1307    #[stable(feature = "new_uninit", since = "1.82.0")]
1308    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1309    #[inline(always)]
1310    pub const unsafe fn assume_init(self) -> Box<T, A> {
1311        // This is used in the `vec!` macro, so we optimize for minimal IR generation
1312        // even in debug builds.
1313        // SAFETY: `Box<T>` and `Box<MaybeUninit<T>>` have the same layout.
1314        unsafe { core::intrinsics::transmute_unchecked(self) }
1315    }
1316
1317    /// Writes the value and converts to `Box<T, A>`.
1318    ///
1319    /// This method converts the box similarly to [`Box::assume_init`] but
1320    /// writes `value` into it before conversion thus guaranteeing safety.
1321    /// In some scenarios use of this method may improve performance because
1322    /// the compiler may be able to optimize copying from stack.
1323    ///
1324    /// # Examples
1325    ///
1326    /// ```
1327    /// let big_box = Box::<[usize; 1024]>::new_uninit();
1328    ///
1329    /// let mut array = [0; 1024];
1330    /// for (i, place) in array.iter_mut().enumerate() {
1331    ///     *place = i;
1332    /// }
1333    ///
1334    /// // The optimizer may be able to elide this copy, so previous code writes
1335    /// // to heap directly.
1336    /// let big_box = Box::write(big_box, array);
1337    ///
1338    /// for (i, x) in big_box.iter().enumerate() {
1339    ///     assert_eq!(*x, i);
1340    /// }
1341    /// ```
1342    #[stable(feature = "box_uninit_write", since = "1.87.0")]
1343    #[inline]
1344    pub fn write(mut boxed: Self, value: T) -> Box<T, A> {
1345        // SAFETY: Writing initialises the boxed value.
1346        unsafe {
1347            (*boxed).write(value);
1348            boxed.assume_init()
1349        }
1350    }
1351}
1352
1353impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
1354    /// Converts to `Box<[T], A>`.
1355    ///
1356    /// # Safety
1357    ///
1358    /// As with [`MaybeUninit::assume_init`],
1359    /// it is up to the caller to guarantee that the values
1360    /// really are in an initialized state.
1361    /// Calling this when the content is not yet fully initialized
1362    /// causes immediate undefined behavior.
1363    ///
1364    /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1365    ///
1366    /// # Examples
1367    ///
1368    /// ```
1369    /// let mut values = Box::<[u32]>::new_uninit_slice(3);
1370    /// // Deferred initialization:
1371    /// values[0].write(1);
1372    /// values[1].write(2);
1373    /// values[2].write(3);
1374    /// let values = unsafe { values.assume_init() };
1375    ///
1376    /// assert_eq!(*values, [1, 2, 3])
1377    /// ```
1378    #[stable(feature = "new_uninit", since = "1.82.0")]
1379    #[inline]
1380    pub unsafe fn assume_init(self) -> Box<[T], A> {
1381        let (raw, alloc) = Box::into_raw_with_allocator(self);
1382        // SAFETY: Upheld by caller.
1383        unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
1384    }
1385}
1386
1387impl<T: ?Sized> Box<T> {
1388    /// Constructs a box from a raw pointer.
1389    ///
1390    /// After calling this function, the raw pointer is owned by the
1391    /// resulting `Box`. Specifically, the `Box` destructor will call
1392    /// the destructor of `T` and free the allocated memory. For this
1393    /// to be safe, the memory must have been allocated in accordance
1394    /// with the [memory layout] used by `Box` .
1395    ///
1396    /// # Safety
1397    ///
1398    /// This function is unsafe because improper use may lead to
1399    /// memory problems. For example, a double-free may occur if the
1400    /// function is called twice on the same raw pointer.
1401    ///
1402    /// The exact safety requirements are described in the [memory layout] section, together
1403    /// with recommendations about how to handle the special case of zero-sized allocations
1404    /// correctly.
1405    ///
1406    /// In particular, if the size of the pointee, as reported by [`size_of_val`], is
1407    /// nonzero, then the raw pointer must point to a block of memory allocated by
1408    /// [`Global`].
1409    /// If the size of the pointee is zero, then the raw pointer can be any
1410    /// sufficiently aligned non-null pointer, e.g. [`ptr::dangling`].
1411    ///
1412    /// Note that the [considerations for unsafe code] apply to all `Box<T>` values.
1413    ///
1414    /// # Examples
1415    ///
1416    /// Recreate a `Box` which was previously converted to a raw pointer
1417    /// using [`Box::into_raw`]:
1418    /// ```
1419    /// let x = Box::new(5);
1420    /// let ptr = Box::into_raw(x);
1421    /// let x = unsafe { Box::from_raw(ptr) };
1422    /// ```
1423    /// Manually create a `Box` from scratch by using the global allocator:
1424    /// ```
1425    /// use std::alloc::{alloc, Layout};
1426    ///
1427    /// unsafe {
1428    ///     let ptr = alloc(Layout::new::<i32>()) as *mut i32;
1429    ///     // In general .write is required to avoid attempting to destruct
1430    ///     // the (uninitialized) previous contents of `ptr`, though for this
1431    ///     // simple example `*ptr = 5` would have worked as well.
1432    ///     ptr.write(5);
1433    ///     let x = Box::from_raw(ptr);
1434    /// }
1435    /// ```
1436    ///
1437    /// [memory layout]: self#memory-layout
1438    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1439    #[stable(feature = "box_raw", since = "1.4.0")]
1440    #[inline]
1441    #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
1442    pub unsafe fn from_raw(raw: *mut T) -> Self {
1443        // SAFETY: Upheld by caller.
1444        unsafe { Self::from_raw_in(raw, Global) }
1445    }
1446
1447    /// Constructs a box from a `NonNull` pointer.
1448    ///
1449    /// After calling this function, the `NonNull` pointer is owned by
1450    /// the resulting `Box`. Specifically, the `Box` destructor will call
1451    /// the destructor of `T` and free the allocated memory. For this
1452    /// to be safe, the memory must have been allocated in accordance
1453    /// with the [memory layout] used by `Box` .
1454    ///
1455    /// # Safety
1456    ///
1457    /// This function is unsafe because improper use may lead to
1458    /// memory problems. For example, a double-free may occur if the
1459    /// function is called twice on the same `NonNull` pointer.
1460    ///
1461    /// The exact safety requirements are described in the [memory layout] section, together
1462    /// with recommendations about how to handle the special case of zero-sized allocations
1463    /// correctly.
1464    ///
1465    /// In particular, if the size of the pointee, as reported by [`size_of_val`], is
1466    /// nonzero, then the raw pointer must point to a block of memory allocated by
1467    /// [`Global`].
1468    /// If the size of the pointee is zero, then the raw pointer can be any
1469    /// sufficiently aligned pointer, e.g. [`NonNull::dangling`].
1470    ///
1471    /// Note that the [considerations for unsafe code] apply to all `Box<T>` values.
1472    ///
1473    /// # Examples
1474    ///
1475    /// Recreate a `Box` which was previously converted to a `NonNull`
1476    /// pointer using [`Box::into_non_null`]:
1477    /// ```
1478    /// let x = Box::new(5);
1479    /// let non_null = Box::into_non_null(x);
1480    /// let x = unsafe { Box::from_non_null(non_null) };
1481    /// ```
1482    /// Manually create a `Box` from scratch by using the global allocator:
1483    /// ```
1484    /// use std::alloc::{alloc, Layout};
1485    /// use std::ptr::NonNull;
1486    ///
1487    /// unsafe {
1488    ///     let non_null = NonNull::new(alloc(Layout::new::<i32>()).cast::<i32>())
1489    ///         .expect("alloc should have successfully allocated memory");
1490    ///     // In general .write is required to avoid attempting to destruct
1491    ///     // the (uninitialized) previous contents of `non_null`.
1492    ///     non_null.write(5);
1493    ///     let x = Box::from_non_null(non_null);
1494    /// }
1495    /// ```
1496    ///
1497    /// [memory layout]: self#memory-layout
1498    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1499    #[stable(feature = "box_vec_non_null", since = "1.99.0")]
1500    #[inline]
1501    #[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"]
1502    pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self {
1503        // SAFETY: Upheld by caller.
1504        unsafe { Self::from_raw(ptr.as_ptr()) }
1505    }
1506
1507    /// Consumes the `Box`, returning a wrapped raw pointer.
1508    ///
1509    /// The pointer will be properly aligned and non-null.
1510    ///
1511    /// After calling this function, the caller is responsible for the
1512    /// memory previously managed by the `Box`. In particular, the
1513    /// caller should properly destroy `T` and release the memory, taking
1514    /// into account the [memory layout] used by `Box`. The easiest way to
1515    /// do this is to convert the raw pointer back into a `Box` with the
1516    /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1517    /// the cleanup.
1518    ///
1519    /// While manually deallocating the pointer through [`deallocate`]
1520    /// is possible, you must only do this if the pointee's size, as reported by
1521    /// [`size_of_val`], is non-zero (the `Box` may be a dangling pointer
1522    /// otherwise). See the [memory layout] section for more details.
1523    ///
1524    /// Note: this is an associated function, which means that you have
1525    /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1526    /// is so that there is no conflict with a method on the inner type.
1527    ///
1528    /// # Examples
1529    /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1530    /// for automatic cleanup:
1531    /// ```
1532    /// let x = Box::new(String::from("Hello"));
1533    /// let ptr = Box::into_raw(x);
1534    /// let x = unsafe { Box::from_raw(ptr) };
1535    /// ```
1536    /// Manual cleanup by explicitly running the destructor and deallocating
1537    /// the memory:
1538    /// ```
1539    /// use std::alloc::{dealloc, Layout};
1540    /// use std::ptr;
1541    ///
1542    /// let x = Box::new(String::from("Hello"));
1543    /// let ptr = Box::into_raw(x);
1544    /// unsafe {
1545    ///     ptr::drop_in_place(ptr);
1546    ///     dealloc(ptr as *mut u8, Layout::new::<String>());
1547    /// }
1548    /// ```
1549    /// Note: This is equivalent to the following:
1550    /// ```
1551    /// let x = Box::new(String::from("Hello"));
1552    /// let ptr = Box::into_raw(x);
1553    /// unsafe {
1554    ///     drop(Box::from_raw(ptr));
1555    /// }
1556    /// ```
1557    ///
1558    /// [memory layout]: self#memory-layout
1559    /// [`deallocate`]: Allocator::deallocate
1560    #[must_use = "losing the pointer will leak memory"]
1561    #[stable(feature = "box_raw", since = "1.4.0")]
1562    #[inline]
1563    pub fn into_raw(b: Self) -> *mut T {
1564        // Avoid `into_raw_with_allocator` as that interacts poorly with Miri's Stacked Borrows.
1565        let mut b = mem::ManuallyDrop::new(b);
1566        // We need to give Miri (specifically, Stacked Borrows) a chance to recognize this as a
1567        // safe-to-raw-pointer cast. To achieve this, we first create a mutable reference, and then
1568        // cast that to a raw pointer -- this cast is recognized by the aliasing model and leads to
1569        // a suitable retag.
1570        // It would be wrong for `into_raw_with_allocator` to do the same as that would induce
1571        // uniqueness assumptions (from the `&mut`) that we only want with the default allocator.
1572        (&mut **b) as *mut T
1573    }
1574
1575    /// Consumes the `Box`, returning a wrapped `NonNull` pointer.
1576    ///
1577    /// The pointer will be properly aligned.
1578    ///
1579    /// After calling this function, the caller is responsible for the
1580    /// memory previously managed by the `Box`. In particular, the
1581    /// caller should properly destroy `T` and release the memory, taking
1582    /// into account the [memory layout] used by `Box`. The easiest way to
1583    /// do this is to convert the `NonNull` pointer back into a `Box` with the
1584    /// [`Box::from_non_null`] function, allowing the `Box` destructor to
1585    /// perform the cleanup.
1586    ///
1587    /// While manually deallocating the pointer through [`deallocate`]
1588    /// is possible, you must only do this if the pointee's size, as reported by
1589    /// [`size_of_val`], is non-zero (the `Box` may be a dangling pointer
1590    /// otherwise). See the [memory layout] section for more details.
1591    ///
1592    /// Note: this is an associated function, which means that you have
1593    /// to call it as `Box::into_non_null(b)` instead of `b.into_non_null()`.
1594    /// This is so that there is no conflict with a method on the inner type.
1595    ///
1596    /// # Examples
1597    /// Converting the `NonNull` pointer back into a `Box` with [`Box::from_non_null`]
1598    /// for automatic cleanup:
1599    /// ```
1600    /// let x = Box::new(String::from("Hello"));
1601    /// let non_null = Box::into_non_null(x);
1602    /// let x = unsafe { Box::from_non_null(non_null) };
1603    /// ```
1604    /// Manual cleanup by explicitly running the destructor and deallocating
1605    /// the memory:
1606    /// ```
1607    /// use std::alloc::{dealloc, Layout};
1608    ///
1609    /// let x = Box::new(String::from("Hello"));
1610    /// let non_null = Box::into_non_null(x);
1611    /// unsafe {
1612    ///     non_null.drop_in_place();
1613    ///     dealloc(non_null.as_ptr().cast::<u8>(), Layout::new::<String>());
1614    /// }
1615    /// ```
1616    /// Note: This is equivalent to the following:
1617    /// ```
1618    /// let x = Box::new(String::from("Hello"));
1619    /// let non_null = Box::into_non_null(x);
1620    /// unsafe {
1621    ///     drop(Box::from_non_null(non_null));
1622    /// }
1623    /// ```
1624    ///
1625    /// [memory layout]: self#memory-layout
1626    /// [`deallocate`]: Allocator::deallocate
1627    #[must_use = "losing the pointer will leak memory"]
1628    #[stable(feature = "box_vec_non_null", since = "1.99.0")]
1629    #[inline]
1630    pub fn into_non_null(b: Self) -> NonNull<T> {
1631        // As of August 2026, we cannot utilize `Box::leak`
1632        // because whether or not you can reconstruct the `Box`
1633        // later using `Box::from_raw` or `Box::from_non_null` is
1634        // an open question.
1635        // SAFETY: `Box` is guaranteed to be non-null.
1636        unsafe { NonNull::new_unchecked(Self::into_raw(b)) }
1637    }
1638}
1639
1640impl<T: ?Sized, A: Allocator> Box<T, A> {
1641    /// Constructs a box from a raw pointer in the given allocator.
1642    ///
1643    /// After calling this function, the raw pointer is owned by the
1644    /// resulting `Box`. Specifically, the `Box` destructor will call
1645    /// the destructor of `T` and free the allocated memory, except
1646    /// in the cases described in the [memory layout] section.
1647    ///
1648    /// # Safety
1649    ///
1650    /// This function is unsafe because improper use may lead to
1651    /// memory problems. For example, a double-free may occur if the
1652    /// function is called twice on the same raw pointer.
1653    ///
1654    /// The exact safety requirements are described in the [memory layout] section, together
1655    /// with recommendations about how to handle the special case of zero-sized allocations
1656    /// correctly.
1657    ///
1658    /// In particular, if the size of the pointee, as reported by [`size_of_val`], is
1659    /// nonzero, then the raw pointer must point to a block of memory allocated by
1660    /// `alloc`.
1661    /// If the size of the pointee is zero, then the raw pointer can be any
1662    /// sufficiently aligned non-null pointer, e.g. [`ptr::dangling`].
1663    ///
1664    /// Note that the [considerations for unsafe code] apply to all `Box<T, A>` values.
1665    ///
1666    /// # Examples
1667    ///
1668    /// Recreate a `Box` which was previously converted to a raw pointer
1669    /// using [`Box::into_raw_with_allocator`]:
1670    /// ```
1671    /// use std::alloc::System;
1672    ///
1673    /// let x = Box::new_in(5, System);
1674    /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1675    /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1676    /// ```
1677    /// Manually create a `Box` from scratch by using the system allocator:
1678    /// ```
1679    /// #![feature(slice_ptr_get)]
1680    ///
1681    /// use std::alloc::{Allocator, Layout, System};
1682    ///
1683    /// unsafe {
1684    ///     let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1685    ///     // In general .write is required to avoid attempting to destruct
1686    ///     // the (uninitialized) previous contents of `ptr`, though for this
1687    ///     // simple example `*ptr = 5` would have worked as well.
1688    ///     ptr.write(5);
1689    ///     let x = Box::from_raw_in(ptr, System);
1690    /// }
1691    /// # Ok::<(), std::alloc::AllocError>(())
1692    /// ```
1693    ///
1694    /// [memory layout]: self#memory-layout
1695    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1696    #[stable(feature = "allocator_api", since = "1.100.0")]
1697    #[inline]
1698    pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1699        // SAFETY: Upheld by caller.
1700        Box(unsafe { BoxRaw::new_unchecked(raw) }, alloc)
1701    }
1702
1703    /// Constructs a box from a `NonNull` pointer in the given allocator.
1704    ///
1705    /// After calling this function, the `NonNull` pointer is owned by
1706    /// the resulting `Box`. Specifically, the `Box` destructor will call
1707    /// the destructor of `T` and free the allocated memory, except
1708    /// in the cases described in the [memory layout] section.
1709    ///
1710    /// # Safety
1711    ///
1712    /// This function is unsafe because improper use may lead to
1713    /// memory problems. For example, a double-free may occur if the
1714    /// function is called twice on the same raw pointer.
1715    ///
1716    /// The exact safety requirements are described in the [memory layout] section, together
1717    /// with recommendations about how to handle the special case of zero-sized allocations
1718    /// correctly.
1719    ///
1720    /// In particular, if the size of the pointee, as reported by [`size_of_val`], is
1721    /// nonzero, then the raw pointer must point to a block of memory allocated by
1722    /// `alloc`.
1723    /// If the size of the pointee is zero, then the raw pointer can be any
1724    /// sufficiently aligned pointer, e.g. [`NonNull::dangling`].
1725    ///
1726    /// Note that the [considerations for unsafe code] apply to all `Box<T, A>` values.
1727    ///
1728    /// # Examples
1729    ///
1730    /// Recreate a `Box` which was previously converted to a `NonNull` pointer
1731    /// using [`Box::into_non_null_with_allocator`]:
1732    /// ```
1733    /// use std::alloc::System;
1734    ///
1735    /// let x = Box::new_in(5, System);
1736    /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1737    /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1738    /// ```
1739    /// Manually create a `Box` from scratch by using the system allocator:
1740    /// ```
1741    /// use std::alloc::{Allocator, Layout, System};
1742    ///
1743    /// unsafe {
1744    ///     let non_null = System.allocate(Layout::new::<i32>())?.cast::<i32>();
1745    ///     // In general .write is required to avoid attempting to destruct
1746    ///     // the (uninitialized) previous contents of `non_null`.
1747    ///     non_null.write(5);
1748    ///     let x = Box::from_non_null_in(non_null, System);
1749    /// }
1750    /// # Ok::<(), std::alloc::AllocError>(())
1751    /// ```
1752    ///
1753    /// [memory layout]: self#memory-layout
1754    /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1755    #[stable(feature = "allocator_api", since = "1.100.0")]
1756    #[inline]
1757    pub unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Self {
1758        // SAFETY: guaranteed by the caller.
1759        unsafe { Box::from_raw_in(raw.as_ptr(), alloc) }
1760    }
1761
1762    /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1763    ///
1764    /// The pointer will be properly aligned and non-null.
1765    ///
1766    /// After calling this function, the caller is responsible for the
1767    /// memory previously managed by the `Box`. In particular, the
1768    /// caller should properly destroy `T` and release the memory, taking
1769    /// into account the [memory layout] used by `Box`. The easiest way to
1770    /// do this is to convert the raw pointer back into a `Box` with the
1771    /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1772    /// the cleanup.
1773    ///
1774    /// While manually deallocating the pointer through [`deallocate`]
1775    /// is possible, you must only do this if the pointee's size, as reported by
1776    /// [`size_of_val`], is non-zero (the `Box` may be a dangling pointer
1777    /// otherwise). See the [memory layout] section for more details.
1778    ///
1779    /// Note: this is an associated function, which means that you have
1780    /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1781    /// is so that there is no conflict with a method on the inner type.
1782    ///
1783    /// # Examples
1784    /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1785    /// for automatic cleanup:
1786    /// ```
1787    /// use std::alloc::System;
1788    ///
1789    /// let x = Box::new_in(String::from("Hello"), System);
1790    /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1791    /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1792    /// ```
1793    /// Manual cleanup by explicitly running the destructor and deallocating
1794    /// the memory:
1795    /// ```
1796    /// use std::alloc::{Allocator, Layout, System};
1797    /// use std::ptr::{self, NonNull};
1798    ///
1799    /// let x = Box::new_in(String::from("Hello"), System);
1800    /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1801    /// unsafe {
1802    ///     ptr::drop_in_place(ptr);
1803    ///     let non_null = NonNull::new_unchecked(ptr);
1804    ///     alloc.deallocate(non_null.cast(), Layout::new::<String>());
1805    /// }
1806    /// ```
1807    ///
1808    /// [memory layout]: self#memory-layout
1809    /// [`deallocate`]: Allocator::deallocate
1810    #[must_use = "losing the pointer will leak memory"]
1811    #[stable(feature = "allocator_api", since = "1.100.0")]
1812    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1813    #[inline]
1814    pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1815        let mut b = mem::ManuallyDrop::new(b);
1816        // We carefully get the raw pointer out in a way that Miri's aliasing model understands what
1817        // is happening: using the primitive "deref" of `Box`. In case `A` is *not* `Global`, we
1818        // want *no* aliasing requirements here!
1819        // In case `A` *is* `Global`, this does not quite have the right behavior; `into_raw`
1820        // works around that.
1821        let ptr = &raw mut **b;
1822        // SAFETY: See above.
1823        let alloc = unsafe { ptr::read(&b.1) };
1824        (ptr, alloc)
1825    }
1826
1827    /// Consumes the `Box`, returning a wrapped `NonNull` pointer and the allocator.
1828    ///
1829    /// The pointer will be properly aligned.
1830    ///
1831    /// After calling this function, the caller is responsible for the
1832    /// memory previously managed by the `Box`. In particular, the
1833    /// caller should properly destroy `T` and release the memory, taking
1834    /// into account the [memory layout] used by `Box`. The easiest way to
1835    /// do this is to convert the `NonNull` pointer back into a `Box` with the
1836    /// [`Box::from_non_null_in`] function, allowing the `Box` destructor to
1837    /// perform the cleanup.
1838    ///
1839    /// While manually deallocating the pointer through [`deallocate`]
1840    /// is possible, you must only do this if the pointee's size, as reported by
1841    /// [`size_of_val`], is non-zero (the `Box` may be a dangling pointer
1842    /// otherwise). See the [memory layout] section for more details.
1843    ///
1844    /// Note: this is an associated function, which means that you have
1845    /// to call it as `Box::into_non_null_with_allocator(b)` instead of
1846    /// `b.into_non_null_with_allocator()`. This is so that there is no
1847    /// conflict with a method on the inner type.
1848    ///
1849    /// # Examples
1850    /// Converting the `NonNull` pointer back into a `Box` with
1851    /// [`Box::from_non_null_in`] for automatic cleanup:
1852    /// ```
1853    /// use std::alloc::System;
1854    ///
1855    /// let x = Box::new_in(String::from("Hello"), System);
1856    /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1857    /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1858    /// ```
1859    /// Manual cleanup by explicitly running the destructor and deallocating
1860    /// the memory:
1861    /// ```
1862    /// use std::alloc::{Allocator, Layout, System};
1863    ///
1864    /// let x = Box::new_in(String::from("Hello"), System);
1865    /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1866    /// unsafe {
1867    ///     non_null.drop_in_place();
1868    ///     alloc.deallocate(non_null.cast::<u8>(), Layout::new::<String>());
1869    /// }
1870    /// ```
1871    ///
1872    /// [memory layout]: self#memory-layout
1873    /// [`deallocate`]: Allocator::deallocate
1874    #[must_use = "losing the pointer will leak memory"]
1875    #[stable(feature = "allocator_api", since = "1.100.0")]
1876    #[inline]
1877    pub fn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A) {
1878        let (ptr, alloc) = Box::into_raw_with_allocator(b);
1879        // SAFETY: `Box` is guaranteed to be non-null.
1880        unsafe { (NonNull::new_unchecked(ptr), alloc) }
1881    }
1882
1883    /// Returns a raw mutable pointer to the `Box`'s contents.
1884    ///
1885    /// The caller must ensure that the `Box` outlives the pointer this
1886    /// function returns, or else it will end up dangling.
1887    ///
1888    /// This method guarantees that for the purpose of the aliasing model, this method
1889    /// does not materialize a reference to the underlying memory, and thus the returned pointer
1890    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], and [`as_non_null`].
1891    /// Note that calling other methods that materialize references to the memory
1892    /// may still invalidate this pointer.
1893    /// See the example below for how this guarantee can be used.
1894    ///
1895    /// # Examples
1896    ///
1897    /// Due to the aliasing guarantee, the following code is legal:
1898    ///
1899    /// ```rust
1900    /// unsafe {
1901    ///     let mut b = Box::new(0);
1902    ///     let ptr1 = Box::as_mut_ptr(&mut b);
1903    ///     ptr1.write(1);
1904    ///     let ptr2 = Box::as_mut_ptr(&mut b);
1905    ///     ptr2.write(2);
1906    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1907    ///     ptr1.write(3);
1908    /// }
1909    /// ```
1910    ///
1911    /// [`as_mut_ptr`]: Self::as_mut_ptr
1912    /// [`as_ptr`]: Self::as_ptr
1913    /// [`as_non_null`]: Self::as_non_null
1914    #[must_use]
1915    #[stable(feature = "box_as_ptr", since = "1.98.0")]
1916    #[rustc_never_returns_null_ptr]
1917    #[rustc_as_ptr]
1918    #[inline]
1919    pub fn as_mut_ptr(b: &mut Self) -> *mut T {
1920        // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1921        // any references.
1922        &raw mut **b
1923    }
1924
1925    /// Returns a raw pointer to the `Box`'s contents.
1926    ///
1927    /// The caller must ensure that the `Box` outlives the pointer this
1928    /// function returns, or else it will end up dangling.
1929    ///
1930    /// The caller must also ensure that the memory the pointer (non-transitively) points to
1931    /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1932    /// derived from it. If you need to mutate the contents of the `Box`, use [`as_mut_ptr`].
1933    ///
1934    /// This method guarantees that for the purpose of the aliasing model, this method
1935    /// does not materialize a reference to the underlying memory, and thus the returned pointer
1936    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], and [`as_non_null`].
1937    /// Note that calling other methods that materialize mutable references to the memory,
1938    /// as well as writing to this memory, may still invalidate this pointer.
1939    /// See the example below for how this guarantee can be used.
1940    ///
1941    /// # Examples
1942    ///
1943    /// Due to the aliasing guarantee, the following code is legal:
1944    ///
1945    /// ```rust
1946    /// unsafe {
1947    ///     let mut v = Box::new(0);
1948    ///     let ptr1 = Box::as_ptr(&v);
1949    ///     let ptr2 = Box::as_mut_ptr(&mut v);
1950    ///     let _val = ptr2.read();
1951    ///     // No write to this memory has happened yet, so `ptr1` is still valid.
1952    ///     let _val = ptr1.read();
1953    ///     // However, once we do a write...
1954    ///     ptr2.write(1);
1955    ///     // ... `ptr1` is no longer valid.
1956    ///     // This would be UB: let _val = ptr1.read();
1957    /// }
1958    /// ```
1959    ///
1960    /// [`as_mut_ptr`]: Self::as_mut_ptr
1961    /// [`as_ptr`]: Self::as_ptr
1962    /// [`as_non_null`]: Self::as_non_null
1963    #[must_use]
1964    #[stable(feature = "box_as_ptr", since = "1.98.0")]
1965    #[rustc_never_returns_null_ptr]
1966    #[rustc_as_ptr]
1967    #[inline]
1968    pub fn as_ptr(b: &Self) -> *const T {
1969        // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1970        // any references.
1971        &raw const **b
1972    }
1973
1974    /// Returns a `NonNull` pointer to the `Box`'s contents.
1975    ///
1976    /// The caller must ensure that the `Box` outlives the pointer this
1977    /// function returns, or else it will end up dangling.
1978    ///
1979    /// This method guarantees that for the purpose of the aliasing model, this method
1980    /// does not materialize a reference to the underlying memory, and thus the returned pointer
1981    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], and [`as_non_null`].
1982    /// Note that calling other methods that materialize references to the memory
1983    /// may still invalidate this pointer.
1984    /// See the example below for how this guarantee can be used.
1985    ///
1986    /// # Examples
1987    ///
1988    /// Due to the aliasing guarantee, the following code is legal:
1989    ///
1990    /// ```rust
1991    /// #![feature(box_as_non_null)]
1992    ///
1993    /// unsafe {
1994    ///     let mut b = Box::new(0);
1995    ///     let ptr1 = Box::as_non_null(&mut b);
1996    ///     ptr1.write(1);
1997    ///     let ptr2 = Box::as_non_null(&mut b);
1998    ///     ptr2.write(2);
1999    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
2000    ///     ptr1.write(3);
2001    /// }
2002    /// ```
2003    ///
2004    /// [`as_mut_ptr`]: Self::as_mut_ptr
2005    /// [`as_ptr`]: Self::as_ptr
2006    /// [`as_non_null`]: Self::as_non_null
2007    #[must_use]
2008    #[unstable(feature = "box_as_non_null", issue = "157345")]
2009    #[rustc_as_ptr]
2010    #[inline]
2011    pub fn as_non_null(b: &mut Self) -> NonNull<T> {
2012        // SAFETY: `Box` is guaranteed to be non-null.
2013        unsafe { NonNull::new_unchecked(Self::as_mut_ptr(b)) }
2014    }
2015
2016    /// Returns a reference to the underlying allocator.
2017    ///
2018    /// Note: this is an associated function, which means that you have
2019    /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
2020    /// is so that there is no conflict with a method on the inner type.
2021    #[stable(feature = "allocator_api", since = "1.100.0")]
2022    #[inline]
2023    pub fn allocator(b: &Self) -> &A {
2024        &b.1
2025    }
2026
2027    /// Consumes and leaks the `Box`, returning a mutable reference,
2028    /// `&'a mut T`.
2029    ///
2030    /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
2031    /// has only static references, or none at all, then this may be chosen to be
2032    /// `'static`.
2033    ///
2034    /// This function is mainly useful for data that lives for the remainder of the program's life,
2035    /// i.e., memory that is meant to leak. If the memory should eventually be freed, prefer to use
2036    /// [`Box::into_raw`] or [`Box::into_non_null`] instead. Reconstructing ("unleaking") a `Box` from
2037    /// the mutable reference returned here (e.g. via [`Box::from_raw`]) is only possible if the
2038    /// allocator is `Global`, and even then it is a grey area (meaning it is possible under specific
2039    /// circumstances but many seemingly harmless ways of doing it are undefined behavior) and should
2040    /// be avoided.
2041    ///
2042    /// Note: this is an associated function, which means that you have
2043    /// to call it as `Box::leak(b)` instead of `b.leak()`. This
2044    /// is so that there is no conflict with a method on the inner type.
2045    ///
2046    /// # Examples
2047    ///
2048    /// Simple usage:
2049    ///
2050    /// ```
2051    /// let x = Box::new(41);
2052    /// let static_ref: &'static mut usize = Box::leak(x);
2053    /// *static_ref += 1;
2054    /// assert_eq!(*static_ref, 42);
2055    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2056    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2057    /// # drop(unsafe { Box::from_raw(static_ref) });
2058    /// ```
2059    ///
2060    /// Unsized data:
2061    ///
2062    /// ```
2063    /// let x = vec![1, 2, 3].into_boxed_slice();
2064    /// let static_ref = Box::leak(x);
2065    /// static_ref[0] = 4;
2066    /// assert_eq!(*static_ref, [4, 2, 3]);
2067    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2068    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2069    /// # drop(unsafe { Box::from_raw(static_ref) });
2070    /// ```
2071    #[stable(feature = "box_leak", since = "1.26.0")]
2072    #[inline]
2073    pub fn leak<'a>(b: Self) -> &'a mut T
2074    where
2075        A: 'a,
2076    {
2077        let (ptr, alloc) = Box::into_raw_with_allocator(b);
2078        mem::forget(alloc);
2079        // SAFETY: Pointer is valid and unique.
2080        unsafe { &mut *ptr }
2081    }
2082
2083    /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
2084    /// `*boxed` will be pinned in memory and unable to be moved.
2085    ///
2086    /// This conversion does not allocate on the heap and happens in place.
2087    ///
2088    /// This is also available via [`From`].
2089    ///
2090    /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
2091    /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
2092    /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
2093    /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
2094    ///
2095    /// # Notes
2096    ///
2097    /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
2098    /// as it'll introduce an ambiguity when calling `Pin::from`.
2099    /// A demonstration of such a poor impl is shown below.
2100    ///
2101    /// ```compile_fail
2102    /// # use std::pin::Pin;
2103    /// struct Foo; // A type defined in this crate.
2104    /// impl From<Box<()>> for Pin<Foo> {
2105    ///     fn from(_: Box<()>) -> Pin<Foo> {
2106    ///         Pin::new(Foo)
2107    ///     }
2108    /// }
2109    ///
2110    /// let foo = Box::new(());
2111    /// let bar = Pin::from(foo);
2112    /// ```
2113    #[stable(feature = "box_into_pin", since = "1.63.0")]
2114    pub fn into_pin(boxed: Self) -> Pin<Self>
2115    where
2116        A: StaticAllocator,
2117    {
2118        // SAFETY: It's not possible to move or replace the insides of a
2119        // `Pin<Box<T>>` when `T: !Unpin`, so it's safe to pin it directly
2120        // so long as the allocator promises to not break the pinning invariants.
2121        unsafe { Pin::new_unchecked(boxed) }
2122    }
2123}
2124
2125#[stable(feature = "rust1", since = "1.0.0")]
2126unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
2127    #[inline]
2128    fn drop(&mut self) {
2129        // the T in the Box is dropped by the compiler before the destructor is run
2130
2131        let ptr = self.0;
2132
2133        // SAFETY: The construction site of the unsized box had ensured for us that the
2134        // allocation was made with a valid layout (the size does not overflow an isize,
2135        // possibly because the size of the type is 0).
2136        let layout = unsafe { Layout::for_value_raw(ptr.as_ptr()) };
2137        if layout.size() != 0 {
2138            // SAFETY: Any nonzero allocation would have been created with the allocator
2139            // of this box and `layout` would fit that allocation. We also are the only ones
2140            // responsible for doing this deallocation and know that the pointer must be valid.
2141            unsafe {
2142                self.1.deallocate(From::from(ptr.cast()), layout);
2143            }
2144        }
2145    }
2146}
2147
2148#[cfg(not(no_global_oom_handling))]
2149#[stable(feature = "rust1", since = "1.0.0")]
2150impl<T: Default> Default for Box<T> {
2151    /// Creates a `Box<T>`, with the `Default` value for `T`.
2152    #[inline]
2153    fn default() -> Self {
2154        let mut x: Box<mem::MaybeUninit<T>> = Box::new_uninit();
2155
2156        // SAFETY: `x` is valid for writing and has the same layout as `T`.
2157        // If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
2158        // does not have a destructor.
2159        //
2160        // We use `ptr::write` as `MaybeUninit::write` creates
2161        // extra stack copies of `T` in debug mode.
2162        //
2163        // See https://github.com/rust-lang/rust/issues/136043 for more context.
2164        unsafe { ptr::write(&raw mut *x as *mut T, T::default()) };
2165        // SAFETY: `x` was just initialized above.
2166        unsafe { x.assume_init() }
2167    }
2168}
2169
2170#[cfg(not(no_global_oom_handling))]
2171#[stable(feature = "rust1", since = "1.0.0")]
2172impl<T> Default for Box<[T]> {
2173    /// Creates an empty `[T]` inside a `Box`.
2174    #[inline]
2175    fn default() -> Self {
2176        let ptr: BoxRaw<[T]> = BoxRaw::<[T; 0]>::dangling();
2177        // SAFETY: `[T; 0]` is a ZST, for which `dangling` is valid to turn into a `Box`,
2178        // even after unsize coercion.
2179        Box(ptr, Global)
2180    }
2181}
2182
2183#[cfg(not(no_global_oom_handling))]
2184#[stable(feature = "default_box_extra", since = "1.17.0")]
2185impl Default for Box<str> {
2186    #[inline]
2187    fn default() -> Self {
2188        // SAFETY:
2189        // - `[u8; 0]` is a ZST, for which `dangling` is valid to turn into a `Box`
2190        // - Casting `[u8]` to `str` is correct
2191        // - The empty byte slice is valid UTF-8
2192        let ptr: BoxRaw<str> = unsafe {
2193            let bytes: BoxRaw<[u8]> = BoxRaw::<[u8; 0]>::dangling();
2194            BoxRaw::new_unchecked(bytes.as_ptr() as *mut str)
2195        };
2196        Box(ptr, Global)
2197    }
2198}
2199
2200#[cfg(not(no_global_oom_handling))]
2201#[stable(feature = "pin_default_impls", since = "1.91.0")]
2202impl<T> Default for Pin<Box<T>>
2203where
2204    T: ?Sized,
2205    Box<T>: Default,
2206{
2207    #[inline]
2208    fn default() -> Self {
2209        Box::into_pin(Box::<T>::default())
2210    }
2211}
2212
2213#[cfg(not(no_global_oom_handling))]
2214#[stable(feature = "rust1", since = "1.0.0")]
2215// NB: This is not `AllocatorClone` since we don't care about allocator
2216// equivalence when cloning boxes.
2217impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
2218    /// Returns a new box with a `clone()` of this box's contents.
2219    ///
2220    /// # Examples
2221    ///
2222    /// ```
2223    /// let x = Box::new(5);
2224    /// let y = x.clone();
2225    ///
2226    /// // The value is the same
2227    /// assert_eq!(x, y);
2228    ///
2229    /// // But they are unique objects
2230    /// assert_ne!(&*x as *const i32, &*y as *const i32);
2231    /// ```
2232    #[inline]
2233    fn clone(&self) -> Self {
2234        // Pre-allocate memory to allow writing the cloned value directly.
2235        let mut boxed = Self::new_uninit_in(self.1.clone());
2236        // SAFETY: Destination pointer is valid and will then become initialised.
2237        unsafe {
2238            (**self).clone_to_uninit(boxed.as_mut_ptr().cast());
2239            boxed.assume_init()
2240        }
2241    }
2242
2243    /// Copies `source`'s contents into `self` without creating a new allocation.
2244    ///
2245    /// # Examples
2246    ///
2247    /// ```
2248    /// let x = Box::new(5);
2249    /// let mut y = Box::new(10);
2250    /// let yp: *const i32 = &*y;
2251    ///
2252    /// y.clone_from(&x);
2253    ///
2254    /// // The value is the same
2255    /// assert_eq!(x, y);
2256    ///
2257    /// // And no allocation occurred
2258    /// assert_eq!(yp, &*y);
2259    /// ```
2260    #[inline]
2261    fn clone_from(&mut self, source: &Self) {
2262        (**self).clone_from(&(**source));
2263    }
2264}
2265
2266#[cfg(not(no_global_oom_handling))]
2267#[stable(feature = "box_slice_clone", since = "1.3.0")]
2268impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2269    fn clone(&self) -> Self {
2270        let alloc = Box::allocator(self).clone();
2271        self.to_vec_in(alloc).into_boxed_slice()
2272    }
2273
2274    /// Copies `source`'s contents into `self` without creating a new allocation,
2275    /// so long as the two are of the same length.
2276    ///
2277    /// # Examples
2278    ///
2279    /// ```
2280    /// let x = Box::new([5, 6, 7]);
2281    /// let mut y = Box::new([8, 9, 10]);
2282    /// let yp: *const [i32] = &*y;
2283    ///
2284    /// y.clone_from(&x);
2285    ///
2286    /// // The value is the same
2287    /// assert_eq!(x, y);
2288    ///
2289    /// // And no allocation occurred
2290    /// assert_eq!(yp, &*y);
2291    /// ```
2292    fn clone_from(&mut self, source: &Self) {
2293        if self.len() == source.len() {
2294            self.clone_from_slice(source);
2295        } else {
2296            *self = source.clone();
2297        }
2298    }
2299}
2300
2301#[cfg(not(no_global_oom_handling))]
2302#[stable(feature = "box_slice_clone", since = "1.3.0")]
2303impl<A: Allocator + Clone> Clone for Box<str, A> {
2304    fn clone(&self) -> Self {
2305        let buf = Box::clone_from_ref_in(self.as_bytes(), self.1.clone());
2306        // SAFETY: We know the [u8] is a valid str.
2307        unsafe { from_boxed_utf8_unchecked_in(buf) }
2308    }
2309}
2310
2311#[stable(feature = "rust1", since = "1.0.0")]
2312impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
2313    #[inline]
2314    fn eq(&self, other: &Self) -> bool {
2315        PartialEq::eq(&**self, &**other)
2316    }
2317    #[inline]
2318    fn ne(&self, other: &Self) -> bool {
2319        PartialEq::ne(&**self, &**other)
2320    }
2321}
2322
2323#[stable(feature = "rust1", since = "1.0.0")]
2324impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
2325    #[inline]
2326    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2327        PartialOrd::partial_cmp(&**self, &**other)
2328    }
2329    #[inline]
2330    fn lt(&self, other: &Self) -> bool {
2331        PartialOrd::lt(&**self, &**other)
2332    }
2333    #[inline]
2334    fn le(&self, other: &Self) -> bool {
2335        PartialOrd::le(&**self, &**other)
2336    }
2337    #[inline]
2338    fn ge(&self, other: &Self) -> bool {
2339        PartialOrd::ge(&**self, &**other)
2340    }
2341    #[inline]
2342    fn gt(&self, other: &Self) -> bool {
2343        PartialOrd::gt(&**self, &**other)
2344    }
2345}
2346
2347#[stable(feature = "rust1", since = "1.0.0")]
2348impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
2349    #[inline]
2350    fn cmp(&self, other: &Self) -> Ordering {
2351        Ord::cmp(&**self, &**other)
2352    }
2353}
2354
2355#[stable(feature = "rust1", since = "1.0.0")]
2356impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
2357
2358#[stable(feature = "rust1", since = "1.0.0")]
2359impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
2360    fn hash<H: Hasher>(&self, state: &mut H) {
2361        (**self).hash(state);
2362    }
2363}
2364
2365#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
2366impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
2367    fn finish(&self) -> u64 {
2368        (**self).finish()
2369    }
2370    fn write(&mut self, bytes: &[u8]) {
2371        (**self).write(bytes)
2372    }
2373    fn write_u8(&mut self, i: u8) {
2374        (**self).write_u8(i)
2375    }
2376    fn write_u16(&mut self, i: u16) {
2377        (**self).write_u16(i)
2378    }
2379    fn write_u32(&mut self, i: u32) {
2380        (**self).write_u32(i)
2381    }
2382    fn write_u64(&mut self, i: u64) {
2383        (**self).write_u64(i)
2384    }
2385    fn write_u128(&mut self, i: u128) {
2386        (**self).write_u128(i)
2387    }
2388    fn write_usize(&mut self, i: usize) {
2389        (**self).write_usize(i)
2390    }
2391    fn write_i8(&mut self, i: i8) {
2392        (**self).write_i8(i)
2393    }
2394    fn write_i16(&mut self, i: i16) {
2395        (**self).write_i16(i)
2396    }
2397    fn write_i32(&mut self, i: i32) {
2398        (**self).write_i32(i)
2399    }
2400    fn write_i64(&mut self, i: i64) {
2401        (**self).write_i64(i)
2402    }
2403    fn write_i128(&mut self, i: i128) {
2404        (**self).write_i128(i)
2405    }
2406    fn write_isize(&mut self, i: isize) {
2407        (**self).write_isize(i)
2408    }
2409    fn write_length_prefix(&mut self, len: usize) {
2410        (**self).write_length_prefix(len)
2411    }
2412    fn write_str(&mut self, s: &str) {
2413        (**self).write_str(s)
2414    }
2415}
2416
2417#[stable(feature = "rust1", since = "1.0.0")]
2418impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
2419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2420        fmt::Display::fmt(&**self, f)
2421    }
2422}
2423
2424#[stable(feature = "rust1", since = "1.0.0")]
2425impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
2426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2427        fmt::Debug::fmt(&**self, f)
2428    }
2429}
2430
2431#[stable(feature = "rust1", since = "1.0.0")]
2432impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
2433    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2434        // It's not possible to extract the inner Uniq directly from the Box,
2435        // instead we cast it to a *const which aliases the Unique
2436        let ptr: *const T = &**self;
2437        fmt::Pointer::fmt(&ptr, f)
2438    }
2439}
2440
2441#[stable(feature = "rust1", since = "1.0.0")]
2442impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
2443    type Target = T;
2444
2445    fn deref(&self) -> &T {
2446        self
2447    }
2448}
2449
2450#[stable(feature = "rust1", since = "1.0.0")]
2451impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
2452    fn deref_mut(&mut self) -> &mut T {
2453        self
2454    }
2455}
2456
2457#[unstable(feature = "deref_pure_trait", issue = "87121")]
2458unsafe impl<T: ?Sized, A: Allocator> DerefPure for Box<T, A> {}
2459
2460#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2461impl<T: ?Sized, A: Allocator> LegacyReceiver for Box<T, A> {}
2462
2463#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2464impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
2465    type Output = <F as FnOnce<Args>>::Output;
2466
2467    extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
2468        <F as FnOnce<Args>>::call_once(*self, args)
2469    }
2470}
2471
2472#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2473impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
2474    extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
2475        <F as FnMut<Args>>::call_mut(self, args)
2476    }
2477}
2478
2479#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2480impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2481    extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2482        <F as Fn<Args>>::call(self, args)
2483    }
2484}
2485
2486#[stable(feature = "async_closure", since = "1.85.0")]
2487impl<Args: Tuple, F: AsyncFnOnce<Args> + ?Sized, A: Allocator> AsyncFnOnce<Args> for Box<F, A> {
2488    type Output = F::Output;
2489    type CallOnceFuture = F::CallOnceFuture;
2490
2491    extern "rust-call" fn async_call_once(self, args: Args) -> Self::CallOnceFuture {
2492        F::async_call_once(*self, args)
2493    }
2494}
2495
2496#[stable(feature = "async_closure", since = "1.85.0")]
2497impl<Args: Tuple, F: AsyncFnMut<Args> + ?Sized, A: Allocator> AsyncFnMut<Args> for Box<F, A> {
2498    type CallRefFuture<'a>
2499        = F::CallRefFuture<'a>
2500    where
2501        Self: 'a;
2502
2503    extern "rust-call" fn async_call_mut(&mut self, args: Args) -> Self::CallRefFuture<'_> {
2504        F::async_call_mut(self, args)
2505    }
2506}
2507
2508#[stable(feature = "async_closure", since = "1.85.0")]
2509impl<Args: Tuple, F: AsyncFn<Args> + ?Sized, A: Allocator> AsyncFn<Args> for Box<F, A> {
2510    extern "rust-call" fn async_call(&self, args: Args) -> Self::CallRefFuture<'_> {
2511        F::async_call(self, args)
2512    }
2513}
2514
2515#[unstable(feature = "coerce_unsized", issue = "18598")]
2516impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2517
2518// A pointer can only be pin safe if it does not implement certain safe traits
2519// maliciously. Since `Box` is fundamental, downstream crates may be able to
2520// implement those traits for `Box<LocalType>`, so we must carefully check that
2521// this is not a problem for each trait.
2522//
2523// The `Box` type always implements `Deref` and `DerefMut`, so despite being
2524// fundamental, downstream crates cannot implement these traits for
2525// `Box<LocalType>`.
2526//
2527// Conversely, downstream crates are able to implement `Clone`, `Debug`, and
2528// `Display` for `Box<LocalType>` as long as `LocalType` does not implement
2529// said trait. However, the `Box<T>` type does not treat the existence of an
2530// `&Box<T>` as evidence that the `T` is not pinned, so this is not
2531// problematic.
2532//
2533// Finally, even if downstream crates provide their own implementation of
2534// `Clone` for `Box<LocalType>`, it is not problematic for the cloned box to be
2535// wrapped in `Pin`, since the same conversion could have been carried out
2536// safely as `Box::pin((*p).clone())`.
2537#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2538unsafe impl<T: ?Sized, A: StaticAllocator> PinSafePointer for Box<T, A> {}
2539
2540// It is quite crucial that we only allow the `Global` allocator here.
2541// Handling arbitrary custom allocators (which can affect the `Box` layout heavily!)
2542// would need a lot of codegen and interpreter adjustments.
2543#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2544impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2545
2546#[stable(feature = "box_borrow", since = "1.1.0")]
2547impl<T: ?Sized, A: Allocator> Borrow<T> for Box<T, A> {
2548    fn borrow(&self) -> &T {
2549        self
2550    }
2551}
2552
2553#[stable(feature = "box_borrow", since = "1.1.0")]
2554impl<T: ?Sized, A: Allocator> BorrowMut<T> for Box<T, A> {
2555    fn borrow_mut(&mut self) -> &mut T {
2556        self
2557    }
2558}
2559
2560#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2561impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2562    fn as_ref(&self) -> &T {
2563        self
2564    }
2565}
2566
2567#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2568impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2569    fn as_mut(&mut self) -> &mut T {
2570        self
2571    }
2572}
2573
2574/* Nota bene
2575 *
2576 *  We could have chosen not to add this impl, and instead have written a
2577 *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2578 *  because Box<T> implements Unpin even when T does not, as a result of
2579 *  this impl.
2580 *
2581 *  We chose this API instead of the alternative for a few reasons:
2582 *      - Logically, it is helpful to understand pinning in regard to the
2583 *        memory region being pointed to. For this reason none of the
2584 *        standard library pointer types support projecting through a pin
2585 *        (Box<T> is the only pointer type in std for which this would be
2586 *        safe.)
2587 *      - It is in practice very useful to have Box<T> be unconditionally
2588 *        Unpin because of trait objects, for which the structural auto
2589 *        trait functionality does not apply (e.g., Box<dyn Foo> would
2590 *        otherwise not be Unpin).
2591 *
2592 *  Another type with the same semantics as Box but only a conditional
2593 *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2594 *  could have a method to project a Pin<T> from it.
2595 */
2596#[stable(feature = "pin", since = "1.33.0")]
2597impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> {}
2598
2599#[unstable(feature = "coroutine_trait", issue = "43122")]
2600impl<G: ?Sized + Coroutine<R> + Unpin, R, A: Allocator> Coroutine<R> for Box<G, A> {
2601    type Yield = G::Yield;
2602    type Return = G::Return;
2603
2604    fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2605        G::resume(Pin::new(&mut *self), arg)
2606    }
2607}
2608
2609#[unstable(feature = "coroutine_trait", issue = "43122")]
2610impl<G: ?Sized + Coroutine<R>, R, A: Allocator> Coroutine<R> for Pin<Box<G, A>>
2611where
2612    A: StaticAllocator,
2613{
2614    type Yield = G::Yield;
2615    type Return = G::Return;
2616
2617    fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2618        G::resume((*self).as_mut(), arg)
2619    }
2620}
2621
2622#[stable(feature = "futures_api", since = "1.36.0")]
2623impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A> {
2624    type Output = F::Output;
2625
2626    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2627        F::poll(Pin::new(&mut *self), cx)
2628    }
2629}
2630
2631#[stable(feature = "box_error", since = "1.8.0")]
2632impl<E: Error, A: Allocator> Error for Box<E, A> {
2633    #[allow(deprecated)]
2634    fn cause(&self) -> Option<&dyn Error> {
2635        Error::cause(&**self)
2636    }
2637
2638    fn source(&self) -> Option<&(dyn Error + 'static)> {
2639        Error::source(&**self)
2640    }
2641
2642    fn provide<'b>(&'b self, request: &mut error::Request<'b>) {
2643        Error::provide(&**self, request);
2644    }
2645}
2646
2647#[stable(feature = "allocator_api", since = "1.100.0")]
2648unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Box<T, A> {
2649    #[inline]
2650    fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2651        (**self).allocate(layout)
2652    }
2653
2654    #[inline]
2655    fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2656        (**self).allocate_zeroed(layout)
2657    }
2658
2659    #[inline]
2660    unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
2661        // SAFETY: the safety contract must be upheld by the caller
2662        unsafe { (**self).deallocate(ptr, layout) }
2663    }
2664
2665    #[inline]
2666    unsafe fn grow(
2667        &self,
2668        ptr: NonNull<u8>,
2669        old_layout: Layout,
2670        new_layout: Layout,
2671    ) -> Result<NonNull<[u8]>, AllocError> {
2672        // SAFETY: the safety contract must be upheld by the caller
2673        unsafe { (**self).grow(ptr, old_layout, new_layout) }
2674    }
2675
2676    #[inline]
2677    unsafe fn grow_zeroed(
2678        &self,
2679        ptr: NonNull<u8>,
2680        old_layout: Layout,
2681        new_layout: Layout,
2682    ) -> Result<NonNull<[u8]>, AllocError> {
2683        // SAFETY: the safety contract must be upheld by the caller
2684        unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
2685    }
2686
2687    #[inline]
2688    unsafe fn shrink(
2689        &self,
2690        ptr: NonNull<u8>,
2691        old_layout: Layout,
2692        new_layout: Layout,
2693    ) -> Result<NonNull<[u8]>, AllocError> {
2694        // SAFETY: the safety contract must be upheld by the caller
2695        unsafe { (**self).shrink(ptr, old_layout, new_layout) }
2696    }
2697}
2698#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
2699#[unstable_feature_bound(allocator_ext)]
2700impl<T: ?Sized + Allocator, A: Allocator> AllocatorNightly for Box<T, A> {}
2701
2702#[unstable(feature = "random", issue = "130703")]
2703impl<R: core::random::Rng + ?Sized, A: Allocator> core::random::Rng for Box<R, A> {
2704    #[inline]
2705    fn fill_bytes(&mut self, bytes: &mut [u8]) {
2706        (**self).fill_bytes(bytes)
2707    }
2708}