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