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