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