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