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