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