]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[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 pointer type for heap allocation.
12 //!
13 //! `Box<T>`, casually referred to as a 'box', provides the simplest form of
14 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
15 //! drop their contents when they go out of scope.
16 //!
17 //! Boxes are useful in two situations: recursive data structures, and
18 //! occasionally when returning data. [The Pointer chapter of the
19 //! Book](../../../book/pointers.html#best-practices-1) explains these cases in
20 //! detail.
21 //!
22 //! # Examples
23 //!
24 //! Creating a box:
25 //!
26 //! ```
27 //! let x = Box::new(5);
28 //! ```
29 //!
30 //! Creating a recursive data structure:
31 //!
32 //! ```
33 //! #[derive(Debug)]
34 //! enum List<T> {
35 //!     Cons(T, Box<List<T>>),
36 //!     Nil,
37 //! }
38 //!
39 //! fn main() {
40 //!     let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
41 //!     println!("{:?}", list);
42 //! }
43 //! ```
44 //!
45 //! This will print `Cons(1i32, Box(Cons(2i32, Box(Nil))))`.
46
47 #![stable(feature = "rust1", since = "1.0.0")]
48
49 use core::prelude::*;
50
51 use core::any::Any;
52 use core::cmp::Ordering;
53 use core::default::Default;
54 use core::error::{Error, FromError};
55 use core::fmt;
56 use core::hash::{self, Hash};
57 use core::mem;
58 use core::ops::{Deref, DerefMut};
59 use core::ptr::Unique;
60 use core::raw::TraitObject;
61
62 /// A value that represents the heap. This is the default place that the `box`
63 /// keyword allocates into when no place is supplied.
64 ///
65 /// The following two examples are equivalent:
66 ///
67 /// ```rust
68 /// #![feature(box_syntax)]
69 /// use std::boxed::HEAP;
70 ///
71 /// fn main() {
72 ///     let foo = box(HEAP) 5;
73 ///     let foo = box 5;
74 /// }
75 /// ```
76 #[lang = "exchange_heap"]
77 #[unstable(feature = "alloc",
78            reason = "may be renamed; uncertain about custom allocator design")]
79 pub static HEAP: () = ();
80
81 /// A pointer type for heap allocation.
82 ///
83 /// See the [module-level documentation](../../std/boxed/index.html) for more.
84 #[lang = "owned_box"]
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct Box<T>(Unique<T>);
87
88 impl<T> Box<T> {
89     /// Allocates memory on the heap and then moves `x` into it.
90     ///
91     /// # Examples
92     ///
93     /// ```
94     /// let x = Box::new(5);
95     /// ```
96     #[stable(feature = "rust1", since = "1.0.0")]
97     pub fn new(x: T) -> Box<T> {
98         box x
99     }
100 }
101
102 impl<T : ?Sized> Box<T> {
103     /// Constructs a box from the raw pointer.
104     ///
105     /// After this function call, pointer is owned by resulting box.
106     /// In particular, it means that `Box` destructor calls destructor
107     /// of `T` and releases memory. Since the way `Box` allocates and
108     /// releases memory is unspecified, so the only valid pointer to
109     /// pass to this function is the one taken from another `Box` with
110     /// `box::into_raw` function.
111     ///
112     /// Function is unsafe, because improper use of this function may
113     /// lead to memory problems like double-free, for example if the
114     /// function is called twice on the same raw pointer.
115     #[unstable(feature = "alloc",
116                reason = "may be renamed or moved out of Box scope")]
117     pub unsafe fn from_raw(raw: *mut T) -> Self {
118         mem::transmute(raw)
119     }
120 }
121
122 /// Consumes the `Box`, returning the wrapped raw pointer.
123 ///
124 /// After call to this function, caller is responsible for the memory
125 /// previously managed by `Box`, in particular caller should properly
126 /// destroy `T` and release memory. The proper way to do it is to
127 /// convert pointer back to `Box` with `Box::from_raw` function, because
128 /// `Box` does not specify, how memory is allocated.
129 ///
130 /// Function is unsafe, because result of this function is no longer
131 /// automatically managed that may lead to memory or other resource
132 /// leak.
133 ///
134 /// # Example
135 /// ```
136 /// use std::boxed;
137 ///
138 /// let seventeen = Box::new(17u32);
139 /// let raw = unsafe { boxed::into_raw(seventeen) };
140 /// let boxed_again = unsafe { Box::from_raw(raw) };
141 /// ```
142 #[unstable(feature = "alloc",
143            reason = "may be renamed")]
144 pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
145     mem::transmute(b)
146 }
147
148 #[stable(feature = "rust1", since = "1.0.0")]
149 impl<T: Default> Default for Box<T> {
150     #[stable(feature = "rust1", since = "1.0.0")]
151     fn default() -> Box<T> { box Default::default() }
152 }
153
154 #[stable(feature = "rust1", since = "1.0.0")]
155 impl<T> Default for Box<[T]> {
156     #[stable(feature = "rust1", since = "1.0.0")]
157     fn default() -> Box<[T]> { box [] }
158 }
159
160 #[stable(feature = "rust1", since = "1.0.0")]
161 impl<T: Clone> Clone for Box<T> {
162     /// Returns a new box with a `clone()` of this box's contents.
163     ///
164     /// # Examples
165     ///
166     /// ```
167     /// let x = Box::new(5);
168     /// let y = x.clone();
169     /// ```
170     #[inline]
171     fn clone(&self) -> Box<T> { box {(**self).clone()} }
172
173     /// Copies `source`'s contents into `self` without creating a new allocation.
174     ///
175     /// # Examples
176     ///
177     /// ```
178     /// let x = Box::new(5);
179     /// let mut y = Box::new(10);
180     ///
181     /// y.clone_from(&x);
182     ///
183     /// assert_eq!(*y, 5);
184     /// ```
185     #[inline]
186     fn clone_from(&mut self, source: &Box<T>) {
187         (**self).clone_from(&(**source));
188     }
189 }
190
191 #[stable(feature = "rust1", since = "1.0.0")]
192 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
193     #[inline]
194     fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
195     #[inline]
196     fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
197 }
198 #[stable(feature = "rust1", since = "1.0.0")]
199 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
200     #[inline]
201     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
202         PartialOrd::partial_cmp(&**self, &**other)
203     }
204     #[inline]
205     fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
206     #[inline]
207     fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
208     #[inline]
209     fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
210     #[inline]
211     fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
212 }
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl<T: ?Sized + Ord> Ord for Box<T> {
215     #[inline]
216     fn cmp(&self, other: &Box<T>) -> Ordering {
217         Ord::cmp(&**self, &**other)
218     }
219 }
220 #[stable(feature = "rust1", since = "1.0.0")]
221 impl<T: ?Sized + Eq> Eq for Box<T> {}
222
223 #[cfg(stage0)]
224 impl<S: hash::Hasher, T: ?Sized + Hash<S>> Hash<S> for Box<T> {
225     #[inline]
226     fn hash(&self, state: &mut S) {
227         (**self).hash(state);
228     }
229 }
230 #[cfg(not(stage0))]
231 #[stable(feature = "rust1", since = "1.0.0")]
232 impl<T: ?Sized + Hash> Hash for Box<T> {
233     fn hash<H: hash::Hasher>(&self, state: &mut H) {
234         (**self).hash(state);
235     }
236 }
237
238 /// Extension methods for an owning `Any` trait object.
239 #[unstable(feature = "alloc",
240            reason = "this trait will likely disappear once compiler bugs blocking \
241                      a direct impl on `Box<Any>` have been fixed ")]
242 // FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
243 //                removing this please make sure that you can downcase on
244 //                `Box<Any + Send>` as well as `Box<Any>`
245 pub trait BoxAny {
246     /// Returns the boxed value if it is of type `T`, or
247     /// `Err(Self)` if it isn't.
248     #[stable(feature = "rust1", since = "1.0.0")]
249     fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
250 }
251
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl BoxAny for Box<Any> {
254     #[inline]
255     fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
256         if self.is::<T>() {
257             unsafe {
258                 // Get the raw representation of the trait object
259                 let to: TraitObject =
260                     mem::transmute::<Box<Any>, TraitObject>(self);
261
262                 // Extract the data pointer
263                 Ok(mem::transmute(to.data))
264             }
265         } else {
266             Err(self)
267         }
268     }
269 }
270
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
273     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
274         fmt::Display::fmt(&**self, f)
275     }
276 }
277
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
280     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
281         fmt::Debug::fmt(&**self, f)
282     }
283 }
284
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl fmt::Debug for Box<Any> {
287     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
288         f.pad("Box<Any>")
289     }
290 }
291
292 #[stable(feature = "rust1", since = "1.0.0")]
293 impl<T: ?Sized> Deref for Box<T> {
294     type Target = T;
295
296     fn deref(&self) -> &T { &**self }
297 }
298
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<T: ?Sized> DerefMut for Box<T> {
301     fn deref_mut(&mut self) -> &mut T { &mut **self }
302 }
303
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<I: Iterator + ?Sized> Iterator for Box<I> {
306     type Item = I::Item;
307     fn next(&mut self) -> Option<I::Item> { (**self).next() }
308     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
309 }
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
312     fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
313 }
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
316
317 #[stable(feature = "rust1", since = "1.0.0")]
318 impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
319     fn from_error(err: E) -> Box<Error + 'a> {
320         Box::new(err)
321     }
322 }