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