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