Skip to main content

alloc/
boxed.rs

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