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