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