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