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