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