1 // Copyright 2012 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
13 use core::any::{Any, AnyRefExt};
14 use core::clone::Clone;
15 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
16 use core::default::Default;
19 use core::kinds::Send;
21 use core::option::Option;
22 use core::raw::TraitObject;
23 use core::result::{Ok, Err, Result};
25 /// A value that represents the global exchange heap. This is the default
26 /// place that the `box` keyword allocates into when no place is supplied.
28 /// The following two examples are equivalent:
30 /// use std::owned::HEAP;
33 /// # impl Bar { fn new(_a: int) { } }
34 /// let foo = box(HEAP) Bar::new(2);
35 /// let foo = box Bar::new(2);
36 #[lang="exchange_heap"]
37 pub static HEAP: () = ();
39 /// A type that represents a uniquely-owned value.
41 pub struct Box<T>(*mut T);
43 impl<T: Default> Default for Box<T> {
44 fn default() -> Box<T> { box Default::default() }
48 impl<T: Clone> Clone for Box<T> {
49 /// Return a copy of the owned box.
51 fn clone(&self) -> Box<T> { box {(**self).clone()} }
53 /// Perform copy-assignment from `source` by reusing the existing allocation.
55 fn clone_from(&mut self, source: &Box<T>) {
56 (**self).clone_from(&(**source));
61 impl<T:PartialEq> PartialEq for Box<T> {
63 fn eq(&self, other: &Box<T>) -> bool { *(*self) == *(*other) }
65 fn ne(&self, other: &Box<T>) -> bool { *(*self) != *(*other) }
67 impl<T:PartialOrd> PartialOrd for Box<T> {
69 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
70 (**self).partial_cmp(*other)
73 fn lt(&self, other: &Box<T>) -> bool { *(*self) < *(*other) }
75 fn le(&self, other: &Box<T>) -> bool { *(*self) <= *(*other) }
77 fn ge(&self, other: &Box<T>) -> bool { *(*self) >= *(*other) }
79 fn gt(&self, other: &Box<T>) -> bool { *(*self) > *(*other) }
81 impl<T: Ord> Ord for Box<T> {
83 fn cmp(&self, other: &Box<T>) -> Ordering { (**self).cmp(*other) }
85 impl<T: Eq> Eq for Box<T> {}
87 /// Extension methods for an owning `Any` trait object
89 /// Returns the boxed value if it is of type `T`, or
90 /// `Err(Self)` if it isn't.
91 fn move<T: 'static>(self) -> Result<Box<T>, Self>;
94 impl AnyOwnExt for Box<Any> {
96 fn move<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
99 // Get the raw representation of the trait object
100 let to: TraitObject =
101 *mem::transmute::<&Box<Any>, &TraitObject>(&self);
103 // Prevent destructor on self being run
104 intrinsics::forget(self);
106 // Extract the data pointer
107 Ok(mem::transmute(to.data))
115 /// Extension methods for an owning `Any+Send` trait object
116 pub trait AnySendOwnExt {
117 /// Returns the boxed value if it is of type `T`, or
118 /// `Err(Self)` if it isn't.
119 fn move_send<T: 'static>(self) -> Result<Box<T>, Self>;
122 impl AnySendOwnExt for Box<Any+Send> {
124 fn move_send<T: 'static>(self) -> Result<Box<T>, Box<Any+Send>> {
127 // Get the raw representation of the trait object
128 let to: TraitObject =
129 *mem::transmute::<&Box<Any+Send>, &TraitObject>(&self);
131 // Prevent destructor on self being run
132 intrinsics::forget(self);
134 // Extract the data pointer
135 Ok(mem::transmute(to.data))
143 impl<T: fmt::Show> fmt::Show for Box<T> {
144 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
149 impl fmt::Show for Box<Any> {
150 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
158 fn test_owned_clone() {
160 let b: Box<int> = a.clone();
166 let a = box 8u as Box<Any>;
167 let b = box Test as Box<Any>;
169 match a.move::<uint>() {
170 Ok(a) => { assert!(a == box 8u); }
173 match b.move::<Test>() {
174 Ok(a) => { assert!(a == box Test); }
178 let a = box 8u as Box<Any>;
179 let b = box Test as Box<Any>;
181 assert!(a.move::<Box<Test>>().is_err());
182 assert!(b.move::<Box<uint>>().is_err());
187 let a = box 8u as Box<Any>;
188 let b = box Test as Box<Any>;
189 let a_str = a.to_str();
190 let b_str = b.to_str();
191 assert_eq!(a_str.as_slice(), "Box<Any>");
192 assert_eq!(b_str.as_slice(), "Box<Any>");
195 let b = &Test as &Any;
196 let s = format!("{}", a);
197 assert_eq!(s.as_slice(), "&Any");
198 let s = format!("{}", b);
199 assert_eq!(s.as_slice(), "&Any");