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