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