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::marker::Sized;
23 use core::option::Option;
24 use core::ptr::Unique;
25 use core::raw::TraitObject;
26 use core::result::Result;
27 use core::result::Result::{Ok, Err};
28 use core::ops::{Deref, DerefMut};
30 /// A value that represents the global exchange heap. This is the default
31 /// place that the `box` keyword allocates into when no place is supplied.
33 /// The following two examples are equivalent:
36 /// #![feature(box_syntax)]
37 /// use std::boxed::HEAP;
41 /// # impl Bar { fn new(_a: int) { } }
42 /// let foo = box(HEAP) Bar::new(2);
43 /// let foo = box Bar::new(2);
46 #[lang = "exchange_heap"]
47 #[unstable = "may be renamed; uncertain about custom allocator design"]
48 pub static HEAP: () = ();
50 /// A type that represents a uniquely-owned value.
53 pub struct Box<T>(Unique<T>);
56 /// Moves `x` into a freshly allocated box on the global exchange heap.
58 pub fn new(x: T) -> Box<T> {
64 impl<T: Default> Default for Box<T> {
66 fn default() -> Box<T> { box Default::default() }
70 impl<T> Default for Box<[T]> {
72 fn default() -> Box<[T]> { box [] }
76 impl<T: Clone> Clone for Box<T> {
77 /// Returns a copy of the owned box.
79 fn clone(&self) -> Box<T> { box {(**self).clone()} }
81 /// Performs copy-assignment from `source` by reusing the existing allocation.
83 fn clone_from(&mut self, source: &Box<T>) {
84 (**self).clone_from(&(**source));
89 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
91 fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
93 fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
96 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
98 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
99 PartialOrd::partial_cmp(&**self, &**other)
102 fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
104 fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
106 fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
108 fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
111 impl<T: ?Sized + Ord> Ord for Box<T> {
113 fn cmp(&self, other: &Box<T>) -> Ordering {
114 Ord::cmp(&**self, &**other)
118 impl<T: ?Sized + Eq> Eq for Box<T> {}
120 impl<S: hash::Hasher, T: ?Sized + Hash<S>> Hash<S> for Box<T> {
122 fn hash(&self, state: &mut S) {
123 (**self).hash(state);
127 /// Extension methods for an owning `Any` trait object.
128 #[unstable = "this trait will likely disappear once compiler bugs blocking \
129 a direct impl on `Box<Any>` have been fixed "]
130 // FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
131 // removing this please make sure that you can downcase on
132 // `Box<Any + Send>` as well as `Box<Any>`
134 /// Returns the boxed value if it is of type `T`, or
135 /// `Err(Self)` if it isn't.
137 fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
141 impl BoxAny for Box<Any> {
143 fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
146 // Get the raw representation of the trait object
147 let to: TraitObject =
148 mem::transmute::<Box<Any>, TraitObject>(self);
150 // Extract the data pointer
151 Ok(mem::transmute(to.data))
159 impl<T: ?Sized + fmt::Show> fmt::Show for Box<T> {
160 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
161 write!(f, "Box({:?})", &**self)
166 impl<T: ?Sized + fmt::String> fmt::String for Box<T> {
167 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
168 fmt::String::fmt(&**self, f)
172 impl fmt::Show for Box<Any> {
173 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
179 impl<T: ?Sized> Deref for Box<T> {
182 fn deref(&self) -> &T { &**self }
186 impl<T: ?Sized> DerefMut for Box<T> {
187 fn deref_mut(&mut self) -> &mut T { &mut **self }
193 fn test_owned_clone() {
194 let a = Box::new(5i);
195 let b: Box<int> = a.clone();
201 let a = Box::new(8u) as Box<Any>;
202 let b = Box::new(Test) as Box<Any>;
204 match a.downcast::<uint>() {
205 Ok(a) => { assert!(a == Box::new(8u)); }
208 match b.downcast::<Test>() {
209 Ok(a) => { assert!(a == Box::new(Test)); }
213 let a = Box::new(8u) as Box<Any>;
214 let b = Box::new(Test) as Box<Any>;
216 assert!(a.downcast::<Box<Test>>().is_err());
217 assert!(b.downcast::<Box<uint>>().is_err());
222 let a = Box::new(8u) as Box<Any>;
223 let b = Box::new(Test) as Box<Any>;
224 let a_str = a.to_str();
225 let b_str = b.to_str();
226 assert_eq!(a_str, "Box<Any>");
227 assert_eq!(b_str, "Box<Any>");
230 let b = &Test as &Any;
231 let s = format!("{}", a);
232 assert_eq!(s, "&Any");
233 let s = format!("{}", b);
234 assert_eq!(s, "&Any");
239 fn homura<T: Deref<Target=i32>>(_: T) { }
240 homura(Box::new(765i32));