]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/boxed.rs
Rollup merge of #97617 - GuillaumeGomez:rustdoc-anonymous-reexports, r=Nemo157
[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     ///
1179     /// # Notes
1180     ///
1181     /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1182     /// as it'll introduce an ambiguity when calling `Pin::from`.
1183     /// A demonstration of such a poor impl is shown below.
1184     ///
1185     /// ```compile_fail
1186     /// # use std::pin::Pin;
1187     /// struct Foo; // A type defined in this crate.
1188     /// impl From<Box<()>> for Pin<Foo> {
1189     ///     fn from(_: Box<()>) -> Pin<Foo> {
1190     ///         Pin::new(Foo)
1191     ///     }
1192     /// }
1193     ///
1194     /// let foo = Box::new(());
1195     /// let bar = Pin::from(foo);
1196     /// ```
1197     #[stable(feature = "box_into_pin", since = "1.63.0")]
1198     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1199     pub const fn into_pin(boxed: Self) -> Pin<Self>
1200     where
1201         A: 'static,
1202     {
1203         // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1204         // when `T: !Unpin`, so it's safe to pin it directly without any
1205         // additional requirements.
1206         unsafe { Pin::new_unchecked(boxed) }
1207     }
1208 }
1209
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1212     fn drop(&mut self) {
1213         // FIXME: Do nothing, drop is currently performed by compiler.
1214     }
1215 }
1216
1217 #[cfg(not(no_global_oom_handling))]
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T: Default> Default for Box<T> {
1220     /// Creates a `Box<T>`, with the `Default` value for T.
1221     fn default() -> Self {
1222         box T::default()
1223     }
1224 }
1225
1226 #[cfg(not(no_global_oom_handling))]
1227 #[stable(feature = "rust1", since = "1.0.0")]
1228 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1229 impl<T> const Default for Box<[T]> {
1230     fn default() -> Self {
1231         let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1232         Box(ptr, Global)
1233     }
1234 }
1235
1236 #[cfg(not(no_global_oom_handling))]
1237 #[stable(feature = "default_box_extra", since = "1.17.0")]
1238 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1239 impl const Default for Box<str> {
1240     fn default() -> Self {
1241         // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1242         let ptr: Unique<str> = unsafe {
1243             let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1244             Unique::new_unchecked(bytes.as_ptr() as *mut str)
1245         };
1246         Box(ptr, Global)
1247     }
1248 }
1249
1250 #[cfg(not(no_global_oom_handling))]
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1253     /// Returns a new box with a `clone()` of this box's contents.
1254     ///
1255     /// # Examples
1256     ///
1257     /// ```
1258     /// let x = Box::new(5);
1259     /// let y = x.clone();
1260     ///
1261     /// // The value is the same
1262     /// assert_eq!(x, y);
1263     ///
1264     /// // But they are unique objects
1265     /// assert_ne!(&*x as *const i32, &*y as *const i32);
1266     /// ```
1267     #[inline]
1268     fn clone(&self) -> Self {
1269         // Pre-allocate memory to allow writing the cloned value directly.
1270         let mut boxed = Self::new_uninit_in(self.1.clone());
1271         unsafe {
1272             (**self).write_clone_into_raw(boxed.as_mut_ptr());
1273             boxed.assume_init()
1274         }
1275     }
1276
1277     /// Copies `source`'s contents into `self` without creating a new allocation.
1278     ///
1279     /// # Examples
1280     ///
1281     /// ```
1282     /// let x = Box::new(5);
1283     /// let mut y = Box::new(10);
1284     /// let yp: *const i32 = &*y;
1285     ///
1286     /// y.clone_from(&x);
1287     ///
1288     /// // The value is the same
1289     /// assert_eq!(x, y);
1290     ///
1291     /// // And no allocation occurred
1292     /// assert_eq!(yp, &*y);
1293     /// ```
1294     #[inline]
1295     fn clone_from(&mut self, source: &Self) {
1296         (**self).clone_from(&(**source));
1297     }
1298 }
1299
1300 #[cfg(not(no_global_oom_handling))]
1301 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1302 impl Clone for Box<str> {
1303     fn clone(&self) -> Self {
1304         // this makes a copy of the data
1305         let buf: Box<[u8]> = self.as_bytes().into();
1306         unsafe { from_boxed_utf8_unchecked(buf) }
1307     }
1308 }
1309
1310 #[stable(feature = "rust1", since = "1.0.0")]
1311 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1312     #[inline]
1313     fn eq(&self, other: &Self) -> bool {
1314         PartialEq::eq(&**self, &**other)
1315     }
1316     #[inline]
1317     fn ne(&self, other: &Self) -> bool {
1318         PartialEq::ne(&**self, &**other)
1319     }
1320 }
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1323     #[inline]
1324     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1325         PartialOrd::partial_cmp(&**self, &**other)
1326     }
1327     #[inline]
1328     fn lt(&self, other: &Self) -> bool {
1329         PartialOrd::lt(&**self, &**other)
1330     }
1331     #[inline]
1332     fn le(&self, other: &Self) -> bool {
1333         PartialOrd::le(&**self, &**other)
1334     }
1335     #[inline]
1336     fn ge(&self, other: &Self) -> bool {
1337         PartialOrd::ge(&**self, &**other)
1338     }
1339     #[inline]
1340     fn gt(&self, other: &Self) -> bool {
1341         PartialOrd::gt(&**self, &**other)
1342     }
1343 }
1344 #[stable(feature = "rust1", since = "1.0.0")]
1345 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1346     #[inline]
1347     fn cmp(&self, other: &Self) -> Ordering {
1348         Ord::cmp(&**self, &**other)
1349     }
1350 }
1351 #[stable(feature = "rust1", since = "1.0.0")]
1352 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1353
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1356     fn hash<H: Hasher>(&self, state: &mut H) {
1357         (**self).hash(state);
1358     }
1359 }
1360
1361 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1362 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1363     fn finish(&self) -> u64 {
1364         (**self).finish()
1365     }
1366     fn write(&mut self, bytes: &[u8]) {
1367         (**self).write(bytes)
1368     }
1369     fn write_u8(&mut self, i: u8) {
1370         (**self).write_u8(i)
1371     }
1372     fn write_u16(&mut self, i: u16) {
1373         (**self).write_u16(i)
1374     }
1375     fn write_u32(&mut self, i: u32) {
1376         (**self).write_u32(i)
1377     }
1378     fn write_u64(&mut self, i: u64) {
1379         (**self).write_u64(i)
1380     }
1381     fn write_u128(&mut self, i: u128) {
1382         (**self).write_u128(i)
1383     }
1384     fn write_usize(&mut self, i: usize) {
1385         (**self).write_usize(i)
1386     }
1387     fn write_i8(&mut self, i: i8) {
1388         (**self).write_i8(i)
1389     }
1390     fn write_i16(&mut self, i: i16) {
1391         (**self).write_i16(i)
1392     }
1393     fn write_i32(&mut self, i: i32) {
1394         (**self).write_i32(i)
1395     }
1396     fn write_i64(&mut self, i: i64) {
1397         (**self).write_i64(i)
1398     }
1399     fn write_i128(&mut self, i: i128) {
1400         (**self).write_i128(i)
1401     }
1402     fn write_isize(&mut self, i: isize) {
1403         (**self).write_isize(i)
1404     }
1405     fn write_length_prefix(&mut self, len: usize) {
1406         (**self).write_length_prefix(len)
1407     }
1408     fn write_str(&mut self, s: &str) {
1409         (**self).write_str(s)
1410     }
1411 }
1412
1413 #[cfg(not(no_global_oom_handling))]
1414 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1415 impl<T> From<T> for Box<T> {
1416     /// Converts a `T` into a `Box<T>`
1417     ///
1418     /// The conversion allocates on the heap and moves `t`
1419     /// from the stack into it.
1420     ///
1421     /// # Examples
1422     ///
1423     /// ```rust
1424     /// let x = 5;
1425     /// let boxed = Box::new(5);
1426     ///
1427     /// assert_eq!(Box::from(x), boxed);
1428     /// ```
1429     fn from(t: T) -> Self {
1430         Box::new(t)
1431     }
1432 }
1433
1434 #[stable(feature = "pin", since = "1.33.0")]
1435 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1436 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1437 where
1438     A: 'static,
1439 {
1440     /// Converts a `Box<T>` into a `Pin<Box<T>>`
1441     ///
1442     /// This conversion does not allocate on the heap and happens in place.
1443     fn from(boxed: Box<T, A>) -> Self {
1444         Box::into_pin(boxed)
1445     }
1446 }
1447
1448 #[cfg(not(no_global_oom_handling))]
1449 #[stable(feature = "box_from_slice", since = "1.17.0")]
1450 impl<T: Copy> From<&[T]> for Box<[T]> {
1451     /// Converts a `&[T]` into a `Box<[T]>`
1452     ///
1453     /// This conversion allocates on the heap
1454     /// and performs a copy of `slice`.
1455     ///
1456     /// # Examples
1457     /// ```rust
1458     /// // create a &[u8] which will be used to create a Box<[u8]>
1459     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1460     /// let boxed_slice: Box<[u8]> = Box::from(slice);
1461     ///
1462     /// println!("{boxed_slice:?}");
1463     /// ```
1464     fn from(slice: &[T]) -> Box<[T]> {
1465         let len = slice.len();
1466         let buf = RawVec::with_capacity(len);
1467         unsafe {
1468             ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1469             buf.into_box(slice.len()).assume_init()
1470         }
1471     }
1472 }
1473
1474 #[cfg(not(no_global_oom_handling))]
1475 #[stable(feature = "box_from_cow", since = "1.45.0")]
1476 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1477     /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1478     ///
1479     /// When `cow` is the `Cow::Borrowed` variant, this
1480     /// conversion allocates on the heap and copies the
1481     /// underlying slice. Otherwise, it will try to reuse the owned
1482     /// `Vec`'s allocation.
1483     #[inline]
1484     fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1485         match cow {
1486             Cow::Borrowed(slice) => Box::from(slice),
1487             Cow::Owned(slice) => Box::from(slice),
1488         }
1489     }
1490 }
1491
1492 #[cfg(not(no_global_oom_handling))]
1493 #[stable(feature = "box_from_slice", since = "1.17.0")]
1494 impl From<&str> for Box<str> {
1495     /// Converts a `&str` into a `Box<str>`
1496     ///
1497     /// This conversion allocates on the heap
1498     /// and performs a copy of `s`.
1499     ///
1500     /// # Examples
1501     ///
1502     /// ```rust
1503     /// let boxed: Box<str> = Box::from("hello");
1504     /// println!("{boxed}");
1505     /// ```
1506     #[inline]
1507     fn from(s: &str) -> Box<str> {
1508         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1509     }
1510 }
1511
1512 #[cfg(not(no_global_oom_handling))]
1513 #[stable(feature = "box_from_cow", since = "1.45.0")]
1514 impl From<Cow<'_, str>> for Box<str> {
1515     /// Converts a `Cow<'_, str>` into a `Box<str>`
1516     ///
1517     /// When `cow` is the `Cow::Borrowed` variant, this
1518     /// conversion allocates on the heap and copies the
1519     /// underlying `str`. Otherwise, it will try to reuse the owned
1520     /// `String`'s allocation.
1521     ///
1522     /// # Examples
1523     ///
1524     /// ```rust
1525     /// use std::borrow::Cow;
1526     ///
1527     /// let unboxed = Cow::Borrowed("hello");
1528     /// let boxed: Box<str> = Box::from(unboxed);
1529     /// println!("{boxed}");
1530     /// ```
1531     ///
1532     /// ```rust
1533     /// # use std::borrow::Cow;
1534     /// let unboxed = Cow::Owned("hello".to_string());
1535     /// let boxed: Box<str> = Box::from(unboxed);
1536     /// println!("{boxed}");
1537     /// ```
1538     #[inline]
1539     fn from(cow: Cow<'_, str>) -> Box<str> {
1540         match cow {
1541             Cow::Borrowed(s) => Box::from(s),
1542             Cow::Owned(s) => Box::from(s),
1543         }
1544     }
1545 }
1546
1547 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1548 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1549     /// Converts a `Box<str>` into a `Box<[u8]>`
1550     ///
1551     /// This conversion does not allocate on the heap and happens in place.
1552     ///
1553     /// # Examples
1554     /// ```rust
1555     /// // create a Box<str> which will be used to create a Box<[u8]>
1556     /// let boxed: Box<str> = Box::from("hello");
1557     /// let boxed_str: Box<[u8]> = Box::from(boxed);
1558     ///
1559     /// // create a &[u8] which will be used to create a Box<[u8]>
1560     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1561     /// let boxed_slice = Box::from(slice);
1562     ///
1563     /// assert_eq!(boxed_slice, boxed_str);
1564     /// ```
1565     #[inline]
1566     fn from(s: Box<str, A>) -> Self {
1567         let (raw, alloc) = Box::into_raw_with_allocator(s);
1568         unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1569     }
1570 }
1571
1572 #[cfg(not(no_global_oom_handling))]
1573 #[stable(feature = "box_from_array", since = "1.45.0")]
1574 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1575     /// Converts a `[T; N]` into a `Box<[T]>`
1576     ///
1577     /// This conversion moves the array to newly heap-allocated memory.
1578     ///
1579     /// # Examples
1580     ///
1581     /// ```rust
1582     /// let boxed: Box<[u8]> = Box::from([4, 2]);
1583     /// println!("{boxed:?}");
1584     /// ```
1585     fn from(array: [T; N]) -> Box<[T]> {
1586         box array
1587     }
1588 }
1589
1590 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1591 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1592     type Error = Box<[T]>;
1593
1594     /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1595     ///
1596     /// The conversion occurs in-place and does not require a
1597     /// new memory allocation.
1598     ///
1599     /// # Errors
1600     ///
1601     /// Returns the old `Box<[T]>` in the `Err` variant if
1602     /// `boxed_slice.len()` does not equal `N`.
1603     fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1604         if boxed_slice.len() == N {
1605             Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1606         } else {
1607             Err(boxed_slice)
1608         }
1609     }
1610 }
1611
1612 impl<A: Allocator> Box<dyn Any, A> {
1613     /// Attempt to downcast the box to a concrete type.
1614     ///
1615     /// # Examples
1616     ///
1617     /// ```
1618     /// use std::any::Any;
1619     ///
1620     /// fn print_if_string(value: Box<dyn Any>) {
1621     ///     if let Ok(string) = value.downcast::<String>() {
1622     ///         println!("String ({}): {}", string.len(), string);
1623     ///     }
1624     /// }
1625     ///
1626     /// let my_string = "Hello World".to_string();
1627     /// print_if_string(Box::new(my_string));
1628     /// print_if_string(Box::new(0i8));
1629     /// ```
1630     #[inline]
1631     #[stable(feature = "rust1", since = "1.0.0")]
1632     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1633         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1634     }
1635
1636     /// Downcasts the box to a concrete type.
1637     ///
1638     /// For a safe alternative see [`downcast`].
1639     ///
1640     /// # Examples
1641     ///
1642     /// ```
1643     /// #![feature(downcast_unchecked)]
1644     ///
1645     /// use std::any::Any;
1646     ///
1647     /// let x: Box<dyn Any> = Box::new(1_usize);
1648     ///
1649     /// unsafe {
1650     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1651     /// }
1652     /// ```
1653     ///
1654     /// # Safety
1655     ///
1656     /// The contained value must be of type `T`. Calling this method
1657     /// with the incorrect type is *undefined behavior*.
1658     ///
1659     /// [`downcast`]: Self::downcast
1660     #[inline]
1661     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1662     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1663         debug_assert!(self.is::<T>());
1664         unsafe {
1665             let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1666             Box::from_raw_in(raw as *mut T, alloc)
1667         }
1668     }
1669 }
1670
1671 impl<A: Allocator> Box<dyn Any + Send, A> {
1672     /// Attempt to downcast the box to a concrete type.
1673     ///
1674     /// # Examples
1675     ///
1676     /// ```
1677     /// use std::any::Any;
1678     ///
1679     /// fn print_if_string(value: Box<dyn Any + Send>) {
1680     ///     if let Ok(string) = value.downcast::<String>() {
1681     ///         println!("String ({}): {}", string.len(), string);
1682     ///     }
1683     /// }
1684     ///
1685     /// let my_string = "Hello World".to_string();
1686     /// print_if_string(Box::new(my_string));
1687     /// print_if_string(Box::new(0i8));
1688     /// ```
1689     #[inline]
1690     #[stable(feature = "rust1", since = "1.0.0")]
1691     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1692         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1693     }
1694
1695     /// Downcasts the box to a concrete type.
1696     ///
1697     /// For a safe alternative see [`downcast`].
1698     ///
1699     /// # Examples
1700     ///
1701     /// ```
1702     /// #![feature(downcast_unchecked)]
1703     ///
1704     /// use std::any::Any;
1705     ///
1706     /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1707     ///
1708     /// unsafe {
1709     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1710     /// }
1711     /// ```
1712     ///
1713     /// # Safety
1714     ///
1715     /// The contained value must be of type `T`. Calling this method
1716     /// with the incorrect type is *undefined behavior*.
1717     ///
1718     /// [`downcast`]: Self::downcast
1719     #[inline]
1720     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1721     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1722         debug_assert!(self.is::<T>());
1723         unsafe {
1724             let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1725             Box::from_raw_in(raw as *mut T, alloc)
1726         }
1727     }
1728 }
1729
1730 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1731     /// Attempt to downcast the box to a concrete type.
1732     ///
1733     /// # Examples
1734     ///
1735     /// ```
1736     /// use std::any::Any;
1737     ///
1738     /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1739     ///     if let Ok(string) = value.downcast::<String>() {
1740     ///         println!("String ({}): {}", string.len(), string);
1741     ///     }
1742     /// }
1743     ///
1744     /// let my_string = "Hello World".to_string();
1745     /// print_if_string(Box::new(my_string));
1746     /// print_if_string(Box::new(0i8));
1747     /// ```
1748     #[inline]
1749     #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1750     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1751         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1752     }
1753
1754     /// Downcasts the box to a concrete type.
1755     ///
1756     /// For a safe alternative see [`downcast`].
1757     ///
1758     /// # Examples
1759     ///
1760     /// ```
1761     /// #![feature(downcast_unchecked)]
1762     ///
1763     /// use std::any::Any;
1764     ///
1765     /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1766     ///
1767     /// unsafe {
1768     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1769     /// }
1770     /// ```
1771     ///
1772     /// # Safety
1773     ///
1774     /// The contained value must be of type `T`. Calling this method
1775     /// with the incorrect type is *undefined behavior*.
1776     ///
1777     /// [`downcast`]: Self::downcast
1778     #[inline]
1779     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1780     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1781         debug_assert!(self.is::<T>());
1782         unsafe {
1783             let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1784                 Box::into_raw_with_allocator(self);
1785             Box::from_raw_in(raw as *mut T, alloc)
1786         }
1787     }
1788 }
1789
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1792     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1793         fmt::Display::fmt(&**self, f)
1794     }
1795 }
1796
1797 #[stable(feature = "rust1", since = "1.0.0")]
1798 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1799     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1800         fmt::Debug::fmt(&**self, f)
1801     }
1802 }
1803
1804 #[stable(feature = "rust1", since = "1.0.0")]
1805 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1806     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1807         // It's not possible to extract the inner Uniq directly from the Box,
1808         // instead we cast it to a *const which aliases the Unique
1809         let ptr: *const T = &**self;
1810         fmt::Pointer::fmt(&ptr, f)
1811     }
1812 }
1813
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1816 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1817     type Target = T;
1818
1819     fn deref(&self) -> &T {
1820         &**self
1821     }
1822 }
1823
1824 #[stable(feature = "rust1", since = "1.0.0")]
1825 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1826 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1827     fn deref_mut(&mut self) -> &mut T {
1828         &mut **self
1829     }
1830 }
1831
1832 #[unstable(feature = "receiver_trait", issue = "none")]
1833 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1834
1835 #[stable(feature = "rust1", since = "1.0.0")]
1836 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1837     type Item = I::Item;
1838     fn next(&mut self) -> Option<I::Item> {
1839         (**self).next()
1840     }
1841     fn size_hint(&self) -> (usize, Option<usize>) {
1842         (**self).size_hint()
1843     }
1844     fn nth(&mut self, n: usize) -> Option<I::Item> {
1845         (**self).nth(n)
1846     }
1847     fn last(self) -> Option<I::Item> {
1848         BoxIter::last(self)
1849     }
1850 }
1851
1852 trait BoxIter {
1853     type Item;
1854     fn last(self) -> Option<Self::Item>;
1855 }
1856
1857 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1858     type Item = I::Item;
1859     default fn last(self) -> Option<I::Item> {
1860         #[inline]
1861         fn some<T>(_: Option<T>, x: T) -> Option<T> {
1862             Some(x)
1863         }
1864
1865         self.fold(None, some)
1866     }
1867 }
1868
1869 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1870 /// instead of the default.
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1873     fn last(self) -> Option<I::Item> {
1874         (*self).last()
1875     }
1876 }
1877
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1880     fn next_back(&mut self) -> Option<I::Item> {
1881         (**self).next_back()
1882     }
1883     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1884         (**self).nth_back(n)
1885     }
1886 }
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1889     fn len(&self) -> usize {
1890         (**self).len()
1891     }
1892     fn is_empty(&self) -> bool {
1893         (**self).is_empty()
1894     }
1895 }
1896
1897 #[stable(feature = "fused", since = "1.26.0")]
1898 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1899
1900 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1901 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1902     type Output = <F as FnOnce<Args>>::Output;
1903
1904     extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1905         <F as FnOnce<Args>>::call_once(*self, args)
1906     }
1907 }
1908
1909 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1910 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1911     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1912         <F as FnMut<Args>>::call_mut(self, args)
1913     }
1914 }
1915
1916 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1917 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1918     extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1919         <F as Fn<Args>>::call(self, args)
1920     }
1921 }
1922
1923 #[unstable(feature = "coerce_unsized", issue = "27732")]
1924 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1925
1926 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1927 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1928
1929 #[cfg(not(no_global_oom_handling))]
1930 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1931 impl<I> FromIterator<I> for Box<[I]> {
1932     fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1933         iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1934     }
1935 }
1936
1937 #[cfg(not(no_global_oom_handling))]
1938 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1939 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1940     fn clone(&self) -> Self {
1941         let alloc = Box::allocator(self).clone();
1942         self.to_vec_in(alloc).into_boxed_slice()
1943     }
1944
1945     fn clone_from(&mut self, other: &Self) {
1946         if self.len() == other.len() {
1947             self.clone_from_slice(&other);
1948         } else {
1949             *self = other.clone();
1950         }
1951     }
1952 }
1953
1954 #[stable(feature = "box_borrow", since = "1.1.0")]
1955 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1956     fn borrow(&self) -> &T {
1957         &**self
1958     }
1959 }
1960
1961 #[stable(feature = "box_borrow", since = "1.1.0")]
1962 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1963     fn borrow_mut(&mut self) -> &mut T {
1964         &mut **self
1965     }
1966 }
1967
1968 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1969 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1970     fn as_ref(&self) -> &T {
1971         &**self
1972     }
1973 }
1974
1975 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1976 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1977     fn as_mut(&mut self) -> &mut T {
1978         &mut **self
1979     }
1980 }
1981
1982 /* Nota bene
1983  *
1984  *  We could have chosen not to add this impl, and instead have written a
1985  *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1986  *  because Box<T> implements Unpin even when T does not, as a result of
1987  *  this impl.
1988  *
1989  *  We chose this API instead of the alternative for a few reasons:
1990  *      - Logically, it is helpful to understand pinning in regard to the
1991  *        memory region being pointed to. For this reason none of the
1992  *        standard library pointer types support projecting through a pin
1993  *        (Box<T> is the only pointer type in std for which this would be
1994  *        safe.)
1995  *      - It is in practice very useful to have Box<T> be unconditionally
1996  *        Unpin because of trait objects, for which the structural auto
1997  *        trait functionality does not apply (e.g., Box<dyn Foo> would
1998  *        otherwise not be Unpin).
1999  *
2000  *  Another type with the same semantics as Box but only a conditional
2001  *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2002  *  could have a method to project a Pin<T> from it.
2003  */
2004 #[stable(feature = "pin", since = "1.33.0")]
2005 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
2006 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
2007
2008 #[unstable(feature = "generator_trait", issue = "43122")]
2009 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2010 where
2011     A: 'static,
2012 {
2013     type Yield = G::Yield;
2014     type Return = G::Return;
2015
2016     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2017         G::resume(Pin::new(&mut *self), arg)
2018     }
2019 }
2020
2021 #[unstable(feature = "generator_trait", issue = "43122")]
2022 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2023 where
2024     A: 'static,
2025 {
2026     type Yield = G::Yield;
2027     type Return = G::Return;
2028
2029     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2030         G::resume((*self).as_mut(), arg)
2031     }
2032 }
2033
2034 #[stable(feature = "futures_api", since = "1.36.0")]
2035 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2036 where
2037     A: 'static,
2038 {
2039     type Output = F::Output;
2040
2041     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2042         F::poll(Pin::new(&mut *self), cx)
2043     }
2044 }
2045
2046 #[unstable(feature = "async_iterator", issue = "79024")]
2047 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2048     type Item = S::Item;
2049
2050     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2051         Pin::new(&mut **self).poll_next(cx)
2052     }
2053
2054     fn size_hint(&self) -> (usize, Option<usize>) {
2055         (**self).size_hint()
2056     }
2057 }