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