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