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