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