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