]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
Auto merge of #41433 - estebank:constructor, r=michaelwoerister
[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 //! ```rust,ignore
46 //! Cons(T, List<T>),
47 //! ```
48 //!
49 //! It wouldn't work. This is because the size of a `List` depends on how many
50 //! elements are in the list, and so we don't know how much memory to allocate
51 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
52 //! big `Cons` needs to be.
53
54 #![stable(feature = "rust1", since = "1.0.0")]
55
56 use heap;
57 use raw_vec::RawVec;
58
59 use core::any::Any;
60 use core::borrow;
61 use core::cmp::Ordering;
62 use core::fmt;
63 use core::hash::{self, Hash};
64 use core::iter::FusedIterator;
65 use core::marker::{self, Unsize};
66 use core::mem;
67 use core::ops::{CoerceUnsized, Deref, DerefMut};
68 use core::ops::{BoxPlace, Boxed, InPlace, Place, Placer};
69 use core::ptr::{self, Unique};
70 use core::convert::From;
71 use str::from_boxed_utf8_unchecked;
72
73 /// A value that represents the heap. This is the default place that the `box`
74 /// keyword allocates into when no place is supplied.
75 ///
76 /// The following two examples are equivalent:
77 ///
78 /// ```
79 /// #![feature(box_heap)]
80 ///
81 /// #![feature(box_syntax, placement_in_syntax)]
82 /// use std::boxed::HEAP;
83 ///
84 /// fn main() {
85 ///     let foo: Box<i32> = in HEAP { 5 };
86 ///     let foo = box 5;
87 /// }
88 /// ```
89 #[unstable(feature = "box_heap",
90            reason = "may be renamed; uncertain about custom allocator design",
91            issue = "27779")]
92 pub const HEAP: ExchangeHeapSingleton = ExchangeHeapSingleton { _force_singleton: () };
93
94 /// This the singleton type used solely for `boxed::HEAP`.
95 #[unstable(feature = "box_heap",
96            reason = "may be renamed; uncertain about custom allocator design",
97            issue = "27779")]
98 #[derive(Copy, Clone)]
99 pub struct ExchangeHeapSingleton {
100     _force_singleton: (),
101 }
102
103 /// A pointer type for heap allocation.
104 ///
105 /// See the [module-level documentation](../../std/boxed/index.html) for more.
106 #[lang = "owned_box"]
107 #[fundamental]
108 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct Box<T: ?Sized>(Unique<T>);
110
111 /// `IntermediateBox` represents uninitialized backing storage for `Box`.
112 ///
113 /// FIXME (pnkfelix): Ideally we would just reuse `Box<T>` instead of
114 /// introducing a separate `IntermediateBox<T>`; but then you hit
115 /// issues when you e.g. attempt to destructure an instance of `Box`,
116 /// since it is a lang item and so it gets special handling by the
117 /// compiler.  Easier just to make this parallel type for now.
118 ///
119 /// FIXME (pnkfelix): Currently the `box` protocol only supports
120 /// creating instances of sized types. This IntermediateBox is
121 /// designed to be forward-compatible with a future protocol that
122 /// supports creating instances of unsized types; that is why the type
123 /// parameter has the `?Sized` generalization marker, and is also why
124 /// this carries an explicit size. However, it probably does not need
125 /// to carry the explicit alignment; that is just a work-around for
126 /// the fact that the `align_of` intrinsic currently requires the
127 /// input type to be Sized (which I do not think is strictly
128 /// necessary).
129 #[unstable(feature = "placement_in",
130            reason = "placement box design is still being worked out.",
131            issue = "27779")]
132 pub struct IntermediateBox<T: ?Sized> {
133     ptr: *mut u8,
134     size: usize,
135     align: usize,
136     marker: marker::PhantomData<*mut T>,
137 }
138
139 #[unstable(feature = "placement_in",
140            reason = "placement box design is still being worked out.",
141            issue = "27779")]
142 impl<T> Place<T> for IntermediateBox<T> {
143     fn pointer(&mut self) -> *mut T {
144         self.ptr as *mut T
145     }
146 }
147
148 unsafe fn finalize<T>(b: IntermediateBox<T>) -> Box<T> {
149     let p = b.ptr as *mut T;
150     mem::forget(b);
151     mem::transmute(p)
152 }
153
154 fn make_place<T>() -> IntermediateBox<T> {
155     let size = mem::size_of::<T>();
156     let align = mem::align_of::<T>();
157
158     let p = if size == 0 {
159         heap::EMPTY as *mut u8
160     } else {
161         let p = unsafe { heap::allocate(size, align) };
162         if p.is_null() {
163             panic!("Box make_place allocation failure.");
164         }
165         p
166     };
167
168     IntermediateBox {
169         ptr: p,
170         size: size,
171         align: align,
172         marker: marker::PhantomData,
173     }
174 }
175
176 #[unstable(feature = "placement_in",
177            reason = "placement box design is still being worked out.",
178            issue = "27779")]
179 impl<T> BoxPlace<T> for IntermediateBox<T> {
180     fn make_place() -> IntermediateBox<T> {
181         make_place()
182     }
183 }
184
185 #[unstable(feature = "placement_in",
186            reason = "placement box design is still being worked out.",
187            issue = "27779")]
188 impl<T> InPlace<T> for IntermediateBox<T> {
189     type Owner = Box<T>;
190     unsafe fn finalize(self) -> Box<T> {
191         finalize(self)
192     }
193 }
194
195 #[unstable(feature = "placement_new_protocol", issue = "27779")]
196 impl<T> Boxed for Box<T> {
197     type Data = T;
198     type Place = IntermediateBox<T>;
199     unsafe fn finalize(b: IntermediateBox<T>) -> Box<T> {
200         finalize(b)
201     }
202 }
203
204 #[unstable(feature = "placement_in",
205            reason = "placement box design is still being worked out.",
206            issue = "27779")]
207 impl<T> Placer<T> for ExchangeHeapSingleton {
208     type Place = IntermediateBox<T>;
209
210     fn make_place(self) -> IntermediateBox<T> {
211         make_place()
212     }
213 }
214
215 #[unstable(feature = "placement_in",
216            reason = "placement box design is still being worked out.",
217            issue = "27779")]
218 impl<T: ?Sized> Drop for IntermediateBox<T> {
219     fn drop(&mut self) {
220         if self.size > 0 {
221             unsafe { heap::deallocate(self.ptr, self.size, self.align) }
222         }
223     }
224 }
225
226 impl<T> Box<T> {
227     /// Allocates memory on the heap and then places `x` into it.
228     ///
229     /// This doesn't actually allocate if `T` is zero-sized.
230     ///
231     /// # Examples
232     ///
233     /// ```
234     /// let five = Box::new(5);
235     /// ```
236     #[stable(feature = "rust1", since = "1.0.0")]
237     #[inline(always)]
238     pub fn new(x: T) -> Box<T> {
239         box x
240     }
241 }
242
243 impl<T: ?Sized> Box<T> {
244     /// Constructs a box from a raw pointer.
245     ///
246     /// After calling this function, the raw pointer is owned by the
247     /// resulting `Box`. Specifically, the `Box` destructor will call
248     /// the destructor of `T` and free the allocated memory. Since the
249     /// way `Box` allocates and releases memory is unspecified, the
250     /// only valid pointer to pass to this function is the one taken
251     /// from another `Box` via the [`Box::into_raw`] function.
252     ///
253     /// This function is unsafe because improper use may lead to
254     /// memory problems. For example, a double-free may occur if the
255     /// function is called twice on the same raw pointer.
256     ///
257     /// [`Box::into_raw`]: struct.Box.html#method.into_raw
258     ///
259     /// # Examples
260     ///
261     /// ```
262     /// let x = Box::new(5);
263     /// let ptr = Box::into_raw(x);
264     /// let x = unsafe { Box::from_raw(ptr) };
265     /// ```
266     #[stable(feature = "box_raw", since = "1.4.0")]
267     #[inline]
268     pub unsafe fn from_raw(raw: *mut T) -> Self {
269         mem::transmute(raw)
270     }
271
272     /// Consumes the `Box`, returning the wrapped raw pointer.
273     ///
274     /// After calling this function, the caller is responsible for the
275     /// memory previously managed by the `Box`. In particular, the
276     /// caller should properly destroy `T` and release the memory. The
277     /// proper way to do so is to convert the raw pointer back into a
278     /// `Box` with the [`Box::from_raw`] function.
279     ///
280     /// Note: this is an associated function, which means that you have
281     /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
282     /// is so that there is no conflict with a method on the inner type.
283     ///
284     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
285     ///
286     /// # Examples
287     ///
288     /// ```
289     /// let x = Box::new(5);
290     /// let ptr = Box::into_raw(x);
291     /// ```
292     #[stable(feature = "box_raw", since = "1.4.0")]
293     #[inline]
294     pub fn into_raw(b: Box<T>) -> *mut T {
295         unsafe { mem::transmute(b) }
296     }
297 }
298
299 #[stable(feature = "rust1", since = "1.0.0")]
300 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
301     fn drop(&mut self) {
302         // FIXME: Do nothing, drop is currently performed by compiler.
303     }
304 }
305
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T: Default> Default for Box<T> {
308     /// Creates a `Box<T>`, with the `Default` value for T.
309     fn default() -> Box<T> {
310         box Default::default()
311     }
312 }
313
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<T> Default for Box<[T]> {
316     fn default() -> Box<[T]> {
317         Box::<[T; 0]>::new([])
318     }
319 }
320
321 #[stable(feature = "default_box_extra", since = "1.17.0")]
322 impl Default for Box<str> {
323     fn default() -> Box<str> {
324         unsafe { from_boxed_utf8_unchecked(Default::default()) }
325     }
326 }
327
328 #[stable(feature = "rust1", since = "1.0.0")]
329 impl<T: Clone> Clone for Box<T> {
330     /// Returns a new box with a `clone()` of this box's contents.
331     ///
332     /// # Examples
333     ///
334     /// ```
335     /// let x = Box::new(5);
336     /// let y = x.clone();
337     /// ```
338     #[rustfmt_skip]
339     #[inline]
340     fn clone(&self) -> Box<T> {
341         box { (**self).clone() }
342     }
343     /// Copies `source`'s contents into `self` without creating a new allocation.
344     ///
345     /// # Examples
346     ///
347     /// ```
348     /// let x = Box::new(5);
349     /// let mut y = Box::new(10);
350     ///
351     /// y.clone_from(&x);
352     ///
353     /// assert_eq!(*y, 5);
354     /// ```
355     #[inline]
356     fn clone_from(&mut self, source: &Box<T>) {
357         (**self).clone_from(&(**source));
358     }
359 }
360
361
362 #[stable(feature = "box_slice_clone", since = "1.3.0")]
363 impl Clone for Box<str> {
364     fn clone(&self) -> Self {
365         let len = self.len();
366         let buf = RawVec::with_capacity(len);
367         unsafe {
368             ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
369             from_boxed_utf8_unchecked(buf.into_box())
370         }
371     }
372 }
373
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
376     #[inline]
377     fn eq(&self, other: &Box<T>) -> bool {
378         PartialEq::eq(&**self, &**other)
379     }
380     #[inline]
381     fn ne(&self, other: &Box<T>) -> bool {
382         PartialEq::ne(&**self, &**other)
383     }
384 }
385 #[stable(feature = "rust1", since = "1.0.0")]
386 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
387     #[inline]
388     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
389         PartialOrd::partial_cmp(&**self, &**other)
390     }
391     #[inline]
392     fn lt(&self, other: &Box<T>) -> bool {
393         PartialOrd::lt(&**self, &**other)
394     }
395     #[inline]
396     fn le(&self, other: &Box<T>) -> bool {
397         PartialOrd::le(&**self, &**other)
398     }
399     #[inline]
400     fn ge(&self, other: &Box<T>) -> bool {
401         PartialOrd::ge(&**self, &**other)
402     }
403     #[inline]
404     fn gt(&self, other: &Box<T>) -> bool {
405         PartialOrd::gt(&**self, &**other)
406     }
407 }
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<T: ?Sized + Ord> Ord for Box<T> {
410     #[inline]
411     fn cmp(&self, other: &Box<T>) -> Ordering {
412         Ord::cmp(&**self, &**other)
413     }
414 }
415 #[stable(feature = "rust1", since = "1.0.0")]
416 impl<T: ?Sized + Eq> Eq for Box<T> {}
417
418 #[stable(feature = "rust1", since = "1.0.0")]
419 impl<T: ?Sized + Hash> Hash for Box<T> {
420     fn hash<H: hash::Hasher>(&self, state: &mut H) {
421         (**self).hash(state);
422     }
423 }
424
425 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
426 impl<T> From<T> for Box<T> {
427     fn from(t: T) -> Self {
428         Box::new(t)
429     }
430 }
431
432 #[stable(feature = "box_from_slice", since = "1.17.0")]
433 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
434     fn from(slice: &'a [T]) -> Box<[T]> {
435         let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
436         boxed.copy_from_slice(slice);
437         boxed
438     }
439 }
440
441 #[stable(feature = "box_from_slice", since = "1.17.0")]
442 impl<'a> From<&'a str> for Box<str> {
443     fn from(s: &'a str) -> Box<str> {
444         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
445     }
446 }
447
448 #[stable(feature = "boxed_str_conv", since = "1.18.0")]
449 impl From<Box<str>> for Box<[u8]> {
450     fn from(s: Box<str>) -> Self {
451         unsafe {
452             mem::transmute(s)
453         }
454     }
455 }
456
457 impl Box<Any> {
458     #[inline]
459     #[stable(feature = "rust1", since = "1.0.0")]
460     /// Attempt to downcast the box to a concrete type.
461     ///
462     /// # Examples
463     ///
464     /// ```
465     /// use std::any::Any;
466     ///
467     /// fn print_if_string(value: Box<Any>) {
468     ///     if let Ok(string) = value.downcast::<String>() {
469     ///         println!("String ({}): {}", string.len(), string);
470     ///     }
471     /// }
472     ///
473     /// fn main() {
474     ///     let my_string = "Hello World".to_string();
475     ///     print_if_string(Box::new(my_string));
476     ///     print_if_string(Box::new(0i8));
477     /// }
478     /// ```
479     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
480         if self.is::<T>() {
481             unsafe {
482                 let raw: *mut Any = Box::into_raw(self);
483                 Ok(Box::from_raw(raw as *mut T))
484             }
485         } else {
486             Err(self)
487         }
488     }
489 }
490
491 impl Box<Any + Send> {
492     #[inline]
493     #[stable(feature = "rust1", since = "1.0.0")]
494     /// Attempt to downcast the box to a concrete type.
495     ///
496     /// # Examples
497     ///
498     /// ```
499     /// use std::any::Any;
500     ///
501     /// fn print_if_string(value: Box<Any + Send>) {
502     ///     if let Ok(string) = value.downcast::<String>() {
503     ///         println!("String ({}): {}", string.len(), string);
504     ///     }
505     /// }
506     ///
507     /// fn main() {
508     ///     let my_string = "Hello World".to_string();
509     ///     print_if_string(Box::new(my_string));
510     ///     print_if_string(Box::new(0i8));
511     /// }
512     /// ```
513     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
514         <Box<Any>>::downcast(self).map_err(|s| unsafe {
515             // reapply the Send marker
516             mem::transmute::<Box<Any>, Box<Any + Send>>(s)
517         })
518     }
519 }
520
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
523     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
524         fmt::Display::fmt(&**self, f)
525     }
526 }
527
528 #[stable(feature = "rust1", since = "1.0.0")]
529 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
530     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
531         fmt::Debug::fmt(&**self, f)
532     }
533 }
534
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl<T: ?Sized> fmt::Pointer for Box<T> {
537     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
538         // It's not possible to extract the inner Uniq directly from the Box,
539         // instead we cast it to a *const which aliases the Unique
540         let ptr: *const T = &**self;
541         fmt::Pointer::fmt(&ptr, f)
542     }
543 }
544
545 #[stable(feature = "rust1", since = "1.0.0")]
546 impl<T: ?Sized> Deref for Box<T> {
547     type Target = T;
548
549     fn deref(&self) -> &T {
550         &**self
551     }
552 }
553
554 #[stable(feature = "rust1", since = "1.0.0")]
555 impl<T: ?Sized> DerefMut for Box<T> {
556     fn deref_mut(&mut self) -> &mut T {
557         &mut **self
558     }
559 }
560
561 #[stable(feature = "rust1", since = "1.0.0")]
562 impl<I: Iterator + ?Sized> Iterator for Box<I> {
563     type Item = I::Item;
564     fn next(&mut self) -> Option<I::Item> {
565         (**self).next()
566     }
567     fn size_hint(&self) -> (usize, Option<usize>) {
568         (**self).size_hint()
569     }
570     fn nth(&mut self, n: usize) -> Option<I::Item> {
571         (**self).nth(n)
572     }
573 }
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
576     fn next_back(&mut self) -> Option<I::Item> {
577         (**self).next_back()
578     }
579 }
580 #[stable(feature = "rust1", since = "1.0.0")]
581 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
582     fn len(&self) -> usize {
583         (**self).len()
584     }
585     fn is_empty(&self) -> bool {
586         (**self).is_empty()
587     }
588 }
589
590 #[unstable(feature = "fused", issue = "35602")]
591 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
592
593
594 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
595 /// closure objects. The idea is that where one would normally store a
596 /// `Box<FnOnce()>` in a data structure, you should use
597 /// `Box<FnBox()>`. The two traits behave essentially the same, except
598 /// that a `FnBox` closure can only be called if it is boxed. (Note
599 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
600 /// closures become directly usable.)
601 ///
602 /// ### Example
603 ///
604 /// Here is a snippet of code which creates a hashmap full of boxed
605 /// once closures and then removes them one by one, calling each
606 /// closure as it is removed. Note that the type of the closures
607 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
608 /// -> i32>`.
609 ///
610 /// ```
611 /// #![feature(fnbox)]
612 ///
613 /// use std::boxed::FnBox;
614 /// use std::collections::HashMap;
615 ///
616 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
617 ///     let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
618 ///     map.insert(1, Box::new(|| 22));
619 ///     map.insert(2, Box::new(|| 44));
620 ///     map
621 /// }
622 ///
623 /// fn main() {
624 ///     let mut map = make_map();
625 ///     for i in &[1, 2] {
626 ///         let f = map.remove(&i).unwrap();
627 ///         assert_eq!(f(), i * 22);
628 ///     }
629 /// }
630 /// ```
631 #[rustc_paren_sugar]
632 #[unstable(feature = "fnbox",
633            reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
634 pub trait FnBox<A> {
635     type Output;
636
637     fn call_box(self: Box<Self>, args: A) -> Self::Output;
638 }
639
640 #[unstable(feature = "fnbox",
641            reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
642 impl<A, F> FnBox<A> for F
643     where F: FnOnce<A>
644 {
645     type Output = F::Output;
646
647     fn call_box(self: Box<F>, args: A) -> F::Output {
648         self.call_once(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> + '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 = "fnbox",
663            reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
664 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + Send + 'a> {
665     type Output = R;
666
667     extern "rust-call" fn call_once(self, args: A) -> R {
668         self.call_box(args)
669     }
670 }
671
672 #[unstable(feature = "coerce_unsized", issue = "27732")]
673 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
674
675 #[stable(feature = "box_slice_clone", since = "1.3.0")]
676 impl<T: Clone> Clone for Box<[T]> {
677     fn clone(&self) -> Self {
678         let mut new = BoxBuilder {
679             data: RawVec::with_capacity(self.len()),
680             len: 0,
681         };
682
683         let mut target = new.data.ptr();
684
685         for item in self.iter() {
686             unsafe {
687                 ptr::write(target, item.clone());
688                 target = target.offset(1);
689             };
690
691             new.len += 1;
692         }
693
694         return unsafe { new.into_box() };
695
696         // Helper type for responding to panics correctly.
697         struct BoxBuilder<T> {
698             data: RawVec<T>,
699             len: usize,
700         }
701
702         impl<T> BoxBuilder<T> {
703             unsafe fn into_box(self) -> Box<[T]> {
704                 let raw = ptr::read(&self.data);
705                 mem::forget(self);
706                 raw.into_box()
707             }
708         }
709
710         impl<T> Drop for BoxBuilder<T> {
711             fn drop(&mut self) {
712                 let mut data = self.data.ptr();
713                 let max = unsafe { data.offset(self.len as isize) };
714
715                 while data != max {
716                     unsafe {
717                         ptr::read(data);
718                         data = data.offset(1);
719                     }
720                 }
721             }
722         }
723     }
724 }
725
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
728     fn borrow(&self) -> &T {
729         &**self
730     }
731 }
732
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
735     fn borrow_mut(&mut self) -> &mut T {
736         &mut **self
737     }
738 }
739
740 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
741 impl<T: ?Sized> AsRef<T> for Box<T> {
742     fn as_ref(&self) -> &T {
743         &**self
744     }
745 }
746
747 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
748 impl<T: ?Sized> AsMut<T> for Box<T> {
749     fn as_mut(&mut self) -> &mut T {
750         &mut **self
751     }
752 }