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.
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.
11 //! A unique pointer type.
16 use core::clone::Clone;
17 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
18 use core::default::Default;
20 use core::hash::{self, Hash};
21 use core::iter::Iterator;
22 use core::marker::Sized;
24 use core::option::Option;
25 use core::ptr::Unique;
26 use core::raw::TraitObject;
27 use core::result::Result;
28 use core::result::Result::{Ok, Err};
29 use core::ops::{Deref, DerefMut};
31 /// A value that represents the global exchange heap. This is the default
32 /// place that the `box` keyword allocates into when no place is supplied.
34 /// The following two examples are equivalent:
37 /// #![feature(box_syntax)]
38 /// use std::boxed::HEAP;
42 /// # impl Bar { fn new(_a: int) { } }
43 /// let foo = box(HEAP) Bar::new(2);
44 /// let foo = box Bar::new(2);
47 #[lang = "exchange_heap"]
48 #[unstable = "may be renamed; uncertain about custom allocator design"]
49 pub static HEAP: () = ();
51 /// A type that represents a uniquely-owned value.
54 pub struct Box<T>(Unique<T>);
57 /// Moves `x` into a freshly allocated box on the global exchange heap.
59 pub fn new(x: T) -> Box<T> {
65 impl<T: Default> Default for Box<T> {
67 fn default() -> Box<T> { box Default::default() }
71 impl<T> Default for Box<[T]> {
73 fn default() -> Box<[T]> { box [] }
77 impl<T: Clone> Clone for Box<T> {
78 /// Returns a copy of the owned box.
80 fn clone(&self) -> Box<T> { box {(**self).clone()} }
82 /// Performs copy-assignment from `source` by reusing the existing allocation.
84 fn clone_from(&mut self, source: &Box<T>) {
85 (**self).clone_from(&(**source));
90 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
92 fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
94 fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
97 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
99 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
100 PartialOrd::partial_cmp(&**self, &**other)
103 fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
105 fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
107 fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
109 fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
112 impl<T: ?Sized + Ord> Ord for Box<T> {
114 fn cmp(&self, other: &Box<T>) -> Ordering {
115 Ord::cmp(&**self, &**other)
119 impl<T: ?Sized + Eq> Eq for Box<T> {}
121 impl<S: hash::Hasher, T: ?Sized + Hash<S>> Hash<S> for Box<T> {
123 fn hash(&self, state: &mut S) {
124 (**self).hash(state);
128 /// Extension methods for an owning `Any` trait object.
129 #[unstable = "post-DST and coherence changes, this will not be a trait but \
130 rather a direct `impl` on `Box<Any>`"]
132 /// Returns the boxed value if it is of type `T`, or
133 /// `Err(Self)` if it isn't.
135 fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
138 impl BoxAny for Box<Any> {
140 #[unstable = "method may be renamed with respect to other downcasting \
142 fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
145 // Get the raw representation of the trait object
146 let to: TraitObject =
147 mem::transmute::<Box<Any>, TraitObject>(self);
149 // Extract the data pointer
150 Ok(mem::transmute(to.data))
158 impl<T: ?Sized + fmt::Show> fmt::Show for Box<T> {
159 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
160 write!(f, "Box({:?})", &**self)
165 impl<T: ?Sized + fmt::String> fmt::String for Box<T> {
166 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
167 fmt::String::fmt(&**self, f)
171 impl fmt::Show for Box<Any> {
172 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
178 impl<T: ?Sized> Deref for Box<T> {
181 fn deref(&self) -> &T { &**self }
185 impl<T: ?Sized> DerefMut for Box<T> {
186 fn deref_mut(&mut self) -> &mut T { &mut **self }
189 // FIXME(#21363) remove `old_impl_check` when bug is fixed
191 impl<'a, T> Iterator for Box<Iterator<Item=T> + 'a> {
194 fn next(&mut self) -> Option<T> {
202 fn test_owned_clone() {
203 let a = Box::new(5i);
204 let b: Box<int> = a.clone();
210 let a = Box::new(8u) as Box<Any>;
211 let b = Box::new(Test) as Box<Any>;
213 match a.downcast::<uint>() {
214 Ok(a) => { assert!(a == Box::new(8u)); }
217 match b.downcast::<Test>() {
218 Ok(a) => { assert!(a == Box::new(Test)); }
222 let a = Box::new(8u) as Box<Any>;
223 let b = Box::new(Test) as Box<Any>;
225 assert!(a.downcast::<Box<Test>>().is_err());
226 assert!(b.downcast::<Box<uint>>().is_err());
231 let a = Box::new(8u) as Box<Any>;
232 let b = Box::new(Test) as Box<Any>;
233 let a_str = a.to_str();
234 let b_str = b.to_str();
235 assert_eq!(a_str, "Box<Any>");
236 assert_eq!(b_str, "Box<Any>");
239 let b = &Test as &Any;
240 let s = format!("{}", a);
241 assert_eq!(s, "&Any");
242 let s = format!("{}", b);
243 assert_eq!(s, "&Any");
248 fn homura<T: Deref<Target=i32>>(_: T) { }
249 homura(Box::new(765i32));