]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/boxed.rs
Auto merge of #95362 - scottmcm:calloc-arrays, r=Mark-Simulacrum
[rust.git] / library / alloc / src / boxed.rs
1 //! A pointer 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 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
126 //! [dereferencing]: core::ops::Deref
127 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
128 //! [`Global`]: crate::alloc::Global
129 //! [`Layout`]: crate::alloc::Layout
130 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
131 //! [valid]: ptr#safety
132
133 #![stable(feature = "rust1", since = "1.0.0")]
134
135 use core::any::Any;
136 use core::async_iter::AsyncIterator;
137 use core::borrow;
138 use core::cmp::Ordering;
139 use core::convert::{From, TryFrom};
140 use core::fmt;
141 use core::future::Future;
142 use core::hash::{Hash, Hasher};
143 #[cfg(not(no_global_oom_handling))]
144 use core::iter::FromIterator;
145 use core::iter::{FusedIterator, Iterator};
146 use core::marker::{Destruct, Unpin, Unsize};
147 use core::mem;
148 use core::ops::{
149     CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
150 };
151 use core::pin::Pin;
152 use core::ptr::{self, Unique};
153 use core::task::{Context, Poll};
154
155 #[cfg(not(no_global_oom_handling))]
156 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
157 use crate::alloc::{AllocError, Allocator, Global, Layout};
158 #[cfg(not(no_global_oom_handling))]
159 use crate::borrow::Cow;
160 use crate::raw_vec::RawVec;
161 #[cfg(not(no_global_oom_handling))]
162 use crate::str::from_boxed_utf8_unchecked;
163 #[cfg(not(no_global_oom_handling))]
164 use crate::vec::Vec;
165
166 #[unstable(feature = "thin_box", issue = "92791")]
167 pub use thin::ThinBox;
168
169 mod thin;
170
171 /// A pointer type for heap allocation.
172 ///
173 /// See the [module-level documentation](../../std/boxed/index.html) for more.
174 #[lang = "owned_box"]
175 #[fundamental]
176 #[stable(feature = "rust1", since = "1.0.0")]
177 // The declaration of the `Box` struct must be kept in sync with the
178 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
179 // on `box_free` for more details.
180 pub struct Box<
181     T: ?Sized,
182     #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
183 >(Unique<T>, A);
184
185 impl<T> Box<T> {
186     /// Allocates memory on the heap and then places `x` into it.
187     ///
188     /// This doesn't actually allocate if `T` is zero-sized.
189     ///
190     /// # Examples
191     ///
192     /// ```
193     /// let five = Box::new(5);
194     /// ```
195     #[cfg(not(no_global_oom_handling))]
196     #[inline(always)]
197     #[stable(feature = "rust1", since = "1.0.0")]
198     #[must_use]
199     pub fn new(x: T) -> Self {
200         box x
201     }
202
203     /// Constructs a new box with uninitialized contents.
204     ///
205     /// # Examples
206     ///
207     /// ```
208     /// #![feature(new_uninit)]
209     ///
210     /// let mut five = Box::<u32>::new_uninit();
211     ///
212     /// let five = unsafe {
213     ///     // Deferred initialization:
214     ///     five.as_mut_ptr().write(5);
215     ///
216     ///     five.assume_init()
217     /// };
218     ///
219     /// assert_eq!(*five, 5)
220     /// ```
221     #[cfg(not(no_global_oom_handling))]
222     #[unstable(feature = "new_uninit", issue = "63291")]
223     #[must_use]
224     #[inline]
225     pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
226         Self::new_uninit_in(Global)
227     }
228
229     /// Constructs a new `Box` with uninitialized contents, with the memory
230     /// being filled with `0` bytes.
231     ///
232     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
233     /// of this method.
234     ///
235     /// # Examples
236     ///
237     /// ```
238     /// #![feature(new_uninit)]
239     ///
240     /// let zero = Box::<u32>::new_zeroed();
241     /// let zero = unsafe { zero.assume_init() };
242     ///
243     /// assert_eq!(*zero, 0)
244     /// ```
245     ///
246     /// [zeroed]: mem::MaybeUninit::zeroed
247     #[cfg(not(no_global_oom_handling))]
248     #[inline]
249     #[unstable(feature = "new_uninit", issue = "63291")]
250     #[must_use]
251     pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
252         Self::new_zeroed_in(Global)
253     }
254
255     /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
256     /// `x` will be pinned in memory and unable to be moved.
257     #[cfg(not(no_global_oom_handling))]
258     #[stable(feature = "pin", since = "1.33.0")]
259     #[must_use]
260     #[inline(always)]
261     pub fn pin(x: T) -> Pin<Box<T>> {
262         (box x).into()
263     }
264
265     /// Allocates memory on the heap then places `x` into it,
266     /// returning an error if the allocation fails
267     ///
268     /// This doesn't actually allocate if `T` is zero-sized.
269     ///
270     /// # Examples
271     ///
272     /// ```
273     /// #![feature(allocator_api)]
274     ///
275     /// let five = Box::try_new(5)?;
276     /// # Ok::<(), std::alloc::AllocError>(())
277     /// ```
278     #[unstable(feature = "allocator_api", issue = "32838")]
279     #[inline]
280     pub fn try_new(x: T) -> Result<Self, AllocError> {
281         Self::try_new_in(x, Global)
282     }
283
284     /// Constructs a new box with uninitialized contents on the heap,
285     /// returning an error if the allocation fails
286     ///
287     /// # Examples
288     ///
289     /// ```
290     /// #![feature(allocator_api, new_uninit)]
291     ///
292     /// let mut five = Box::<u32>::try_new_uninit()?;
293     ///
294     /// let five = unsafe {
295     ///     // Deferred initialization:
296     ///     five.as_mut_ptr().write(5);
297     ///
298     ///     five.assume_init()
299     /// };
300     ///
301     /// assert_eq!(*five, 5);
302     /// # Ok::<(), std::alloc::AllocError>(())
303     /// ```
304     #[unstable(feature = "allocator_api", issue = "32838")]
305     // #[unstable(feature = "new_uninit", issue = "63291")]
306     #[inline]
307     pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
308         Box::try_new_uninit_in(Global)
309     }
310
311     /// Constructs a new `Box` with uninitialized contents, with the memory
312     /// being filled with `0` bytes on the heap
313     ///
314     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
315     /// of this method.
316     ///
317     /// # Examples
318     ///
319     /// ```
320     /// #![feature(allocator_api, new_uninit)]
321     ///
322     /// let zero = Box::<u32>::try_new_zeroed()?;
323     /// let zero = unsafe { zero.assume_init() };
324     ///
325     /// assert_eq!(*zero, 0);
326     /// # Ok::<(), std::alloc::AllocError>(())
327     /// ```
328     ///
329     /// [zeroed]: mem::MaybeUninit::zeroed
330     #[unstable(feature = "allocator_api", issue = "32838")]
331     // #[unstable(feature = "new_uninit", issue = "63291")]
332     #[inline]
333     pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
334         Box::try_new_zeroed_in(Global)
335     }
336 }
337
338 impl<T, A: Allocator> Box<T, A> {
339     /// Allocates memory in the given allocator then places `x` into it.
340     ///
341     /// This doesn't actually allocate if `T` is zero-sized.
342     ///
343     /// # Examples
344     ///
345     /// ```
346     /// #![feature(allocator_api)]
347     ///
348     /// use std::alloc::System;
349     ///
350     /// let five = Box::new_in(5, System);
351     /// ```
352     #[cfg(not(no_global_oom_handling))]
353     #[unstable(feature = "allocator_api", issue = "32838")]
354     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
355     #[must_use]
356     #[inline]
357     pub const fn new_in(x: T, alloc: A) -> Self
358     where
359         A: ~const Allocator + ~const Destruct,
360     {
361         let mut boxed = Self::new_uninit_in(alloc);
362         unsafe {
363             boxed.as_mut_ptr().write(x);
364             boxed.assume_init()
365         }
366     }
367
368     /// Allocates memory in the given allocator then places `x` into it,
369     /// returning an error if the allocation fails
370     ///
371     /// This doesn't actually allocate if `T` is zero-sized.
372     ///
373     /// # Examples
374     ///
375     /// ```
376     /// #![feature(allocator_api)]
377     ///
378     /// use std::alloc::System;
379     ///
380     /// let five = Box::try_new_in(5, System)?;
381     /// # Ok::<(), std::alloc::AllocError>(())
382     /// ```
383     #[unstable(feature = "allocator_api", issue = "32838")]
384     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
385     #[inline]
386     pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
387     where
388         T: ~const Destruct,
389         A: ~const Allocator + ~const Destruct,
390     {
391         let mut boxed = Self::try_new_uninit_in(alloc)?;
392         unsafe {
393             boxed.as_mut_ptr().write(x);
394             Ok(boxed.assume_init())
395         }
396     }
397
398     /// Constructs a new box with uninitialized contents in the provided allocator.
399     ///
400     /// # Examples
401     ///
402     /// ```
403     /// #![feature(allocator_api, new_uninit)]
404     ///
405     /// use std::alloc::System;
406     ///
407     /// let mut five = Box::<u32, _>::new_uninit_in(System);
408     ///
409     /// let five = unsafe {
410     ///     // Deferred initialization:
411     ///     five.as_mut_ptr().write(5);
412     ///
413     ///     five.assume_init()
414     /// };
415     ///
416     /// assert_eq!(*five, 5)
417     /// ```
418     #[unstable(feature = "allocator_api", issue = "32838")]
419     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
420     #[cfg(not(no_global_oom_handling))]
421     #[must_use]
422     // #[unstable(feature = "new_uninit", issue = "63291")]
423     pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
424     where
425         A: ~const Allocator + ~const Destruct,
426     {
427         let layout = Layout::new::<mem::MaybeUninit<T>>();
428         // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
429         // That would make code size bigger.
430         match Box::try_new_uninit_in(alloc) {
431             Ok(m) => m,
432             Err(_) => handle_alloc_error(layout),
433         }
434     }
435
436     /// Constructs a new box with uninitialized contents in the provided allocator,
437     /// returning an error if the allocation fails
438     ///
439     /// # Examples
440     ///
441     /// ```
442     /// #![feature(allocator_api, new_uninit)]
443     ///
444     /// use std::alloc::System;
445     ///
446     /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
447     ///
448     /// let five = unsafe {
449     ///     // Deferred initialization:
450     ///     five.as_mut_ptr().write(5);
451     ///
452     ///     five.assume_init()
453     /// };
454     ///
455     /// assert_eq!(*five, 5);
456     /// # Ok::<(), std::alloc::AllocError>(())
457     /// ```
458     #[unstable(feature = "allocator_api", issue = "32838")]
459     // #[unstable(feature = "new_uninit", issue = "63291")]
460     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
461     pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
462     where
463         A: ~const Allocator + ~const Destruct,
464     {
465         let layout = Layout::new::<mem::MaybeUninit<T>>();
466         let ptr = alloc.allocate(layout)?.cast();
467         unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
468     }
469
470     /// Constructs a new `Box` with uninitialized contents, with the memory
471     /// being filled with `0` bytes in the provided allocator.
472     ///
473     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
474     /// of this method.
475     ///
476     /// # Examples
477     ///
478     /// ```
479     /// #![feature(allocator_api, new_uninit)]
480     ///
481     /// use std::alloc::System;
482     ///
483     /// let zero = Box::<u32, _>::new_zeroed_in(System);
484     /// let zero = unsafe { zero.assume_init() };
485     ///
486     /// assert_eq!(*zero, 0)
487     /// ```
488     ///
489     /// [zeroed]: mem::MaybeUninit::zeroed
490     #[unstable(feature = "allocator_api", issue = "32838")]
491     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
492     #[cfg(not(no_global_oom_handling))]
493     // #[unstable(feature = "new_uninit", issue = "63291")]
494     #[must_use]
495     pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
496     where
497         A: ~const Allocator + ~const Destruct,
498     {
499         let layout = Layout::new::<mem::MaybeUninit<T>>();
500         // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
501         // That would make code size bigger.
502         match Box::try_new_zeroed_in(alloc) {
503             Ok(m) => m,
504             Err(_) => handle_alloc_error(layout),
505         }
506     }
507
508     /// Constructs a new `Box` with uninitialized contents, with the memory
509     /// being filled with `0` bytes in the provided allocator,
510     /// returning an error if the allocation fails,
511     ///
512     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
513     /// of this method.
514     ///
515     /// # Examples
516     ///
517     /// ```
518     /// #![feature(allocator_api, new_uninit)]
519     ///
520     /// use std::alloc::System;
521     ///
522     /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
523     /// let zero = unsafe { zero.assume_init() };
524     ///
525     /// assert_eq!(*zero, 0);
526     /// # Ok::<(), std::alloc::AllocError>(())
527     /// ```
528     ///
529     /// [zeroed]: mem::MaybeUninit::zeroed
530     #[unstable(feature = "allocator_api", issue = "32838")]
531     // #[unstable(feature = "new_uninit", issue = "63291")]
532     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
533     pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
534     where
535         A: ~const Allocator + ~const Destruct,
536     {
537         let layout = Layout::new::<mem::MaybeUninit<T>>();
538         let ptr = alloc.allocate_zeroed(layout)?.cast();
539         unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
540     }
541
542     /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
543     /// `x` will be pinned in memory and unable to be moved.
544     #[cfg(not(no_global_oom_handling))]
545     #[unstable(feature = "allocator_api", issue = "32838")]
546     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
547     #[must_use]
548     #[inline(always)]
549     pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
550     where
551         A: 'static + ~const Allocator + ~const Destruct,
552     {
553         Self::into_pin(Self::new_in(x, alloc))
554     }
555
556     /// Converts a `Box<T>` into a `Box<[T]>`
557     ///
558     /// This conversion does not allocate on the heap and happens in place.
559     #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
560     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
561     pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
562         let (raw, alloc) = Box::into_raw_with_allocator(boxed);
563         unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
564     }
565
566     /// Consumes the `Box`, returning the wrapped value.
567     ///
568     /// # Examples
569     ///
570     /// ```
571     /// #![feature(box_into_inner)]
572     ///
573     /// let c = Box::new(5);
574     ///
575     /// assert_eq!(Box::into_inner(c), 5);
576     /// ```
577     #[unstable(feature = "box_into_inner", issue = "80437")]
578     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
579     #[inline]
580     pub const fn into_inner(boxed: Self) -> T
581     where
582         Self: ~const Destruct,
583     {
584         *boxed
585     }
586 }
587
588 impl<T> Box<[T]> {
589     /// Constructs a new boxed slice with uninitialized contents.
590     ///
591     /// # Examples
592     ///
593     /// ```
594     /// #![feature(new_uninit)]
595     ///
596     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
597     ///
598     /// let values = unsafe {
599     ///     // Deferred initialization:
600     ///     values[0].as_mut_ptr().write(1);
601     ///     values[1].as_mut_ptr().write(2);
602     ///     values[2].as_mut_ptr().write(3);
603     ///
604     ///     values.assume_init()
605     /// };
606     ///
607     /// assert_eq!(*values, [1, 2, 3])
608     /// ```
609     #[cfg(not(no_global_oom_handling))]
610     #[unstable(feature = "new_uninit", issue = "63291")]
611     #[must_use]
612     pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
613         unsafe { RawVec::with_capacity(len).into_box(len) }
614     }
615
616     /// Constructs a new boxed slice with uninitialized contents, with the memory
617     /// being filled with `0` bytes.
618     ///
619     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
620     /// of this method.
621     ///
622     /// # Examples
623     ///
624     /// ```
625     /// #![feature(new_uninit)]
626     ///
627     /// let values = Box::<[u32]>::new_zeroed_slice(3);
628     /// let values = unsafe { values.assume_init() };
629     ///
630     /// assert_eq!(*values, [0, 0, 0])
631     /// ```
632     ///
633     /// [zeroed]: mem::MaybeUninit::zeroed
634     #[cfg(not(no_global_oom_handling))]
635     #[unstable(feature = "new_uninit", issue = "63291")]
636     #[must_use]
637     pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
638         unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
639     }
640
641     /// Constructs a new boxed slice with uninitialized contents. Returns an error if
642     /// the allocation fails
643     ///
644     /// # Examples
645     ///
646     /// ```
647     /// #![feature(allocator_api, new_uninit)]
648     ///
649     /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
650     /// let values = unsafe {
651     ///     // Deferred initialization:
652     ///     values[0].as_mut_ptr().write(1);
653     ///     values[1].as_mut_ptr().write(2);
654     ///     values[2].as_mut_ptr().write(3);
655     ///     values.assume_init()
656     /// };
657     ///
658     /// assert_eq!(*values, [1, 2, 3]);
659     /// # Ok::<(), std::alloc::AllocError>(())
660     /// ```
661     #[unstable(feature = "allocator_api", issue = "32838")]
662     #[inline]
663     pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
664         unsafe {
665             let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
666                 Ok(l) => l,
667                 Err(_) => return Err(AllocError),
668             };
669             let ptr = Global.allocate(layout)?;
670             Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
671         }
672     }
673
674     /// Constructs a new boxed slice with uninitialized contents, with the memory
675     /// being filled with `0` bytes. Returns an error if the allocation fails
676     ///
677     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
678     /// of this method.
679     ///
680     /// # Examples
681     ///
682     /// ```
683     /// #![feature(allocator_api, new_uninit)]
684     ///
685     /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
686     /// let values = unsafe { values.assume_init() };
687     ///
688     /// assert_eq!(*values, [0, 0, 0]);
689     /// # Ok::<(), std::alloc::AllocError>(())
690     /// ```
691     ///
692     /// [zeroed]: mem::MaybeUninit::zeroed
693     #[unstable(feature = "allocator_api", issue = "32838")]
694     #[inline]
695     pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
696         unsafe {
697             let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
698                 Ok(l) => l,
699                 Err(_) => return Err(AllocError),
700             };
701             let ptr = Global.allocate_zeroed(layout)?;
702             Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
703         }
704     }
705 }
706
707 impl<T, A: Allocator> Box<[T], A> {
708     /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
709     ///
710     /// # Examples
711     ///
712     /// ```
713     /// #![feature(allocator_api, new_uninit)]
714     ///
715     /// use std::alloc::System;
716     ///
717     /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
718     ///
719     /// let values = unsafe {
720     ///     // Deferred initialization:
721     ///     values[0].as_mut_ptr().write(1);
722     ///     values[1].as_mut_ptr().write(2);
723     ///     values[2].as_mut_ptr().write(3);
724     ///
725     ///     values.assume_init()
726     /// };
727     ///
728     /// assert_eq!(*values, [1, 2, 3])
729     /// ```
730     #[cfg(not(no_global_oom_handling))]
731     #[unstable(feature = "allocator_api", issue = "32838")]
732     // #[unstable(feature = "new_uninit", issue = "63291")]
733     #[must_use]
734     pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
735         unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
736     }
737
738     /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
739     /// with the memory being filled with `0` bytes.
740     ///
741     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
742     /// of this method.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// #![feature(allocator_api, new_uninit)]
748     ///
749     /// use std::alloc::System;
750     ///
751     /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
752     /// let values = unsafe { values.assume_init() };
753     ///
754     /// assert_eq!(*values, [0, 0, 0])
755     /// ```
756     ///
757     /// [zeroed]: mem::MaybeUninit::zeroed
758     #[cfg(not(no_global_oom_handling))]
759     #[unstable(feature = "allocator_api", issue = "32838")]
760     // #[unstable(feature = "new_uninit", issue = "63291")]
761     #[must_use]
762     pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
763         unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
764     }
765 }
766
767 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
768     /// Converts to `Box<T, A>`.
769     ///
770     /// # Safety
771     ///
772     /// As with [`MaybeUninit::assume_init`],
773     /// it is up to the caller to guarantee that the value
774     /// really is in an initialized state.
775     /// Calling this when the content is not yet fully initialized
776     /// causes immediate undefined behavior.
777     ///
778     /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
779     ///
780     /// # Examples
781     ///
782     /// ```
783     /// #![feature(new_uninit)]
784     ///
785     /// let mut five = Box::<u32>::new_uninit();
786     ///
787     /// let five: Box<u32> = unsafe {
788     ///     // Deferred initialization:
789     ///     five.as_mut_ptr().write(5);
790     ///
791     ///     five.assume_init()
792     /// };
793     ///
794     /// assert_eq!(*five, 5)
795     /// ```
796     #[unstable(feature = "new_uninit", issue = "63291")]
797     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
798     #[inline]
799     pub const unsafe fn assume_init(self) -> Box<T, A> {
800         let (raw, alloc) = Box::into_raw_with_allocator(self);
801         unsafe { Box::from_raw_in(raw as *mut T, alloc) }
802     }
803
804     /// Writes the value and converts to `Box<T, A>`.
805     ///
806     /// This method converts the box similarly to [`Box::assume_init`] but
807     /// writes `value` into it before conversion thus guaranteeing safety.
808     /// In some scenarios use of this method may improve performance because
809     /// the compiler may be able to optimize copying from stack.
810     ///
811     /// # Examples
812     ///
813     /// ```
814     /// #![feature(new_uninit)]
815     ///
816     /// let big_box = Box::<[usize; 1024]>::new_uninit();
817     ///
818     /// let mut array = [0; 1024];
819     /// for (i, place) in array.iter_mut().enumerate() {
820     ///     *place = i;
821     /// }
822     ///
823     /// // The optimizer may be able to elide this copy, so previous code writes
824     /// // to heap directly.
825     /// let big_box = Box::write(big_box, array);
826     ///
827     /// for (i, x) in big_box.iter().enumerate() {
828     ///     assert_eq!(*x, i);
829     /// }
830     /// ```
831     #[unstable(feature = "new_uninit", issue = "63291")]
832     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
833     #[inline]
834     pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
835         unsafe {
836             (*boxed).write(value);
837             boxed.assume_init()
838         }
839     }
840 }
841
842 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
843     /// Converts to `Box<[T], A>`.
844     ///
845     /// # Safety
846     ///
847     /// As with [`MaybeUninit::assume_init`],
848     /// it is up to the caller to guarantee that the values
849     /// really are in an initialized state.
850     /// Calling this when the content is not yet fully initialized
851     /// causes immediate undefined behavior.
852     ///
853     /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
854     ///
855     /// # Examples
856     ///
857     /// ```
858     /// #![feature(new_uninit)]
859     ///
860     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
861     ///
862     /// let values = unsafe {
863     ///     // Deferred initialization:
864     ///     values[0].as_mut_ptr().write(1);
865     ///     values[1].as_mut_ptr().write(2);
866     ///     values[2].as_mut_ptr().write(3);
867     ///
868     ///     values.assume_init()
869     /// };
870     ///
871     /// assert_eq!(*values, [1, 2, 3])
872     /// ```
873     #[unstable(feature = "new_uninit", issue = "63291")]
874     #[inline]
875     pub unsafe fn assume_init(self) -> Box<[T], A> {
876         let (raw, alloc) = Box::into_raw_with_allocator(self);
877         unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
878     }
879 }
880
881 impl<T: ?Sized> Box<T> {
882     /// Constructs a box from a raw pointer.
883     ///
884     /// After calling this function, the raw pointer is owned by the
885     /// resulting `Box`. Specifically, the `Box` destructor will call
886     /// the destructor of `T` and free the allocated memory. For this
887     /// to be safe, the memory must have been allocated in accordance
888     /// with the [memory layout] used by `Box` .
889     ///
890     /// # Safety
891     ///
892     /// This function is unsafe because improper use may lead to
893     /// memory problems. For example, a double-free may occur if the
894     /// function is called twice on the same raw pointer.
895     ///
896     /// The safety conditions are described in the [memory layout] section.
897     ///
898     /// # Examples
899     ///
900     /// Recreate a `Box` which was previously converted to a raw pointer
901     /// using [`Box::into_raw`]:
902     /// ```
903     /// let x = Box::new(5);
904     /// let ptr = Box::into_raw(x);
905     /// let x = unsafe { Box::from_raw(ptr) };
906     /// ```
907     /// Manually create a `Box` from scratch by using the global allocator:
908     /// ```
909     /// use std::alloc::{alloc, Layout};
910     ///
911     /// unsafe {
912     ///     let ptr = alloc(Layout::new::<i32>()) as *mut i32;
913     ///     // In general .write is required to avoid attempting to destruct
914     ///     // the (uninitialized) previous contents of `ptr`, though for this
915     ///     // simple example `*ptr = 5` would have worked as well.
916     ///     ptr.write(5);
917     ///     let x = Box::from_raw(ptr);
918     /// }
919     /// ```
920     ///
921     /// [memory layout]: self#memory-layout
922     /// [`Layout`]: crate::Layout
923     #[stable(feature = "box_raw", since = "1.4.0")]
924     #[inline]
925     pub unsafe fn from_raw(raw: *mut T) -> Self {
926         unsafe { Self::from_raw_in(raw, Global) }
927     }
928 }
929
930 impl<T: ?Sized, A: Allocator> Box<T, A> {
931     /// Constructs a box from a raw pointer in the given allocator.
932     ///
933     /// After calling this function, the raw pointer is owned by the
934     /// resulting `Box`. Specifically, the `Box` destructor will call
935     /// the destructor of `T` and free the allocated memory. For this
936     /// to be safe, the memory must have been allocated in accordance
937     /// with the [memory layout] used by `Box` .
938     ///
939     /// # Safety
940     ///
941     /// This function is unsafe because improper use may lead to
942     /// memory problems. For example, a double-free may occur if the
943     /// function is called twice on the same raw pointer.
944     ///
945     ///
946     /// # Examples
947     ///
948     /// Recreate a `Box` which was previously converted to a raw pointer
949     /// using [`Box::into_raw_with_allocator`]:
950     /// ```
951     /// #![feature(allocator_api)]
952     ///
953     /// use std::alloc::System;
954     ///
955     /// let x = Box::new_in(5, System);
956     /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
957     /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
958     /// ```
959     /// Manually create a `Box` from scratch by using the system allocator:
960     /// ```
961     /// #![feature(allocator_api, slice_ptr_get)]
962     ///
963     /// use std::alloc::{Allocator, Layout, System};
964     ///
965     /// unsafe {
966     ///     let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
967     ///     // In general .write is required to avoid attempting to destruct
968     ///     // the (uninitialized) previous contents of `ptr`, though for this
969     ///     // simple example `*ptr = 5` would have worked as well.
970     ///     ptr.write(5);
971     ///     let x = Box::from_raw_in(ptr, System);
972     /// }
973     /// # Ok::<(), std::alloc::AllocError>(())
974     /// ```
975     ///
976     /// [memory layout]: self#memory-layout
977     /// [`Layout`]: crate::Layout
978     #[unstable(feature = "allocator_api", issue = "32838")]
979     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
980     #[inline]
981     pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
982         Box(unsafe { Unique::new_unchecked(raw) }, alloc)
983     }
984
985     /// Consumes the `Box`, returning a wrapped raw pointer.
986     ///
987     /// The pointer will be properly aligned and non-null.
988     ///
989     /// After calling this function, the caller is responsible for the
990     /// memory previously managed by the `Box`. In particular, the
991     /// caller should properly destroy `T` and release the memory, taking
992     /// into account the [memory layout] used by `Box`. The easiest way to
993     /// do this is to convert the raw pointer back into a `Box` with the
994     /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
995     /// the cleanup.
996     ///
997     /// Note: this is an associated function, which means that you have
998     /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
999     /// is so that there is no conflict with a method on the inner type.
1000     ///
1001     /// # Examples
1002     /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1003     /// for automatic cleanup:
1004     /// ```
1005     /// let x = Box::new(String::from("Hello"));
1006     /// let ptr = Box::into_raw(x);
1007     /// let x = unsafe { Box::from_raw(ptr) };
1008     /// ```
1009     /// Manual cleanup by explicitly running the destructor and deallocating
1010     /// the memory:
1011     /// ```
1012     /// use std::alloc::{dealloc, Layout};
1013     /// use std::ptr;
1014     ///
1015     /// let x = Box::new(String::from("Hello"));
1016     /// let p = Box::into_raw(x);
1017     /// unsafe {
1018     ///     ptr::drop_in_place(p);
1019     ///     dealloc(p as *mut u8, Layout::new::<String>());
1020     /// }
1021     /// ```
1022     ///
1023     /// [memory layout]: self#memory-layout
1024     #[stable(feature = "box_raw", since = "1.4.0")]
1025     #[inline]
1026     pub fn into_raw(b: Self) -> *mut T {
1027         Self::into_raw_with_allocator(b).0
1028     }
1029
1030     /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1031     ///
1032     /// The pointer will be properly aligned and non-null.
1033     ///
1034     /// After calling this function, the caller is responsible for the
1035     /// memory previously managed by the `Box`. In particular, the
1036     /// caller should properly destroy `T` and release the memory, taking
1037     /// into account the [memory layout] used by `Box`. The easiest way to
1038     /// do this is to convert the raw pointer back into a `Box` with the
1039     /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1040     /// the cleanup.
1041     ///
1042     /// Note: this is an associated function, which means that you have
1043     /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1044     /// is so that there is no conflict with a method on the inner type.
1045     ///
1046     /// # Examples
1047     /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1048     /// for automatic cleanup:
1049     /// ```
1050     /// #![feature(allocator_api)]
1051     ///
1052     /// use std::alloc::System;
1053     ///
1054     /// let x = Box::new_in(String::from("Hello"), System);
1055     /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1056     /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1057     /// ```
1058     /// Manual cleanup by explicitly running the destructor and deallocating
1059     /// the memory:
1060     /// ```
1061     /// #![feature(allocator_api)]
1062     ///
1063     /// use std::alloc::{Allocator, Layout, System};
1064     /// use std::ptr::{self, NonNull};
1065     ///
1066     /// let x = Box::new_in(String::from("Hello"), System);
1067     /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1068     /// unsafe {
1069     ///     ptr::drop_in_place(ptr);
1070     ///     let non_null = NonNull::new_unchecked(ptr);
1071     ///     alloc.deallocate(non_null.cast(), Layout::new::<String>());
1072     /// }
1073     /// ```
1074     ///
1075     /// [memory layout]: self#memory-layout
1076     #[unstable(feature = "allocator_api", issue = "32838")]
1077     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1078     #[inline]
1079     pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1080         let (leaked, alloc) = Box::into_unique(b);
1081         (leaked.as_ptr(), alloc)
1082     }
1083
1084     #[unstable(
1085         feature = "ptr_internals",
1086         issue = "none",
1087         reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1088     )]
1089     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1090     #[inline]
1091     #[doc(hidden)]
1092     pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1093         // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1094         // raw pointer for the type system. Turning it directly into a raw pointer would not be
1095         // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1096         // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1097         // behaves correctly.
1098         let alloc = unsafe { ptr::read(&b.1) };
1099         (Unique::from(Box::leak(b)), alloc)
1100     }
1101
1102     /// Returns a reference to the underlying allocator.
1103     ///
1104     /// Note: this is an associated function, which means that you have
1105     /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1106     /// is so that there is no conflict with a method on the inner type.
1107     #[unstable(feature = "allocator_api", issue = "32838")]
1108     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1109     #[inline]
1110     pub const fn allocator(b: &Self) -> &A {
1111         &b.1
1112     }
1113
1114     /// Consumes and leaks the `Box`, returning a mutable reference,
1115     /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1116     /// `'a`. If the type has only static references, or none at all, then this
1117     /// may be chosen to be `'static`.
1118     ///
1119     /// This function is mainly useful for data that lives for the remainder of
1120     /// the program's life. Dropping the returned reference will cause a memory
1121     /// leak. If this is not acceptable, the reference should first be wrapped
1122     /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1123     /// then be dropped which will properly destroy `T` and release the
1124     /// allocated memory.
1125     ///
1126     /// Note: this is an associated function, which means that you have
1127     /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1128     /// is so that there is no conflict with a method on the inner type.
1129     ///
1130     /// # Examples
1131     ///
1132     /// Simple usage:
1133     ///
1134     /// ```
1135     /// let x = Box::new(41);
1136     /// let static_ref: &'static mut usize = Box::leak(x);
1137     /// *static_ref += 1;
1138     /// assert_eq!(*static_ref, 42);
1139     /// ```
1140     ///
1141     /// Unsized data:
1142     ///
1143     /// ```
1144     /// let x = vec![1, 2, 3].into_boxed_slice();
1145     /// let static_ref = Box::leak(x);
1146     /// static_ref[0] = 4;
1147     /// assert_eq!(*static_ref, [4, 2, 3]);
1148     /// ```
1149     #[stable(feature = "box_leak", since = "1.26.0")]
1150     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1151     #[inline]
1152     pub const fn leak<'a>(b: Self) -> &'a mut T
1153     where
1154         A: 'a,
1155     {
1156         unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1157     }
1158
1159     /// Converts a `Box<T>` into a `Pin<Box<T>>`
1160     ///
1161     /// This conversion does not allocate on the heap and happens in place.
1162     ///
1163     /// This is also available via [`From`].
1164     #[unstable(feature = "box_into_pin", issue = "62370")]
1165     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1166     pub const fn into_pin(boxed: Self) -> Pin<Self>
1167     where
1168         A: 'static,
1169     {
1170         // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1171         // when `T: !Unpin`,  so it's safe to pin it directly without any
1172         // additional requirements.
1173         unsafe { Pin::new_unchecked(boxed) }
1174     }
1175 }
1176
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1179     fn drop(&mut self) {
1180         // FIXME: Do nothing, drop is currently performed by compiler.
1181     }
1182 }
1183
1184 #[cfg(not(no_global_oom_handling))]
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<T: Default> Default for Box<T> {
1187     /// Creates a `Box<T>`, with the `Default` value for T.
1188     fn default() -> Self {
1189         box T::default()
1190     }
1191 }
1192
1193 #[cfg(not(no_global_oom_handling))]
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1196 impl<T> const Default for Box<[T]> {
1197     fn default() -> Self {
1198         let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1199         Box(ptr, Global)
1200     }
1201 }
1202
1203 #[cfg(not(no_global_oom_handling))]
1204 #[stable(feature = "default_box_extra", since = "1.17.0")]
1205 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1206 impl const Default for Box<str> {
1207     fn default() -> Self {
1208         // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1209         let ptr: Unique<str> = unsafe {
1210             let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1211             Unique::new_unchecked(bytes.as_ptr() as *mut str)
1212         };
1213         Box(ptr, Global)
1214     }
1215 }
1216
1217 #[cfg(not(no_global_oom_handling))]
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1220     /// Returns a new box with a `clone()` of this box's contents.
1221     ///
1222     /// # Examples
1223     ///
1224     /// ```
1225     /// let x = Box::new(5);
1226     /// let y = x.clone();
1227     ///
1228     /// // The value is the same
1229     /// assert_eq!(x, y);
1230     ///
1231     /// // But they are unique objects
1232     /// assert_ne!(&*x as *const i32, &*y as *const i32);
1233     /// ```
1234     #[inline]
1235     fn clone(&self) -> Self {
1236         // Pre-allocate memory to allow writing the cloned value directly.
1237         let mut boxed = Self::new_uninit_in(self.1.clone());
1238         unsafe {
1239             (**self).write_clone_into_raw(boxed.as_mut_ptr());
1240             boxed.assume_init()
1241         }
1242     }
1243
1244     /// Copies `source`'s contents into `self` without creating a new allocation.
1245     ///
1246     /// # Examples
1247     ///
1248     /// ```
1249     /// let x = Box::new(5);
1250     /// let mut y = Box::new(10);
1251     /// let yp: *const i32 = &*y;
1252     ///
1253     /// y.clone_from(&x);
1254     ///
1255     /// // The value is the same
1256     /// assert_eq!(x, y);
1257     ///
1258     /// // And no allocation occurred
1259     /// assert_eq!(yp, &*y);
1260     /// ```
1261     #[inline]
1262     fn clone_from(&mut self, source: &Self) {
1263         (**self).clone_from(&(**source));
1264     }
1265 }
1266
1267 #[cfg(not(no_global_oom_handling))]
1268 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1269 impl Clone for Box<str> {
1270     fn clone(&self) -> Self {
1271         // this makes a copy of the data
1272         let buf: Box<[u8]> = self.as_bytes().into();
1273         unsafe { from_boxed_utf8_unchecked(buf) }
1274     }
1275 }
1276
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1279     #[inline]
1280     fn eq(&self, other: &Self) -> bool {
1281         PartialEq::eq(&**self, &**other)
1282     }
1283     #[inline]
1284     fn ne(&self, other: &Self) -> bool {
1285         PartialEq::ne(&**self, &**other)
1286     }
1287 }
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1290     #[inline]
1291     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1292         PartialOrd::partial_cmp(&**self, &**other)
1293     }
1294     #[inline]
1295     fn lt(&self, other: &Self) -> bool {
1296         PartialOrd::lt(&**self, &**other)
1297     }
1298     #[inline]
1299     fn le(&self, other: &Self) -> bool {
1300         PartialOrd::le(&**self, &**other)
1301     }
1302     #[inline]
1303     fn ge(&self, other: &Self) -> bool {
1304         PartialOrd::ge(&**self, &**other)
1305     }
1306     #[inline]
1307     fn gt(&self, other: &Self) -> bool {
1308         PartialOrd::gt(&**self, &**other)
1309     }
1310 }
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1313     #[inline]
1314     fn cmp(&self, other: &Self) -> Ordering {
1315         Ord::cmp(&**self, &**other)
1316     }
1317 }
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1320
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1323     fn hash<H: Hasher>(&self, state: &mut H) {
1324         (**self).hash(state);
1325     }
1326 }
1327
1328 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1329 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1330     fn finish(&self) -> u64 {
1331         (**self).finish()
1332     }
1333     fn write(&mut self, bytes: &[u8]) {
1334         (**self).write(bytes)
1335     }
1336     fn write_u8(&mut self, i: u8) {
1337         (**self).write_u8(i)
1338     }
1339     fn write_u16(&mut self, i: u16) {
1340         (**self).write_u16(i)
1341     }
1342     fn write_u32(&mut self, i: u32) {
1343         (**self).write_u32(i)
1344     }
1345     fn write_u64(&mut self, i: u64) {
1346         (**self).write_u64(i)
1347     }
1348     fn write_u128(&mut self, i: u128) {
1349         (**self).write_u128(i)
1350     }
1351     fn write_usize(&mut self, i: usize) {
1352         (**self).write_usize(i)
1353     }
1354     fn write_i8(&mut self, i: i8) {
1355         (**self).write_i8(i)
1356     }
1357     fn write_i16(&mut self, i: i16) {
1358         (**self).write_i16(i)
1359     }
1360     fn write_i32(&mut self, i: i32) {
1361         (**self).write_i32(i)
1362     }
1363     fn write_i64(&mut self, i: i64) {
1364         (**self).write_i64(i)
1365     }
1366     fn write_i128(&mut self, i: i128) {
1367         (**self).write_i128(i)
1368     }
1369     fn write_isize(&mut self, i: isize) {
1370         (**self).write_isize(i)
1371     }
1372 }
1373
1374 #[cfg(not(no_global_oom_handling))]
1375 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1376 impl<T> From<T> for Box<T> {
1377     /// Converts a `T` into a `Box<T>`
1378     ///
1379     /// The conversion allocates on the heap and moves `t`
1380     /// from the stack into it.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```rust
1385     /// let x = 5;
1386     /// let boxed = Box::new(5);
1387     ///
1388     /// assert_eq!(Box::from(x), boxed);
1389     /// ```
1390     fn from(t: T) -> Self {
1391         Box::new(t)
1392     }
1393 }
1394
1395 #[stable(feature = "pin", since = "1.33.0")]
1396 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1397 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1398 where
1399     A: 'static,
1400 {
1401     /// Converts a `Box<T>` into a `Pin<Box<T>>`
1402     ///
1403     /// This conversion does not allocate on the heap and happens in place.
1404     fn from(boxed: Box<T, A>) -> Self {
1405         Box::into_pin(boxed)
1406     }
1407 }
1408
1409 #[cfg(not(no_global_oom_handling))]
1410 #[stable(feature = "box_from_slice", since = "1.17.0")]
1411 impl<T: Copy> From<&[T]> for Box<[T]> {
1412     /// Converts a `&[T]` into a `Box<[T]>`
1413     ///
1414     /// This conversion allocates on the heap
1415     /// and performs a copy of `slice`.
1416     ///
1417     /// # Examples
1418     /// ```rust
1419     /// // create a &[u8] which will be used to create a Box<[u8]>
1420     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1421     /// let boxed_slice: Box<[u8]> = Box::from(slice);
1422     ///
1423     /// println!("{boxed_slice:?}");
1424     /// ```
1425     fn from(slice: &[T]) -> Box<[T]> {
1426         let len = slice.len();
1427         let buf = RawVec::with_capacity(len);
1428         unsafe {
1429             ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1430             buf.into_box(slice.len()).assume_init()
1431         }
1432     }
1433 }
1434
1435 #[cfg(not(no_global_oom_handling))]
1436 #[stable(feature = "box_from_cow", since = "1.45.0")]
1437 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1438     /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1439     ///
1440     /// When `cow` is the `Cow::Borrowed` variant, this
1441     /// conversion allocates on the heap and copies the
1442     /// underlying slice. Otherwise, it will try to reuse the owned
1443     /// `Vec`'s allocation.
1444     #[inline]
1445     fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1446         match cow {
1447             Cow::Borrowed(slice) => Box::from(slice),
1448             Cow::Owned(slice) => Box::from(slice),
1449         }
1450     }
1451 }
1452
1453 #[cfg(not(no_global_oom_handling))]
1454 #[stable(feature = "box_from_slice", since = "1.17.0")]
1455 impl From<&str> for Box<str> {
1456     /// Converts a `&str` into a `Box<str>`
1457     ///
1458     /// This conversion allocates on the heap
1459     /// and performs a copy of `s`.
1460     ///
1461     /// # Examples
1462     ///
1463     /// ```rust
1464     /// let boxed: Box<str> = Box::from("hello");
1465     /// println!("{boxed}");
1466     /// ```
1467     #[inline]
1468     fn from(s: &str) -> Box<str> {
1469         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1470     }
1471 }
1472
1473 #[cfg(not(no_global_oom_handling))]
1474 #[stable(feature = "box_from_cow", since = "1.45.0")]
1475 impl From<Cow<'_, str>> for Box<str> {
1476     /// Converts a `Cow<'_, str>` into a `Box<str>`
1477     ///
1478     /// When `cow` is the `Cow::Borrowed` variant, this
1479     /// conversion allocates on the heap and copies the
1480     /// underlying `str`. Otherwise, it will try to reuse the owned
1481     /// `String`'s allocation.
1482     ///
1483     /// # Examples
1484     ///
1485     /// ```rust
1486     /// use std::borrow::Cow;
1487     ///
1488     /// let unboxed = Cow::Borrowed("hello");
1489     /// let boxed: Box<str> = Box::from(unboxed);
1490     /// println!("{boxed}");
1491     /// ```
1492     ///
1493     /// ```rust
1494     /// # use std::borrow::Cow;
1495     /// let unboxed = Cow::Owned("hello".to_string());
1496     /// let boxed: Box<str> = Box::from(unboxed);
1497     /// println!("{boxed}");
1498     /// ```
1499     #[inline]
1500     fn from(cow: Cow<'_, str>) -> Box<str> {
1501         match cow {
1502             Cow::Borrowed(s) => Box::from(s),
1503             Cow::Owned(s) => Box::from(s),
1504         }
1505     }
1506 }
1507
1508 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1509 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1510     /// Converts a `Box<str>` into a `Box<[u8]>`
1511     ///
1512     /// This conversion does not allocate on the heap and happens in place.
1513     ///
1514     /// # Examples
1515     /// ```rust
1516     /// // create a Box<str> which will be used to create a Box<[u8]>
1517     /// let boxed: Box<str> = Box::from("hello");
1518     /// let boxed_str: Box<[u8]> = Box::from(boxed);
1519     ///
1520     /// // create a &[u8] which will be used to create a Box<[u8]>
1521     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1522     /// let boxed_slice = Box::from(slice);
1523     ///
1524     /// assert_eq!(boxed_slice, boxed_str);
1525     /// ```
1526     #[inline]
1527     fn from(s: Box<str, A>) -> Self {
1528         let (raw, alloc) = Box::into_raw_with_allocator(s);
1529         unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1530     }
1531 }
1532
1533 #[cfg(not(no_global_oom_handling))]
1534 #[stable(feature = "box_from_array", since = "1.45.0")]
1535 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1536     /// Converts a `[T; N]` into a `Box<[T]>`
1537     ///
1538     /// This conversion moves the array to newly heap-allocated memory.
1539     ///
1540     /// # Examples
1541     ///
1542     /// ```rust
1543     /// let boxed: Box<[u8]> = Box::from([4, 2]);
1544     /// println!("{boxed:?}");
1545     /// ```
1546     fn from(array: [T; N]) -> Box<[T]> {
1547         box array
1548     }
1549 }
1550
1551 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1552 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1553     type Error = Box<[T]>;
1554
1555     /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1556     ///
1557     /// The conversion occurs in-place and does not require a
1558     /// new memory allocation.
1559     ///
1560     /// # Errors
1561     ///
1562     /// Returns the old `Box<[T]>` in the `Err` variant if
1563     /// `boxed_slice.len()` does not equal `N`.
1564     fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1565         if boxed_slice.len() == N {
1566             Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1567         } else {
1568             Err(boxed_slice)
1569         }
1570     }
1571 }
1572
1573 impl<A: Allocator> Box<dyn Any, A> {
1574     /// Attempt to downcast the box to a concrete type.
1575     ///
1576     /// # Examples
1577     ///
1578     /// ```
1579     /// use std::any::Any;
1580     ///
1581     /// fn print_if_string(value: Box<dyn Any>) {
1582     ///     if let Ok(string) = value.downcast::<String>() {
1583     ///         println!("String ({}): {}", string.len(), string);
1584     ///     }
1585     /// }
1586     ///
1587     /// let my_string = "Hello World".to_string();
1588     /// print_if_string(Box::new(my_string));
1589     /// print_if_string(Box::new(0i8));
1590     /// ```
1591     #[inline]
1592     #[stable(feature = "rust1", since = "1.0.0")]
1593     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1594         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1595     }
1596
1597     /// Downcasts the box to a concrete type.
1598     ///
1599     /// For a safe alternative see [`downcast`].
1600     ///
1601     /// # Examples
1602     ///
1603     /// ```
1604     /// #![feature(downcast_unchecked)]
1605     ///
1606     /// use std::any::Any;
1607     ///
1608     /// let x: Box<dyn Any> = Box::new(1_usize);
1609     ///
1610     /// unsafe {
1611     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1612     /// }
1613     /// ```
1614     ///
1615     /// # Safety
1616     ///
1617     /// The contained value must be of type `T`. Calling this method
1618     /// with the incorrect type is *undefined behavior*.
1619     ///
1620     /// [`downcast`]: Self::downcast
1621     #[inline]
1622     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1623     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1624         debug_assert!(self.is::<T>());
1625         unsafe {
1626             let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1627             Box::from_raw_in(raw as *mut T, alloc)
1628         }
1629     }
1630 }
1631
1632 impl<A: Allocator> Box<dyn Any + Send, A> {
1633     /// Attempt to downcast the box to a concrete type.
1634     ///
1635     /// # Examples
1636     ///
1637     /// ```
1638     /// use std::any::Any;
1639     ///
1640     /// fn print_if_string(value: Box<dyn Any + Send>) {
1641     ///     if let Ok(string) = value.downcast::<String>() {
1642     ///         println!("String ({}): {}", string.len(), string);
1643     ///     }
1644     /// }
1645     ///
1646     /// let my_string = "Hello World".to_string();
1647     /// print_if_string(Box::new(my_string));
1648     /// print_if_string(Box::new(0i8));
1649     /// ```
1650     #[inline]
1651     #[stable(feature = "rust1", since = "1.0.0")]
1652     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1653         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1654     }
1655
1656     /// Downcasts the box to a concrete type.
1657     ///
1658     /// For a safe alternative see [`downcast`].
1659     ///
1660     /// # Examples
1661     ///
1662     /// ```
1663     /// #![feature(downcast_unchecked)]
1664     ///
1665     /// use std::any::Any;
1666     ///
1667     /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1668     ///
1669     /// unsafe {
1670     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1671     /// }
1672     /// ```
1673     ///
1674     /// # Safety
1675     ///
1676     /// The contained value must be of type `T`. Calling this method
1677     /// with the incorrect type is *undefined behavior*.
1678     ///
1679     /// [`downcast`]: Self::downcast
1680     #[inline]
1681     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1682     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1683         debug_assert!(self.is::<T>());
1684         unsafe {
1685             let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1686             Box::from_raw_in(raw as *mut T, alloc)
1687         }
1688     }
1689 }
1690
1691 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1692     /// Attempt to downcast the box to a concrete type.
1693     ///
1694     /// # Examples
1695     ///
1696     /// ```
1697     /// use std::any::Any;
1698     ///
1699     /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1700     ///     if let Ok(string) = value.downcast::<String>() {
1701     ///         println!("String ({}): {}", string.len(), string);
1702     ///     }
1703     /// }
1704     ///
1705     /// let my_string = "Hello World".to_string();
1706     /// print_if_string(Box::new(my_string));
1707     /// print_if_string(Box::new(0i8));
1708     /// ```
1709     #[inline]
1710     #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1711     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1712         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1713     }
1714
1715     /// Downcasts the box to a concrete type.
1716     ///
1717     /// For a safe alternative see [`downcast`].
1718     ///
1719     /// # Examples
1720     ///
1721     /// ```
1722     /// #![feature(downcast_unchecked)]
1723     ///
1724     /// use std::any::Any;
1725     ///
1726     /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1727     ///
1728     /// unsafe {
1729     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1730     /// }
1731     /// ```
1732     ///
1733     /// # Safety
1734     ///
1735     /// The contained value must be of type `T`. Calling this method
1736     /// with the incorrect type is *undefined behavior*.
1737     ///
1738     /// [`downcast`]: Self::downcast
1739     #[inline]
1740     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1741     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1742         debug_assert!(self.is::<T>());
1743         unsafe {
1744             let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1745                 Box::into_raw_with_allocator(self);
1746             Box::from_raw_in(raw as *mut T, alloc)
1747         }
1748     }
1749 }
1750
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1753     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1754         fmt::Display::fmt(&**self, f)
1755     }
1756 }
1757
1758 #[stable(feature = "rust1", since = "1.0.0")]
1759 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1760     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1761         fmt::Debug::fmt(&**self, f)
1762     }
1763 }
1764
1765 #[stable(feature = "rust1", since = "1.0.0")]
1766 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1767     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1768         // It's not possible to extract the inner Uniq directly from the Box,
1769         // instead we cast it to a *const which aliases the Unique
1770         let ptr: *const T = &**self;
1771         fmt::Pointer::fmt(&ptr, f)
1772     }
1773 }
1774
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1777 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1778     type Target = T;
1779
1780     fn deref(&self) -> &T {
1781         &**self
1782     }
1783 }
1784
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1787 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1788     fn deref_mut(&mut self) -> &mut T {
1789         &mut **self
1790     }
1791 }
1792
1793 #[unstable(feature = "receiver_trait", issue = "none")]
1794 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1795
1796 #[stable(feature = "rust1", since = "1.0.0")]
1797 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1798     type Item = I::Item;
1799     fn next(&mut self) -> Option<I::Item> {
1800         (**self).next()
1801     }
1802     fn size_hint(&self) -> (usize, Option<usize>) {
1803         (**self).size_hint()
1804     }
1805     fn nth(&mut self, n: usize) -> Option<I::Item> {
1806         (**self).nth(n)
1807     }
1808     fn last(self) -> Option<I::Item> {
1809         BoxIter::last(self)
1810     }
1811 }
1812
1813 trait BoxIter {
1814     type Item;
1815     fn last(self) -> Option<Self::Item>;
1816 }
1817
1818 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1819     type Item = I::Item;
1820     default fn last(self) -> Option<I::Item> {
1821         #[inline]
1822         fn some<T>(_: Option<T>, x: T) -> Option<T> {
1823             Some(x)
1824         }
1825
1826         self.fold(None, some)
1827     }
1828 }
1829
1830 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1831 /// instead of the default.
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1834     fn last(self) -> Option<I::Item> {
1835         (*self).last()
1836     }
1837 }
1838
1839 #[stable(feature = "rust1", since = "1.0.0")]
1840 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1841     fn next_back(&mut self) -> Option<I::Item> {
1842         (**self).next_back()
1843     }
1844     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1845         (**self).nth_back(n)
1846     }
1847 }
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1850     fn len(&self) -> usize {
1851         (**self).len()
1852     }
1853     fn is_empty(&self) -> bool {
1854         (**self).is_empty()
1855     }
1856 }
1857
1858 #[stable(feature = "fused", since = "1.26.0")]
1859 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1860
1861 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1862 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1863     type Output = <F as FnOnce<Args>>::Output;
1864
1865     extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1866         <F as FnOnce<Args>>::call_once(*self, args)
1867     }
1868 }
1869
1870 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1871 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1872     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1873         <F as FnMut<Args>>::call_mut(self, args)
1874     }
1875 }
1876
1877 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1878 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1879     extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1880         <F as Fn<Args>>::call(self, args)
1881     }
1882 }
1883
1884 #[unstable(feature = "coerce_unsized", issue = "27732")]
1885 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1886
1887 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1888 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1889
1890 #[cfg(not(no_global_oom_handling))]
1891 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1892 impl<I> FromIterator<I> for Box<[I]> {
1893     fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1894         iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1895     }
1896 }
1897
1898 #[cfg(not(no_global_oom_handling))]
1899 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1900 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1901     fn clone(&self) -> Self {
1902         let alloc = Box::allocator(self).clone();
1903         self.to_vec_in(alloc).into_boxed_slice()
1904     }
1905
1906     fn clone_from(&mut self, other: &Self) {
1907         if self.len() == other.len() {
1908             self.clone_from_slice(&other);
1909         } else {
1910             *self = other.clone();
1911         }
1912     }
1913 }
1914
1915 #[stable(feature = "box_borrow", since = "1.1.0")]
1916 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1917     fn borrow(&self) -> &T {
1918         &**self
1919     }
1920 }
1921
1922 #[stable(feature = "box_borrow", since = "1.1.0")]
1923 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1924     fn borrow_mut(&mut self) -> &mut T {
1925         &mut **self
1926     }
1927 }
1928
1929 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1930 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1931     fn as_ref(&self) -> &T {
1932         &**self
1933     }
1934 }
1935
1936 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1937 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1938     fn as_mut(&mut self) -> &mut T {
1939         &mut **self
1940     }
1941 }
1942
1943 /* Nota bene
1944  *
1945  *  We could have chosen not to add this impl, and instead have written a
1946  *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1947  *  because Box<T> implements Unpin even when T does not, as a result of
1948  *  this impl.
1949  *
1950  *  We chose this API instead of the alternative for a few reasons:
1951  *      - Logically, it is helpful to understand pinning in regard to the
1952  *        memory region being pointed to. For this reason none of the
1953  *        standard library pointer types support projecting through a pin
1954  *        (Box<T> is the only pointer type in std for which this would be
1955  *        safe.)
1956  *      - It is in practice very useful to have Box<T> be unconditionally
1957  *        Unpin because of trait objects, for which the structural auto
1958  *        trait functionality does not apply (e.g., Box<dyn Foo> would
1959  *        otherwise not be Unpin).
1960  *
1961  *  Another type with the same semantics as Box but only a conditional
1962  *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1963  *  could have a method to project a Pin<T> from it.
1964  */
1965 #[stable(feature = "pin", since = "1.33.0")]
1966 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1967 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
1968
1969 #[unstable(feature = "generator_trait", issue = "43122")]
1970 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1971 where
1972     A: 'static,
1973 {
1974     type Yield = G::Yield;
1975     type Return = G::Return;
1976
1977     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1978         G::resume(Pin::new(&mut *self), arg)
1979     }
1980 }
1981
1982 #[unstable(feature = "generator_trait", issue = "43122")]
1983 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1984 where
1985     A: 'static,
1986 {
1987     type Yield = G::Yield;
1988     type Return = G::Return;
1989
1990     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1991         G::resume((*self).as_mut(), arg)
1992     }
1993 }
1994
1995 #[stable(feature = "futures_api", since = "1.36.0")]
1996 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
1997 where
1998     A: 'static,
1999 {
2000     type Output = F::Output;
2001
2002     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2003         F::poll(Pin::new(&mut *self), cx)
2004     }
2005 }
2006
2007 #[unstable(feature = "async_iterator", issue = "79024")]
2008 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2009     type Item = S::Item;
2010
2011     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2012         Pin::new(&mut **self).poll_next(cx)
2013     }
2014
2015     fn size_hint(&self) -> (usize, Option<usize>) {
2016         (**self).size_hint()
2017     }
2018 }