Linux Audio

Check our new training course

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