]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
Simplify `maybe_get_optimized_mir` and `maybe_get_promoted_mir`
[rust.git] / src / liballoc / 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.
6 //!
7 //! # Examples
8 //!
9 //! Move a value from the stack to the heap by creating a [`Box`]:
10 //!
11 //! ```
12 //! let val: u8 = 5;
13 //! let boxed: Box<u8> = Box::new(val);
14 //! ```
15 //!
16 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
17 //!
18 //! ```
19 //! let boxed: Box<u8> = Box::new(5);
20 //! let val: u8 = *boxed;
21 //! ```
22 //!
23 //! Creating a recursive data structure:
24 //!
25 //! ```
26 //! #[derive(Debug)]
27 //! enum List<T> {
28 //!     Cons(T, Box<List<T>>),
29 //!     Nil,
30 //! }
31 //!
32 //! fn main() {
33 //!     let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //!     println!("{:?}", list);
35 //! }
36 //! ```
37 //!
38 //! This will print `Cons(1, Cons(2, Nil))`.
39 //!
40 //! Recursive structures must be boxed, because if the definition of `Cons`
41 //! looked like this:
42 //!
43 //! ```compile_fail,E0072
44 //! # enum List<T> {
45 //! Cons(T, List<T>),
46 //! # }
47 //! ```
48 //!
49 //! It wouldn't work. This is because the size of a `List` depends on how many
50 //! elements are in the list, and so we don't know how much memory to allocate
51 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
52 //! big `Cons` needs to be.
53 //!
54 //! # Memory layout
55 //!
56 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
57 //! its allocation. It is valid to convert both ways between a [`Box`] and a
58 //! raw pointer allocated with the [`Global`] allocator, given that the
59 //! [`Layout`] used with the allocator is correct for the type. More precisely,
60 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
61 //! with `Layout::for_value(&*value)` may be converted into a box using
62 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
63 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
64 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
65 //!
66 //!
67 //! [dereferencing]: ../../std/ops/trait.Deref.html
68 //! [`Box`]: struct.Box.html
69 //! [`Box<T>`]: struct.Box.html
70 //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
71 //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
72 //! [`Global`]: ../alloc/struct.Global.html
73 //! [`Layout`]: ../alloc/struct.Layout.html
74 //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value
75
76 #![stable(feature = "rust1", since = "1.0.0")]
77
78 use core::any::Any;
79 use core::array::LengthAtMost32;
80 use core::borrow;
81 use core::cmp::Ordering;
82 use core::convert::{From, TryFrom};
83 use core::fmt;
84 use core::future::Future;
85 use core::hash::{Hash, Hasher};
86 use core::iter::{Iterator, FromIterator, FusedIterator};
87 use core::marker::{Unpin, Unsize};
88 use core::mem;
89 use core::pin::Pin;
90 use core::ops::{
91     CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
92 };
93 use core::ptr::{self, NonNull, Unique};
94 use core::slice;
95 use core::task::{Context, Poll};
96
97 use crate::alloc::{self, Global, Alloc};
98 use crate::vec::Vec;
99 use crate::raw_vec::RawVec;
100 use crate::str::from_boxed_utf8_unchecked;
101
102 /// A pointer type for heap allocation.
103 ///
104 /// See the [module-level documentation](../../std/boxed/index.html) for more.
105 #[lang = "owned_box"]
106 #[fundamental]
107 #[stable(feature = "rust1", since = "1.0.0")]
108 pub struct Box<T: ?Sized>(Unique<T>);
109
110 impl<T> Box<T> {
111     /// Allocates memory on the heap and then places `x` into it.
112     ///
113     /// This doesn't actually allocate if `T` is zero-sized.
114     ///
115     /// # Examples
116     ///
117     /// ```
118     /// let five = Box::new(5);
119     /// ```
120     #[stable(feature = "rust1", since = "1.0.0")]
121     #[inline(always)]
122     pub fn new(x: T) -> Box<T> {
123         box x
124     }
125
126     /// Constructs a new box with uninitialized contents.
127     ///
128     /// # Examples
129     ///
130     /// ```
131     /// #![feature(new_uninit)]
132     ///
133     /// let mut five = Box::<u32>::new_uninit();
134     ///
135     /// let five = unsafe {
136     ///     // Deferred initialization:
137     ///     five.as_mut_ptr().write(5);
138     ///
139     ///     five.assume_init()
140     /// };
141     ///
142     /// assert_eq!(*five, 5)
143     /// ```
144     #[unstable(feature = "new_uninit", issue = "63291")]
145     pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
146         let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
147         let ptr = unsafe {
148             Global.alloc(layout)
149                 .unwrap_or_else(|_| alloc::handle_alloc_error(layout))
150         };
151         Box(ptr.cast().into())
152     }
153
154     /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
155     /// `x` will be pinned in memory and unable to be moved.
156     #[stable(feature = "pin", since = "1.33.0")]
157     #[inline(always)]
158     pub fn pin(x: T) -> Pin<Box<T>> {
159         (box x).into()
160     }
161 }
162
163 impl<T> Box<[T]> {
164     /// Constructs a new boxed slice with uninitialized contents.
165     ///
166     /// # Examples
167     ///
168     /// ```
169     /// #![feature(new_uninit)]
170     ///
171     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
172     ///
173     /// let values = unsafe {
174     ///     // Deferred initialization:
175     ///     values[0].as_mut_ptr().write(1);
176     ///     values[1].as_mut_ptr().write(2);
177     ///     values[2].as_mut_ptr().write(3);
178     ///
179     ///     values.assume_init()
180     /// };
181     ///
182     /// assert_eq!(*values, [1, 2, 3])
183     /// ```
184     #[unstable(feature = "new_uninit", issue = "63291")]
185     pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
186         let layout = alloc::Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
187         let ptr = unsafe { alloc::alloc(layout) };
188         let unique = Unique::new(ptr).unwrap_or_else(|| alloc::handle_alloc_error(layout));
189         let slice = unsafe { slice::from_raw_parts_mut(unique.cast().as_ptr(), len) };
190         Box(Unique::from(slice))
191     }
192 }
193
194 impl<T> Box<mem::MaybeUninit<T>> {
195     /// Converts to `Box<T>`.
196     ///
197     /// # Safety
198     ///
199     /// As with [`MaybeUninit::assume_init`],
200     /// it is up to the caller to guarantee that the value
201     /// really is in an initialized state.
202     /// Calling this when the content is not yet fully initialized
203     /// causes immediate undefined behavior.
204     ///
205     /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
206     ///
207     /// # Examples
208     ///
209     /// ```
210     /// #![feature(new_uninit)]
211     ///
212     /// let mut five = Box::<u32>::new_uninit();
213     ///
214     /// let five: Box<u32> = unsafe {
215     ///     // Deferred initialization:
216     ///     five.as_mut_ptr().write(5);
217     ///
218     ///     five.assume_init()
219     /// };
220     ///
221     /// assert_eq!(*five, 5)
222     /// ```
223     #[unstable(feature = "new_uninit", issue = "63291")]
224     #[inline]
225     pub unsafe fn assume_init(self) -> Box<T> {
226         Box(Box::into_unique(self).cast())
227     }
228 }
229
230 impl<T> Box<[mem::MaybeUninit<T>]> {
231     /// Converts to `Box<[T]>`.
232     ///
233     /// # Safety
234     ///
235     /// As with [`MaybeUninit::assume_init`],
236     /// it is up to the caller to guarantee that the values
237     /// really are in an initialized state.
238     /// Calling this when the content is not yet fully initialized
239     /// causes immediate undefined behavior.
240     ///
241     /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
242     ///
243     /// # Examples
244     ///
245     /// ```
246     /// #![feature(new_uninit)]
247     ///
248     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
249     ///
250     /// let values = unsafe {
251     ///     // Deferred initialization:
252     ///     values[0].as_mut_ptr().write(1);
253     ///     values[1].as_mut_ptr().write(2);
254     ///     values[2].as_mut_ptr().write(3);
255     ///
256     ///     values.assume_init()
257     /// };
258     ///
259     /// assert_eq!(*values, [1, 2, 3])
260     /// ```
261     #[unstable(feature = "new_uninit", issue = "63291")]
262     #[inline]
263     pub unsafe fn assume_init(self) -> Box<[T]> {
264         Box(Unique::new_unchecked(Box::into_raw(self) as _))
265     }
266 }
267
268 impl<T: ?Sized> Box<T> {
269     /// Constructs a box from a raw pointer.
270     ///
271     /// After calling this function, the raw pointer is owned by the
272     /// resulting `Box`. Specifically, the `Box` destructor will call
273     /// the destructor of `T` and free the allocated memory. For this
274     /// to be safe, the memory must have been allocated in accordance
275     /// with the [memory layout] used by `Box` .
276     ///
277     /// # Safety
278     ///
279     /// This function is unsafe because improper use may lead to
280     /// memory problems. For example, a double-free may occur if the
281     /// function is called twice on the same raw pointer.
282     ///
283     /// # Examples
284     /// Recreate a `Box` which was previously converted to a raw pointer
285     /// using [`Box::into_raw`]:
286     /// ```
287     /// let x = Box::new(5);
288     /// let ptr = Box::into_raw(x);
289     /// let x = unsafe { Box::from_raw(ptr) };
290     /// ```
291     /// Manually create a `Box` from scratch by using the global allocator:
292     /// ```
293     /// use std::alloc::{alloc, Layout};
294     ///
295     /// unsafe {
296     ///     let ptr = alloc(Layout::new::<i32>()) as *mut i32;
297     ///     *ptr = 5;
298     ///     let x = Box::from_raw(ptr);
299     /// }
300     /// ```
301     ///
302     /// [memory layout]: index.html#memory-layout
303     /// [`Layout`]: ../alloc/struct.Layout.html
304     /// [`Box::into_raw`]: struct.Box.html#method.into_raw
305     #[stable(feature = "box_raw", since = "1.4.0")]
306     #[inline]
307     pub unsafe fn from_raw(raw: *mut T) -> Self {
308         Box(Unique::new_unchecked(raw))
309     }
310
311     /// Consumes the `Box`, returning a wrapped raw pointer.
312     ///
313     /// The pointer will be properly aligned and non-null.
314     ///
315     /// After calling this function, the caller is responsible for the
316     /// memory previously managed by the `Box`. In particular, the
317     /// caller should properly destroy `T` and release the memory, taking
318     /// into account the [memory layout] used by `Box`. The easiest way to
319     /// do this is to convert the raw pointer back into a `Box` with the
320     /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
321     /// the cleanup.
322     ///
323     /// Note: this is an associated function, which means that you have
324     /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
325     /// is so that there is no conflict with a method on the inner type.
326     ///
327     /// # Examples
328     /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
329     /// for automatic cleanup:
330     /// ```
331     /// let x = Box::new(String::from("Hello"));
332     /// let ptr = Box::into_raw(x);
333     /// let x = unsafe { Box::from_raw(ptr) };
334     /// ```
335     /// Manual cleanup by explicitly running the destructor and deallocating
336     /// the memory:
337     /// ```
338     /// use std::alloc::{dealloc, Layout};
339     /// use std::ptr;
340     ///
341     /// let x = Box::new(String::from("Hello"));
342     /// let p = Box::into_raw(x);
343     /// unsafe {
344     ///     ptr::drop_in_place(p);
345     ///     dealloc(p as *mut u8, Layout::new::<String>());
346     /// }
347     /// ```
348     ///
349     /// [memory layout]: index.html#memory-layout
350     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
351     #[stable(feature = "box_raw", since = "1.4.0")]
352     #[inline]
353     pub fn into_raw(b: Box<T>) -> *mut T {
354         Box::into_raw_non_null(b).as_ptr()
355     }
356
357     /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
358     ///
359     /// After calling this function, the caller is responsible for the
360     /// memory previously managed by the `Box`. In particular, the
361     /// caller should properly destroy `T` and release the memory. The
362     /// easiest way to do so is to convert the `NonNull<T>` pointer
363     /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
364     /// function.
365     ///
366     /// Note: this is an associated function, which means that you have
367     /// to call it as `Box::into_raw_non_null(b)`
368     /// instead of `b.into_raw_non_null()`. This
369     /// is so that there is no conflict with a method on the inner type.
370     ///
371     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
372     ///
373     /// # Examples
374     ///
375     /// ```
376     /// #![feature(box_into_raw_non_null)]
377     ///
378     /// fn main() {
379     ///     let x = Box::new(5);
380     ///     let ptr = Box::into_raw_non_null(x);
381     ///
382     ///     // Clean up the memory by converting the NonNull pointer back
383     ///     // into a Box and letting the Box be dropped.
384     ///     let x = unsafe { Box::from_raw(ptr.as_ptr()) };
385     /// }
386     /// ```
387     #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
388     #[inline]
389     pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
390         Box::into_unique(b).into()
391     }
392
393     #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
394     #[inline]
395     #[doc(hidden)]
396     pub fn into_unique(b: Box<T>) -> Unique<T> {
397         let mut unique = b.0;
398         mem::forget(b);
399         // Box is kind-of a library type, but recognized as a "unique pointer" by
400         // Stacked Borrows.  This function here corresponds to "reborrowing to
401         // a raw pointer", but there is no actual reborrow here -- so
402         // without some care, the pointer we are returning here still carries
403         // the tag of `b`, with `Unique` permission.
404         // We round-trip through a mutable reference to avoid that.
405         unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
406     }
407
408     /// Consumes and leaks the `Box`, returning a mutable reference,
409     /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
410     /// `'a`. If the type has only static references, or none at all, then this
411     /// may be chosen to be `'static`.
412     ///
413     /// This function is mainly useful for data that lives for the remainder of
414     /// the program's life. Dropping the returned reference will cause a memory
415     /// leak. If this is not acceptable, the reference should first be wrapped
416     /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
417     /// then be dropped which will properly destroy `T` and release the
418     /// allocated memory.
419     ///
420     /// Note: this is an associated function, which means that you have
421     /// to call it as `Box::leak(b)` instead of `b.leak()`. This
422     /// is so that there is no conflict with a method on the inner type.
423     ///
424     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
425     ///
426     /// # Examples
427     ///
428     /// Simple usage:
429     ///
430     /// ```
431     /// fn main() {
432     ///     let x = Box::new(41);
433     ///     let static_ref: &'static mut usize = Box::leak(x);
434     ///     *static_ref += 1;
435     ///     assert_eq!(*static_ref, 42);
436     /// }
437     /// ```
438     ///
439     /// Unsized data:
440     ///
441     /// ```
442     /// fn main() {
443     ///     let x = vec![1, 2, 3].into_boxed_slice();
444     ///     let static_ref = Box::leak(x);
445     ///     static_ref[0] = 4;
446     ///     assert_eq!(*static_ref, [4, 2, 3]);
447     /// }
448     /// ```
449     #[stable(feature = "box_leak", since = "1.26.0")]
450     #[inline]
451     pub fn leak<'a>(b: Box<T>) -> &'a mut T
452     where
453         T: 'a // Technically not needed, but kept to be explicit.
454     {
455         unsafe { &mut *Box::into_raw(b) }
456     }
457
458     /// Converts a `Box<T>` into a `Pin<Box<T>>`
459     ///
460     /// This conversion does not allocate on the heap and happens in place.
461     ///
462     /// This is also available via [`From`].
463     #[unstable(feature = "box_into_pin", issue = "62370")]
464     pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
465         // It's not possible to move or replace the insides of a `Pin<Box<T>>`
466         // when `T: !Unpin`,  so it's safe to pin it directly without any
467         // additional requirements.
468         unsafe { Pin::new_unchecked(boxed) }
469     }
470 }
471
472 #[stable(feature = "rust1", since = "1.0.0")]
473 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
474     fn drop(&mut self) {
475         // FIXME: Do nothing, drop is currently performed by compiler.
476     }
477 }
478
479 #[stable(feature = "rust1", since = "1.0.0")]
480 impl<T: Default> Default for Box<T> {
481     /// Creates a `Box<T>`, with the `Default` value for T.
482     fn default() -> Box<T> {
483         box Default::default()
484     }
485 }
486
487 #[stable(feature = "rust1", since = "1.0.0")]
488 impl<T> Default for Box<[T]> {
489     fn default() -> Box<[T]> {
490         Box::<[T; 0]>::new([])
491     }
492 }
493
494 #[stable(feature = "default_box_extra", since = "1.17.0")]
495 impl Default for Box<str> {
496     fn default() -> Box<str> {
497         unsafe { from_boxed_utf8_unchecked(Default::default()) }
498     }
499 }
500
501 #[stable(feature = "rust1", since = "1.0.0")]
502 impl<T: Clone> Clone for Box<T> {
503     /// Returns a new box with a `clone()` of this box's contents.
504     ///
505     /// # Examples
506     ///
507     /// ```
508     /// let x = Box::new(5);
509     /// let y = x.clone();
510     ///
511     /// // The value is the same
512     /// assert_eq!(x, y);
513     ///
514     /// // But they are unique objects
515     /// assert_ne!(&*x as *const i32, &*y as *const i32);
516     /// ```
517     #[rustfmt::skip]
518     #[inline]
519     fn clone(&self) -> Box<T> {
520         box { (**self).clone() }
521     }
522
523     /// Copies `source`'s contents into `self` without creating a new allocation.
524     ///
525     /// # Examples
526     ///
527     /// ```
528     /// let x = Box::new(5);
529     /// let mut y = Box::new(10);
530     /// let yp: *const i32 = &*y;
531     ///
532     /// y.clone_from(&x);
533     ///
534     /// // The value is the same
535     /// assert_eq!(x, y);
536     ///
537     /// // And no allocation occurred
538     /// assert_eq!(yp, &*y);
539     /// ```
540     #[inline]
541     fn clone_from(&mut self, source: &Box<T>) {
542         (**self).clone_from(&(**source));
543     }
544 }
545
546
547 #[stable(feature = "box_slice_clone", since = "1.3.0")]
548 impl Clone for Box<str> {
549     fn clone(&self) -> Self {
550         // this makes a copy of the data
551         let buf: Box<[u8]> = self.as_bytes().into();
552         unsafe {
553             from_boxed_utf8_unchecked(buf)
554         }
555     }
556 }
557
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
560     #[inline]
561     fn eq(&self, other: &Box<T>) -> bool {
562         PartialEq::eq(&**self, &**other)
563     }
564     #[inline]
565     fn ne(&self, other: &Box<T>) -> bool {
566         PartialEq::ne(&**self, &**other)
567     }
568 }
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
571     #[inline]
572     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
573         PartialOrd::partial_cmp(&**self, &**other)
574     }
575     #[inline]
576     fn lt(&self, other: &Box<T>) -> bool {
577         PartialOrd::lt(&**self, &**other)
578     }
579     #[inline]
580     fn le(&self, other: &Box<T>) -> bool {
581         PartialOrd::le(&**self, &**other)
582     }
583     #[inline]
584     fn ge(&self, other: &Box<T>) -> bool {
585         PartialOrd::ge(&**self, &**other)
586     }
587     #[inline]
588     fn gt(&self, other: &Box<T>) -> bool {
589         PartialOrd::gt(&**self, &**other)
590     }
591 }
592 #[stable(feature = "rust1", since = "1.0.0")]
593 impl<T: ?Sized + Ord> Ord for Box<T> {
594     #[inline]
595     fn cmp(&self, other: &Box<T>) -> Ordering {
596         Ord::cmp(&**self, &**other)
597     }
598 }
599 #[stable(feature = "rust1", since = "1.0.0")]
600 impl<T: ?Sized + Eq> Eq for Box<T> {}
601
602 #[stable(feature = "rust1", since = "1.0.0")]
603 impl<T: ?Sized + Hash> Hash for Box<T> {
604     fn hash<H: Hasher>(&self, state: &mut H) {
605         (**self).hash(state);
606     }
607 }
608
609 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
610 impl<T: ?Sized + Hasher> Hasher for Box<T> {
611     fn finish(&self) -> u64 {
612         (**self).finish()
613     }
614     fn write(&mut self, bytes: &[u8]) {
615         (**self).write(bytes)
616     }
617     fn write_u8(&mut self, i: u8) {
618         (**self).write_u8(i)
619     }
620     fn write_u16(&mut self, i: u16) {
621         (**self).write_u16(i)
622     }
623     fn write_u32(&mut self, i: u32) {
624         (**self).write_u32(i)
625     }
626     fn write_u64(&mut self, i: u64) {
627         (**self).write_u64(i)
628     }
629     fn write_u128(&mut self, i: u128) {
630         (**self).write_u128(i)
631     }
632     fn write_usize(&mut self, i: usize) {
633         (**self).write_usize(i)
634     }
635     fn write_i8(&mut self, i: i8) {
636         (**self).write_i8(i)
637     }
638     fn write_i16(&mut self, i: i16) {
639         (**self).write_i16(i)
640     }
641     fn write_i32(&mut self, i: i32) {
642         (**self).write_i32(i)
643     }
644     fn write_i64(&mut self, i: i64) {
645         (**self).write_i64(i)
646     }
647     fn write_i128(&mut self, i: i128) {
648         (**self).write_i128(i)
649     }
650     fn write_isize(&mut self, i: isize) {
651         (**self).write_isize(i)
652     }
653 }
654
655 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
656 impl<T> From<T> for Box<T> {
657     /// Converts a generic type `T` into a `Box<T>`
658     ///
659     /// The conversion allocates on the heap and moves `t`
660     /// from the stack into it.
661     ///
662     /// # Examples
663     /// ```rust
664     /// let x = 5;
665     /// let boxed = Box::new(5);
666     ///
667     /// assert_eq!(Box::from(x), boxed);
668     /// ```
669     fn from(t: T) -> Self {
670         Box::new(t)
671     }
672 }
673
674 #[stable(feature = "pin", since = "1.33.0")]
675 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
676     /// Converts a `Box<T>` into a `Pin<Box<T>>`
677     ///
678     /// This conversion does not allocate on the heap and happens in place.
679     fn from(boxed: Box<T>) -> Self {
680         Box::into_pin(boxed)
681     }
682 }
683
684 #[stable(feature = "box_from_slice", since = "1.17.0")]
685 impl<T: Copy> From<&[T]> for Box<[T]> {
686     /// Converts a `&[T]` into a `Box<[T]>`
687     ///
688     /// This conversion allocates on the heap
689     /// and performs a copy of `slice`.
690     ///
691     /// # Examples
692     /// ```rust
693     /// // create a &[u8] which will be used to create a Box<[u8]>
694     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
695     /// let boxed_slice: Box<[u8]> = Box::from(slice);
696     ///
697     /// println!("{:?}", boxed_slice);
698     /// ```
699     fn from(slice: &[T]) -> Box<[T]> {
700         let len = slice.len();
701         let buf = RawVec::with_capacity(len);
702         unsafe {
703             ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
704             buf.into_box()
705         }
706     }
707 }
708
709 #[stable(feature = "box_from_slice", since = "1.17.0")]
710 impl From<&str> for Box<str> {
711     /// Converts a `&str` into a `Box<str>`
712     ///
713     /// This conversion allocates on the heap
714     /// and performs a copy of `s`.
715     ///
716     /// # Examples
717     /// ```rust
718     /// let boxed: Box<str> = Box::from("hello");
719     /// println!("{}", boxed);
720     /// ```
721     #[inline]
722     fn from(s: &str) -> Box<str> {
723         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
724     }
725 }
726
727 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
728 impl From<Box<str>> for Box<[u8]> {
729     /// Converts a `Box<str>>` into a `Box<[u8]>`
730     ///
731     /// This conversion does not allocate on the heap and happens in place.
732     ///
733     /// # Examples
734     /// ```rust
735     /// // create a Box<str> which will be used to create a Box<[u8]>
736     /// let boxed: Box<str> = Box::from("hello");
737     /// let boxed_str: Box<[u8]> = Box::from(boxed);
738     ///
739     /// // create a &[u8] which will be used to create a Box<[u8]>
740     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
741     /// let boxed_slice = Box::from(slice);
742     ///
743     /// assert_eq!(boxed_slice, boxed_str);
744     /// ```
745     #[inline]
746     fn from(s: Box<str>) -> Self {
747         unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
748     }
749 }
750
751 #[unstable(feature = "boxed_slice_try_from", issue = "0")]
752 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]>
753 where
754     [T; N]: LengthAtMost32,
755 {
756     type Error = Box<[T]>;
757
758     fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
759         if boxed_slice.len() == N {
760             Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
761         } else {
762             Err(boxed_slice)
763         }
764     }
765 }
766
767 impl Box<dyn Any> {
768     #[inline]
769     #[stable(feature = "rust1", since = "1.0.0")]
770     /// Attempt to downcast the box to a concrete type.
771     ///
772     /// # Examples
773     ///
774     /// ```
775     /// use std::any::Any;
776     ///
777     /// fn print_if_string(value: Box<dyn Any>) {
778     ///     if let Ok(string) = value.downcast::<String>() {
779     ///         println!("String ({}): {}", string.len(), string);
780     ///     }
781     /// }
782     ///
783     /// fn main() {
784     ///     let my_string = "Hello World".to_string();
785     ///     print_if_string(Box::new(my_string));
786     ///     print_if_string(Box::new(0i8));
787     /// }
788     /// ```
789     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
790         if self.is::<T>() {
791             unsafe {
792                 let raw: *mut dyn Any = Box::into_raw(self);
793                 Ok(Box::from_raw(raw as *mut T))
794             }
795         } else {
796             Err(self)
797         }
798     }
799 }
800
801 impl Box<dyn Any + Send> {
802     #[inline]
803     #[stable(feature = "rust1", since = "1.0.0")]
804     /// Attempt to downcast the box to a concrete type.
805     ///
806     /// # Examples
807     ///
808     /// ```
809     /// use std::any::Any;
810     ///
811     /// fn print_if_string(value: Box<dyn Any + Send>) {
812     ///     if let Ok(string) = value.downcast::<String>() {
813     ///         println!("String ({}): {}", string.len(), string);
814     ///     }
815     /// }
816     ///
817     /// fn main() {
818     ///     let my_string = "Hello World".to_string();
819     ///     print_if_string(Box::new(my_string));
820     ///     print_if_string(Box::new(0i8));
821     /// }
822     /// ```
823     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
824         <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
825             // reapply the Send marker
826             Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
827         })
828     }
829 }
830
831 #[stable(feature = "rust1", since = "1.0.0")]
832 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
833     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
834         fmt::Display::fmt(&**self, f)
835     }
836 }
837
838 #[stable(feature = "rust1", since = "1.0.0")]
839 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
840     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
841         fmt::Debug::fmt(&**self, f)
842     }
843 }
844
845 #[stable(feature = "rust1", since = "1.0.0")]
846 impl<T: ?Sized> fmt::Pointer for Box<T> {
847     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
848         // It's not possible to extract the inner Uniq directly from the Box,
849         // instead we cast it to a *const which aliases the Unique
850         let ptr: *const T = &**self;
851         fmt::Pointer::fmt(&ptr, f)
852     }
853 }
854
855 #[stable(feature = "rust1", since = "1.0.0")]
856 impl<T: ?Sized> Deref for Box<T> {
857     type Target = T;
858
859     fn deref(&self) -> &T {
860         &**self
861     }
862 }
863
864 #[stable(feature = "rust1", since = "1.0.0")]
865 impl<T: ?Sized> DerefMut for Box<T> {
866     fn deref_mut(&mut self) -> &mut T {
867         &mut **self
868     }
869 }
870
871 #[unstable(feature = "receiver_trait", issue = "0")]
872 impl<T: ?Sized> Receiver for Box<T> {}
873
874 #[stable(feature = "rust1", since = "1.0.0")]
875 impl<I: Iterator + ?Sized> Iterator for Box<I> {
876     type Item = I::Item;
877     fn next(&mut self) -> Option<I::Item> {
878         (**self).next()
879     }
880     fn size_hint(&self) -> (usize, Option<usize>) {
881         (**self).size_hint()
882     }
883     fn nth(&mut self, n: usize) -> Option<I::Item> {
884         (**self).nth(n)
885     }
886 }
887
888 #[stable(feature = "rust1", since = "1.0.0")]
889 impl<I: Iterator + Sized> Iterator for Box<I> {
890     fn last(self) -> Option<I::Item> where I: Sized {
891         (*self).last()
892     }
893 }
894
895 #[stable(feature = "rust1", since = "1.0.0")]
896 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
897     fn next_back(&mut self) -> Option<I::Item> {
898         (**self).next_back()
899     }
900     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
901         (**self).nth_back(n)
902     }
903 }
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
906     fn len(&self) -> usize {
907         (**self).len()
908     }
909     fn is_empty(&self) -> bool {
910         (**self).is_empty()
911     }
912 }
913
914 #[stable(feature = "fused", since = "1.26.0")]
915 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
916
917 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
918 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
919     type Output = <F as FnOnce<A>>::Output;
920
921     extern "rust-call" fn call_once(self, args: A) -> Self::Output {
922         <F as FnOnce<A>>::call_once(*self, args)
923     }
924 }
925
926 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
927 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
928     extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
929         <F as FnMut<A>>::call_mut(self, args)
930     }
931 }
932
933 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
934 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
935     extern "rust-call" fn call(&self, args: A) -> Self::Output {
936         <F as Fn<A>>::call(self, args)
937     }
938 }
939
940 #[unstable(feature = "coerce_unsized", issue = "27732")]
941 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
942
943 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
944 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
945
946 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
947 impl<A> FromIterator<A> for Box<[A]> {
948     fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
949         iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
950     }
951 }
952
953 #[stable(feature = "box_slice_clone", since = "1.3.0")]
954 impl<T: Clone> Clone for Box<[T]> {
955     fn clone(&self) -> Self {
956         let mut new = BoxBuilder {
957             data: RawVec::with_capacity(self.len()),
958             len: 0,
959         };
960
961         let mut target = new.data.ptr();
962
963         for item in self.iter() {
964             unsafe {
965                 ptr::write(target, item.clone());
966                 target = target.offset(1);
967             };
968
969             new.len += 1;
970         }
971
972         return unsafe { new.into_box() };
973
974         // Helper type for responding to panics correctly.
975         struct BoxBuilder<T> {
976             data: RawVec<T>,
977             len: usize,
978         }
979
980         impl<T> BoxBuilder<T> {
981             unsafe fn into_box(self) -> Box<[T]> {
982                 let raw = ptr::read(&self.data);
983                 mem::forget(self);
984                 raw.into_box()
985             }
986         }
987
988         impl<T> Drop for BoxBuilder<T> {
989             fn drop(&mut self) {
990                 let mut data = self.data.ptr();
991                 let max = unsafe { data.add(self.len) };
992
993                 while data != max {
994                     unsafe {
995                         ptr::read(data);
996                         data = data.offset(1);
997                     }
998                 }
999             }
1000         }
1001     }
1002 }
1003
1004 #[stable(feature = "box_borrow", since = "1.1.0")]
1005 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
1006     fn borrow(&self) -> &T {
1007         &**self
1008     }
1009 }
1010
1011 #[stable(feature = "box_borrow", since = "1.1.0")]
1012 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
1013     fn borrow_mut(&mut self) -> &mut T {
1014         &mut **self
1015     }
1016 }
1017
1018 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1019 impl<T: ?Sized> AsRef<T> for Box<T> {
1020     fn as_ref(&self) -> &T {
1021         &**self
1022     }
1023 }
1024
1025 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1026 impl<T: ?Sized> AsMut<T> for Box<T> {
1027     fn as_mut(&mut self) -> &mut T {
1028         &mut **self
1029     }
1030 }
1031
1032 /* Nota bene
1033  *
1034  *  We could have chosen not to add this impl, and instead have written a
1035  *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1036  *  because Box<T> implements Unpin even when T does not, as a result of
1037  *  this impl.
1038  *
1039  *  We chose this API instead of the alternative for a few reasons:
1040  *      - Logically, it is helpful to understand pinning in regard to the
1041  *        memory region being pointed to. For this reason none of the
1042  *        standard library pointer types support projecting through a pin
1043  *        (Box<T> is the only pointer type in std for which this would be
1044  *        safe.)
1045  *      - It is in practice very useful to have Box<T> be unconditionally
1046  *        Unpin because of trait objects, for which the structural auto
1047  *        trait functionality does not apply (e.g., Box<dyn Foo> would
1048  *        otherwise not be Unpin).
1049  *
1050  *  Another type with the same semantics as Box but only a conditional
1051  *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1052  *  could have a method to project a Pin<T> from it.
1053  */
1054 #[stable(feature = "pin", since = "1.33.0")]
1055 impl<T: ?Sized> Unpin for Box<T> { }
1056
1057 #[unstable(feature = "generator_trait", issue = "43122")]
1058 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
1059     type Yield = G::Yield;
1060     type Return = G::Return;
1061
1062     fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
1063         G::resume(Pin::new(&mut *self))
1064     }
1065 }
1066
1067 #[unstable(feature = "generator_trait", issue = "43122")]
1068 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
1069     type Yield = G::Yield;
1070     type Return = G::Return;
1071
1072     fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
1073         G::resume((*self).as_mut())
1074     }
1075 }
1076
1077 #[stable(feature = "futures_api", since = "1.36.0")]
1078 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
1079     type Output = F::Output;
1080
1081     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1082         F::poll(Pin::new(&mut *self), cx)
1083     }
1084 }