]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
Test fixes and rebase conflicts
[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 unique pointer type.
12
13 #![stable]
14
15 use core::any::Any;
16 use core::clone::Clone;
17 use core::cmp::{PartialEq, PartialOrd, Eq, Ord, Ordering};
18 use core::default::Default;
19 use core::fmt;
20 use core::hash::{self, Hash};
21 use core::marker::Sized;
22 use core::mem;
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};
29
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.
32 ///
33 /// The following two examples are equivalent:
34 ///
35 /// ```rust
36 /// #![feature(box_syntax)]
37 /// use std::boxed::HEAP;
38 ///
39 /// fn main() {
40 /// # struct Bar;
41 /// # impl Bar { fn new(_a: int) { } }
42 ///     let foo = box(HEAP) Bar::new(2);
43 ///     let foo = box Bar::new(2);
44 /// }
45 /// ```
46 #[lang = "exchange_heap"]
47 #[experimental = "may be renamed; uncertain about custom allocator design"]
48 pub static HEAP: () = ();
49
50 /// A type that represents a uniquely-owned value.
51 #[lang = "owned_box"]
52 #[stable]
53 pub struct Box<T>(Unique<T>);
54
55 impl<T> Box<T> {
56     /// Moves `x` into a freshly allocated box on the global exchange heap.
57     #[stable]
58     pub fn new(x: T) -> Box<T> {
59         box x
60     }
61 }
62
63 #[stable]
64 impl<T: Default> Default for Box<T> {
65     #[stable]
66     fn default() -> Box<T> { box Default::default() }
67 }
68
69 #[stable]
70 impl<T> Default for Box<[T]> {
71     #[stable]
72     fn default() -> Box<[T]> { box [] }
73 }
74
75 #[stable]
76 impl<T: Clone> Clone for Box<T> {
77     /// Returns a copy of the owned box.
78     #[inline]
79     fn clone(&self) -> Box<T> { box {(**self).clone()} }
80
81     /// Performs copy-assignment from `source` by reusing the existing allocation.
82     #[inline]
83     fn clone_from(&mut self, source: &Box<T>) {
84         (**self).clone_from(&(**source));
85     }
86 }
87
88 #[stable]
89 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
90     #[inline]
91     fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
92     #[inline]
93     fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
94 }
95 #[stable]
96 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
97     #[inline]
98     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
99         PartialOrd::partial_cmp(&**self, &**other)
100     }
101     #[inline]
102     fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
103     #[inline]
104     fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
105     #[inline]
106     fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
107     #[inline]
108     fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
109 }
110 #[stable]
111 impl<T: ?Sized + Ord> Ord for Box<T> {
112     #[inline]
113     fn cmp(&self, other: &Box<T>) -> Ordering {
114         Ord::cmp(&**self, &**other)
115     }
116 }
117 #[stable]
118 impl<T: ?Sized + Eq> Eq for Box<T> {}
119
120 #[cfg(stage0)]
121 impl<S: hash::Writer, T: ?Sized + Hash<S>> Hash<S> for Box<T> {
122     #[inline]
123     fn hash(&self, state: &mut S) {
124         (**self).hash(state);
125     }
126 }
127 #[cfg(not(stage0))]
128 impl<S: hash::Hasher, T: ?Sized + Hash<S>> Hash<S> for Box<T> {
129     #[inline]
130     fn hash(&self, state: &mut S) {
131         (**self).hash(state);
132     }
133 }
134
135 /// Extension methods for an owning `Any` trait object.
136 #[unstable = "post-DST and coherence changes, this will not be a trait but \
137               rather a direct `impl` on `Box<Any>`"]
138 pub trait BoxAny {
139     /// Returns the boxed value if it is of type `T`, or
140     /// `Err(Self)` if it isn't.
141     #[stable]
142     fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
143 }
144
145 impl BoxAny for Box<Any> {
146     #[inline]
147     #[unstable = "method may be renamed with respect to other downcasting \
148                   methods"]
149     fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
150         if self.is::<T>() {
151             unsafe {
152                 // Get the raw representation of the trait object
153                 let to: TraitObject =
154                     mem::transmute::<Box<Any>, TraitObject>(self);
155
156                 // Extract the data pointer
157                 Ok(mem::transmute(to.data))
158             }
159         } else {
160             Err(self)
161         }
162     }
163 }
164
165 impl<T: ?Sized + fmt::Show> fmt::Show for Box<T> {
166     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
167         write!(f, "Box({:?})", &**self)
168     }
169 }
170
171 #[stable]
172 impl<T: ?Sized + fmt::String> fmt::String for Box<T> {
173     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
174         fmt::String::fmt(&**self, f)
175     }
176 }
177
178 impl fmt::Show for Box<Any> {
179     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
180         f.pad("Box<Any>")
181     }
182 }
183
184 #[stable]
185 impl<T: ?Sized> Deref for Box<T> {
186     type Target = T;
187
188     fn deref(&self) -> &T { &**self }
189 }
190
191 #[stable]
192 impl<T: ?Sized> DerefMut for Box<T> {
193     fn deref_mut(&mut self) -> &mut T { &mut **self }
194 }
195
196 #[cfg(test)]
197 mod test {
198     #[test]
199     fn test_owned_clone() {
200         let a = Box::new(5i);
201         let b: Box<int> = a.clone();
202         assert!(a == b);
203     }
204
205     #[test]
206     fn any_move() {
207         let a = Box::new(8u) as Box<Any>;
208         let b = Box::new(Test) as Box<Any>;
209
210         match a.downcast::<uint>() {
211             Ok(a) => { assert!(a == Box::new(8u)); }
212             Err(..) => panic!()
213         }
214         match b.downcast::<Test>() {
215             Ok(a) => { assert!(a == Box::new(Test)); }
216             Err(..) => panic!()
217         }
218
219         let a = Box::new(8u) as Box<Any>;
220         let b = Box::new(Test) as Box<Any>;
221
222         assert!(a.downcast::<Box<Test>>().is_err());
223         assert!(b.downcast::<Box<uint>>().is_err());
224     }
225
226     #[test]
227     fn test_show() {
228         let a = Box::new(8u) as Box<Any>;
229         let b = Box::new(Test) as Box<Any>;
230         let a_str = a.to_str();
231         let b_str = b.to_str();
232         assert_eq!(a_str, "Box<Any>");
233         assert_eq!(b_str, "Box<Any>");
234
235         let a = &8u as &Any;
236         let b = &Test as &Any;
237         let s = format!("{}", a);
238         assert_eq!(s, "&Any");
239         let s = format!("{}", b);
240         assert_eq!(s, "&Any");
241     }
242
243     #[test]
244     fn deref() {
245         fn homura<T: Deref<Target=i32>>(_: T) { }
246         homura(Box::new(765i32));
247     }
248 }