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