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