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