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