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