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