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