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