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