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