]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/boxed.rs
Rollup merge of #96757 - jyn514:fewer-clippy-rebuilds, 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     fn write_length_prefix(&mut self, len: usize) {
1373         (**self).write_length_prefix(len)
1374     }
1375     fn write_str(&mut self, s: &str) {
1376         (**self).write_str(s)
1377     }
1378 }
1379
1380 #[cfg(not(no_global_oom_handling))]
1381 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1382 impl<T> From<T> for Box<T> {
1383     /// Converts a `T` into a `Box<T>`
1384     ///
1385     /// The conversion allocates on the heap and moves `t`
1386     /// from the stack into it.
1387     ///
1388     /// # Examples
1389     ///
1390     /// ```rust
1391     /// let x = 5;
1392     /// let boxed = Box::new(5);
1393     ///
1394     /// assert_eq!(Box::from(x), boxed);
1395     /// ```
1396     fn from(t: T) -> Self {
1397         Box::new(t)
1398     }
1399 }
1400
1401 #[stable(feature = "pin", since = "1.33.0")]
1402 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1403 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1404 where
1405     A: 'static,
1406 {
1407     /// Converts a `Box<T>` into a `Pin<Box<T>>`
1408     ///
1409     /// This conversion does not allocate on the heap and happens in place.
1410     fn from(boxed: Box<T, A>) -> Self {
1411         Box::into_pin(boxed)
1412     }
1413 }
1414
1415 #[cfg(not(no_global_oom_handling))]
1416 #[stable(feature = "box_from_slice", since = "1.17.0")]
1417 impl<T: Copy> From<&[T]> for Box<[T]> {
1418     /// Converts a `&[T]` into a `Box<[T]>`
1419     ///
1420     /// This conversion allocates on the heap
1421     /// and performs a copy of `slice`.
1422     ///
1423     /// # Examples
1424     /// ```rust
1425     /// // create a &[u8] which will be used to create a Box<[u8]>
1426     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1427     /// let boxed_slice: Box<[u8]> = Box::from(slice);
1428     ///
1429     /// println!("{boxed_slice:?}");
1430     /// ```
1431     fn from(slice: &[T]) -> Box<[T]> {
1432         let len = slice.len();
1433         let buf = RawVec::with_capacity(len);
1434         unsafe {
1435             ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1436             buf.into_box(slice.len()).assume_init()
1437         }
1438     }
1439 }
1440
1441 #[cfg(not(no_global_oom_handling))]
1442 #[stable(feature = "box_from_cow", since = "1.45.0")]
1443 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1444     /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1445     ///
1446     /// When `cow` is the `Cow::Borrowed` variant, this
1447     /// conversion allocates on the heap and copies the
1448     /// underlying slice. Otherwise, it will try to reuse the owned
1449     /// `Vec`'s allocation.
1450     #[inline]
1451     fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1452         match cow {
1453             Cow::Borrowed(slice) => Box::from(slice),
1454             Cow::Owned(slice) => Box::from(slice),
1455         }
1456     }
1457 }
1458
1459 #[cfg(not(no_global_oom_handling))]
1460 #[stable(feature = "box_from_slice", since = "1.17.0")]
1461 impl From<&str> for Box<str> {
1462     /// Converts a `&str` into a `Box<str>`
1463     ///
1464     /// This conversion allocates on the heap
1465     /// and performs a copy of `s`.
1466     ///
1467     /// # Examples
1468     ///
1469     /// ```rust
1470     /// let boxed: Box<str> = Box::from("hello");
1471     /// println!("{boxed}");
1472     /// ```
1473     #[inline]
1474     fn from(s: &str) -> Box<str> {
1475         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1476     }
1477 }
1478
1479 #[cfg(not(no_global_oom_handling))]
1480 #[stable(feature = "box_from_cow", since = "1.45.0")]
1481 impl From<Cow<'_, str>> for Box<str> {
1482     /// Converts a `Cow<'_, str>` into a `Box<str>`
1483     ///
1484     /// When `cow` is the `Cow::Borrowed` variant, this
1485     /// conversion allocates on the heap and copies the
1486     /// underlying `str`. Otherwise, it will try to reuse the owned
1487     /// `String`'s allocation.
1488     ///
1489     /// # Examples
1490     ///
1491     /// ```rust
1492     /// use std::borrow::Cow;
1493     ///
1494     /// let unboxed = Cow::Borrowed("hello");
1495     /// let boxed: Box<str> = Box::from(unboxed);
1496     /// println!("{boxed}");
1497     /// ```
1498     ///
1499     /// ```rust
1500     /// # use std::borrow::Cow;
1501     /// let unboxed = Cow::Owned("hello".to_string());
1502     /// let boxed: Box<str> = Box::from(unboxed);
1503     /// println!("{boxed}");
1504     /// ```
1505     #[inline]
1506     fn from(cow: Cow<'_, str>) -> Box<str> {
1507         match cow {
1508             Cow::Borrowed(s) => Box::from(s),
1509             Cow::Owned(s) => Box::from(s),
1510         }
1511     }
1512 }
1513
1514 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1515 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1516     /// Converts a `Box<str>` into a `Box<[u8]>`
1517     ///
1518     /// This conversion does not allocate on the heap and happens in place.
1519     ///
1520     /// # Examples
1521     /// ```rust
1522     /// // create a Box<str> which will be used to create a Box<[u8]>
1523     /// let boxed: Box<str> = Box::from("hello");
1524     /// let boxed_str: Box<[u8]> = Box::from(boxed);
1525     ///
1526     /// // create a &[u8] which will be used to create a Box<[u8]>
1527     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1528     /// let boxed_slice = Box::from(slice);
1529     ///
1530     /// assert_eq!(boxed_slice, boxed_str);
1531     /// ```
1532     #[inline]
1533     fn from(s: Box<str, A>) -> Self {
1534         let (raw, alloc) = Box::into_raw_with_allocator(s);
1535         unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1536     }
1537 }
1538
1539 #[cfg(not(no_global_oom_handling))]
1540 #[stable(feature = "box_from_array", since = "1.45.0")]
1541 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1542     /// Converts a `[T; N]` into a `Box<[T]>`
1543     ///
1544     /// This conversion moves the array to newly heap-allocated memory.
1545     ///
1546     /// # Examples
1547     ///
1548     /// ```rust
1549     /// let boxed: Box<[u8]> = Box::from([4, 2]);
1550     /// println!("{boxed:?}");
1551     /// ```
1552     fn from(array: [T; N]) -> Box<[T]> {
1553         box array
1554     }
1555 }
1556
1557 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1558 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1559     type Error = Box<[T]>;
1560
1561     /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1562     ///
1563     /// The conversion occurs in-place and does not require a
1564     /// new memory allocation.
1565     ///
1566     /// # Errors
1567     ///
1568     /// Returns the old `Box<[T]>` in the `Err` variant if
1569     /// `boxed_slice.len()` does not equal `N`.
1570     fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1571         if boxed_slice.len() == N {
1572             Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1573         } else {
1574             Err(boxed_slice)
1575         }
1576     }
1577 }
1578
1579 impl<A: Allocator> Box<dyn Any, A> {
1580     /// Attempt to downcast the box to a concrete type.
1581     ///
1582     /// # Examples
1583     ///
1584     /// ```
1585     /// use std::any::Any;
1586     ///
1587     /// fn print_if_string(value: Box<dyn Any>) {
1588     ///     if let Ok(string) = value.downcast::<String>() {
1589     ///         println!("String ({}): {}", string.len(), string);
1590     ///     }
1591     /// }
1592     ///
1593     /// let my_string = "Hello World".to_string();
1594     /// print_if_string(Box::new(my_string));
1595     /// print_if_string(Box::new(0i8));
1596     /// ```
1597     #[inline]
1598     #[stable(feature = "rust1", since = "1.0.0")]
1599     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1600         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1601     }
1602
1603     /// Downcasts the box to a concrete type.
1604     ///
1605     /// For a safe alternative see [`downcast`].
1606     ///
1607     /// # Examples
1608     ///
1609     /// ```
1610     /// #![feature(downcast_unchecked)]
1611     ///
1612     /// use std::any::Any;
1613     ///
1614     /// let x: Box<dyn Any> = Box::new(1_usize);
1615     ///
1616     /// unsafe {
1617     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1618     /// }
1619     /// ```
1620     ///
1621     /// # Safety
1622     ///
1623     /// The contained value must be of type `T`. Calling this method
1624     /// with the incorrect type is *undefined behavior*.
1625     ///
1626     /// [`downcast`]: Self::downcast
1627     #[inline]
1628     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1629     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1630         debug_assert!(self.is::<T>());
1631         unsafe {
1632             let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1633             Box::from_raw_in(raw as *mut T, alloc)
1634         }
1635     }
1636 }
1637
1638 impl<A: Allocator> Box<dyn Any + Send, A> {
1639     /// Attempt to downcast the box to a concrete type.
1640     ///
1641     /// # Examples
1642     ///
1643     /// ```
1644     /// use std::any::Any;
1645     ///
1646     /// fn print_if_string(value: Box<dyn Any + Send>) {
1647     ///     if let Ok(string) = value.downcast::<String>() {
1648     ///         println!("String ({}): {}", string.len(), string);
1649     ///     }
1650     /// }
1651     ///
1652     /// let my_string = "Hello World".to_string();
1653     /// print_if_string(Box::new(my_string));
1654     /// print_if_string(Box::new(0i8));
1655     /// ```
1656     #[inline]
1657     #[stable(feature = "rust1", since = "1.0.0")]
1658     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1659         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1660     }
1661
1662     /// Downcasts the box to a concrete type.
1663     ///
1664     /// For a safe alternative see [`downcast`].
1665     ///
1666     /// # Examples
1667     ///
1668     /// ```
1669     /// #![feature(downcast_unchecked)]
1670     ///
1671     /// use std::any::Any;
1672     ///
1673     /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1674     ///
1675     /// unsafe {
1676     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1677     /// }
1678     /// ```
1679     ///
1680     /// # Safety
1681     ///
1682     /// The contained value must be of type `T`. Calling this method
1683     /// with the incorrect type is *undefined behavior*.
1684     ///
1685     /// [`downcast`]: Self::downcast
1686     #[inline]
1687     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1688     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1689         debug_assert!(self.is::<T>());
1690         unsafe {
1691             let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1692             Box::from_raw_in(raw as *mut T, alloc)
1693         }
1694     }
1695 }
1696
1697 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1698     /// Attempt to downcast the box to a concrete type.
1699     ///
1700     /// # Examples
1701     ///
1702     /// ```
1703     /// use std::any::Any;
1704     ///
1705     /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1706     ///     if let Ok(string) = value.downcast::<String>() {
1707     ///         println!("String ({}): {}", string.len(), string);
1708     ///     }
1709     /// }
1710     ///
1711     /// let my_string = "Hello World".to_string();
1712     /// print_if_string(Box::new(my_string));
1713     /// print_if_string(Box::new(0i8));
1714     /// ```
1715     #[inline]
1716     #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1717     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1718         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1719     }
1720
1721     /// Downcasts the box to a concrete type.
1722     ///
1723     /// For a safe alternative see [`downcast`].
1724     ///
1725     /// # Examples
1726     ///
1727     /// ```
1728     /// #![feature(downcast_unchecked)]
1729     ///
1730     /// use std::any::Any;
1731     ///
1732     /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1733     ///
1734     /// unsafe {
1735     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1736     /// }
1737     /// ```
1738     ///
1739     /// # Safety
1740     ///
1741     /// The contained value must be of type `T`. Calling this method
1742     /// with the incorrect type is *undefined behavior*.
1743     ///
1744     /// [`downcast`]: Self::downcast
1745     #[inline]
1746     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1747     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1748         debug_assert!(self.is::<T>());
1749         unsafe {
1750             let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1751                 Box::into_raw_with_allocator(self);
1752             Box::from_raw_in(raw as *mut T, alloc)
1753         }
1754     }
1755 }
1756
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1759     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1760         fmt::Display::fmt(&**self, f)
1761     }
1762 }
1763
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1766     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1767         fmt::Debug::fmt(&**self, f)
1768     }
1769 }
1770
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1773     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774         // It's not possible to extract the inner Uniq directly from the Box,
1775         // instead we cast it to a *const which aliases the Unique
1776         let ptr: *const T = &**self;
1777         fmt::Pointer::fmt(&ptr, f)
1778     }
1779 }
1780
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1783 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1784     type Target = T;
1785
1786     fn deref(&self) -> &T {
1787         &**self
1788     }
1789 }
1790
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1793 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1794     fn deref_mut(&mut self) -> &mut T {
1795         &mut **self
1796     }
1797 }
1798
1799 #[unstable(feature = "receiver_trait", issue = "none")]
1800 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1801
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1804     type Item = I::Item;
1805     fn next(&mut self) -> Option<I::Item> {
1806         (**self).next()
1807     }
1808     fn size_hint(&self) -> (usize, Option<usize>) {
1809         (**self).size_hint()
1810     }
1811     fn nth(&mut self, n: usize) -> Option<I::Item> {
1812         (**self).nth(n)
1813     }
1814     fn last(self) -> Option<I::Item> {
1815         BoxIter::last(self)
1816     }
1817 }
1818
1819 trait BoxIter {
1820     type Item;
1821     fn last(self) -> Option<Self::Item>;
1822 }
1823
1824 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1825     type Item = I::Item;
1826     default fn last(self) -> Option<I::Item> {
1827         #[inline]
1828         fn some<T>(_: Option<T>, x: T) -> Option<T> {
1829             Some(x)
1830         }
1831
1832         self.fold(None, some)
1833     }
1834 }
1835
1836 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1837 /// instead of the default.
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1840     fn last(self) -> Option<I::Item> {
1841         (*self).last()
1842     }
1843 }
1844
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1847     fn next_back(&mut self) -> Option<I::Item> {
1848         (**self).next_back()
1849     }
1850     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1851         (**self).nth_back(n)
1852     }
1853 }
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1856     fn len(&self) -> usize {
1857         (**self).len()
1858     }
1859     fn is_empty(&self) -> bool {
1860         (**self).is_empty()
1861     }
1862 }
1863
1864 #[stable(feature = "fused", since = "1.26.0")]
1865 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1866
1867 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1868 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1869     type Output = <F as FnOnce<Args>>::Output;
1870
1871     extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1872         <F as FnOnce<Args>>::call_once(*self, args)
1873     }
1874 }
1875
1876 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1877 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1878     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1879         <F as FnMut<Args>>::call_mut(self, args)
1880     }
1881 }
1882
1883 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1884 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1885     extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1886         <F as Fn<Args>>::call(self, args)
1887     }
1888 }
1889
1890 #[unstable(feature = "coerce_unsized", issue = "27732")]
1891 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1892
1893 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1894 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1895
1896 #[cfg(not(no_global_oom_handling))]
1897 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1898 impl<I> FromIterator<I> for Box<[I]> {
1899     fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1900         iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1901     }
1902 }
1903
1904 #[cfg(not(no_global_oom_handling))]
1905 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1906 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1907     fn clone(&self) -> Self {
1908         let alloc = Box::allocator(self).clone();
1909         self.to_vec_in(alloc).into_boxed_slice()
1910     }
1911
1912     fn clone_from(&mut self, other: &Self) {
1913         if self.len() == other.len() {
1914             self.clone_from_slice(&other);
1915         } else {
1916             *self = other.clone();
1917         }
1918     }
1919 }
1920
1921 #[stable(feature = "box_borrow", since = "1.1.0")]
1922 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1923     fn borrow(&self) -> &T {
1924         &**self
1925     }
1926 }
1927
1928 #[stable(feature = "box_borrow", since = "1.1.0")]
1929 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1930     fn borrow_mut(&mut self) -> &mut T {
1931         &mut **self
1932     }
1933 }
1934
1935 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1936 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1937     fn as_ref(&self) -> &T {
1938         &**self
1939     }
1940 }
1941
1942 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1943 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1944     fn as_mut(&mut self) -> &mut T {
1945         &mut **self
1946     }
1947 }
1948
1949 /* Nota bene
1950  *
1951  *  We could have chosen not to add this impl, and instead have written a
1952  *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1953  *  because Box<T> implements Unpin even when T does not, as a result of
1954  *  this impl.
1955  *
1956  *  We chose this API instead of the alternative for a few reasons:
1957  *      - Logically, it is helpful to understand pinning in regard to the
1958  *        memory region being pointed to. For this reason none of the
1959  *        standard library pointer types support projecting through a pin
1960  *        (Box<T> is the only pointer type in std for which this would be
1961  *        safe.)
1962  *      - It is in practice very useful to have Box<T> be unconditionally
1963  *        Unpin because of trait objects, for which the structural auto
1964  *        trait functionality does not apply (e.g., Box<dyn Foo> would
1965  *        otherwise not be Unpin).
1966  *
1967  *  Another type with the same semantics as Box but only a conditional
1968  *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1969  *  could have a method to project a Pin<T> from it.
1970  */
1971 #[stable(feature = "pin", since = "1.33.0")]
1972 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1973 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
1974
1975 #[unstable(feature = "generator_trait", issue = "43122")]
1976 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1977 where
1978     A: 'static,
1979 {
1980     type Yield = G::Yield;
1981     type Return = G::Return;
1982
1983     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1984         G::resume(Pin::new(&mut *self), arg)
1985     }
1986 }
1987
1988 #[unstable(feature = "generator_trait", issue = "43122")]
1989 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1990 where
1991     A: 'static,
1992 {
1993     type Yield = G::Yield;
1994     type Return = G::Return;
1995
1996     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1997         G::resume((*self).as_mut(), arg)
1998     }
1999 }
2000
2001 #[stable(feature = "futures_api", since = "1.36.0")]
2002 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2003 where
2004     A: 'static,
2005 {
2006     type Output = F::Output;
2007
2008     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2009         F::poll(Pin::new(&mut *self), cx)
2010     }
2011 }
2012
2013 #[unstable(feature = "async_iterator", issue = "79024")]
2014 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2015     type Item = S::Item;
2016
2017     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2018         Pin::new(&mut **self).poll_next(cx)
2019     }
2020
2021     fn size_hint(&self) -> (usize, Option<usize>) {
2022         (**self).size_hint()
2023     }
2024 }