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