]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
rollup merge of #23948: nikomatsakis/feature-gate-rust-abi
[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(1, Box(Cons(2, 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::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`
62 /// keyword allocates into when no place is supplied.
63 ///
64 /// The following two examples are equivalent:
65 ///
66 /// ```
67 /// # #![feature(alloc)]
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 #[fundamental]
87 pub struct Box<T>(Unique<T>);
88
89 impl<T> Box<T> {
90     /// Allocates memory on the heap and then moves `x` into it.
91     ///
92     /// # Examples
93     ///
94     /// ```
95     /// let x = Box::new(5);
96     /// ```
97     #[stable(feature = "rust1", since = "1.0.0")]
98     #[inline(always)]
99     pub fn new(x: T) -> Box<T> {
100         box x
101     }
102 }
103
104 impl<T : ?Sized> Box<T> {
105     /// Constructs a box from the raw pointer.
106     ///
107     /// After this function call, pointer is owned by resulting box.
108     /// In particular, it means that `Box` destructor calls destructor
109     /// of `T` and releases memory. Since the way `Box` allocates and
110     /// releases memory is unspecified, the only valid pointer to pass
111     /// to this function is the one taken from another `Box` with
112     /// `boxed::into_raw` function.
113     ///
114     /// Function is unsafe, because improper use of this function may
115     /// lead to memory problems like double-free, for example if the
116     /// function is called twice on the same raw pointer.
117     #[unstable(feature = "alloc",
118                reason = "may be renamed or moved out of Box scope")]
119     #[inline]
120     pub unsafe fn from_raw(raw: *mut T) -> Self {
121         mem::transmute(raw)
122     }
123 }
124
125 /// Consumes the `Box`, returning the wrapped raw pointer.
126 ///
127 /// After call to this function, caller is responsible for the memory
128 /// previously managed by `Box`, in particular caller should properly
129 /// destroy `T` and release memory. The proper way to do it is to
130 /// convert pointer back to `Box` with `Box::from_raw` function, because
131 /// `Box` does not specify, how memory is allocated.
132 ///
133 /// Function is unsafe, because result of this function is no longer
134 /// automatically managed that may lead to memory or other resource
135 /// leak.
136 ///
137 /// # Examples
138 /// ```
139 /// # #![feature(alloc)]
140 /// use std::boxed;
141 ///
142 /// let seventeen = Box::new(17u32);
143 /// let raw = unsafe { boxed::into_raw(seventeen) };
144 /// let boxed_again = unsafe { Box::from_raw(raw) };
145 /// ```
146 #[unstable(feature = "alloc",
147            reason = "may be renamed")]
148 #[inline]
149 pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
150     mem::transmute(b)
151 }
152
153 #[stable(feature = "rust1", since = "1.0.0")]
154 impl<T: Default> Default for Box<T> {
155     #[stable(feature = "rust1", since = "1.0.0")]
156     fn default() -> Box<T> { box Default::default() }
157 }
158
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl<T> Default for Box<[T]> {
161     #[stable(feature = "rust1", since = "1.0.0")]
162     fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
163 }
164
165 #[stable(feature = "rust1", since = "1.0.0")]
166 impl<T: Clone> Clone for Box<T> {
167     /// Returns a new box with a `clone()` of this box's contents.
168     ///
169     /// # Examples
170     ///
171     /// ```
172     /// let x = Box::new(5);
173     /// let y = x.clone();
174     /// ```
175     #[inline]
176     fn clone(&self) -> Box<T> { box {(**self).clone()} }
177
178     /// Copies `source`'s contents into `self` without creating a new allocation.
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// # #![feature(alloc, core)]
184     /// let x = Box::new(5);
185     /// let mut y = Box::new(10);
186     ///
187     /// y.clone_from(&x);
188     ///
189     /// assert_eq!(*y, 5);
190     /// ```
191     #[inline]
192     fn clone_from(&mut self, source: &Box<T>) {
193         (**self).clone_from(&(**source));
194     }
195 }
196
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
199     #[inline]
200     fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
201     #[inline]
202     fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
203 }
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
206     #[inline]
207     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
208         PartialOrd::partial_cmp(&**self, &**other)
209     }
210     #[inline]
211     fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
212     #[inline]
213     fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
214     #[inline]
215     fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
216     #[inline]
217     fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
218 }
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl<T: ?Sized + Ord> Ord for Box<T> {
221     #[inline]
222     fn cmp(&self, other: &Box<T>) -> Ordering {
223         Ord::cmp(&**self, &**other)
224     }
225 }
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<T: ?Sized + Eq> Eq for Box<T> {}
228
229 #[stable(feature = "rust1", since = "1.0.0")]
230 impl<T: ?Sized + Hash> Hash for Box<T> {
231     fn hash<H: hash::Hasher>(&self, state: &mut H) {
232         (**self).hash(state);
233     }
234 }
235
236 impl Box<Any> {
237     #[inline]
238     #[stable(feature = "rust1", since = "1.0.0")]
239     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
240         if self.is::<T>() {
241             unsafe {
242                 // Get the raw representation of the trait object
243                 let raw = into_raw(self);
244                 let to: TraitObject =
245                     mem::transmute::<*mut Any, TraitObject>(raw);
246
247                 // Extract the data pointer
248                 Ok(Box::from_raw(to.data as *mut T))
249             }
250         } else {
251             Err(self)
252         }
253     }
254 }
255
256 impl Box<Any+Send> {
257     #[inline]
258     #[stable(feature = "rust1", since = "1.0.0")]
259     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
260         <Box<Any>>::downcast(self)
261     }
262 }
263
264 #[stable(feature = "rust1", since = "1.0.0")]
265 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
266     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
267         fmt::Display::fmt(&**self, f)
268     }
269 }
270
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
273     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
274         fmt::Debug::fmt(&**self, f)
275     }
276 }
277
278 #[stable(feature = "rust1", since = "1.0.0")]
279 impl<T: ?Sized> Deref for Box<T> {
280     type Target = T;
281
282     fn deref(&self) -> &T { &**self }
283 }
284
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T: ?Sized> DerefMut for Box<T> {
287     fn deref_mut(&mut self) -> &mut T { &mut **self }
288 }
289
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<I: Iterator + ?Sized> Iterator for Box<I> {
292     type Item = I::Item;
293     fn next(&mut self) -> Option<I::Item> { (**self).next() }
294     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
295 }
296 #[stable(feature = "rust1", since = "1.0.0")]
297 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
298     fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
299 }
300 #[stable(feature = "rust1", since = "1.0.0")]
301 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
302
303
304 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
305 /// closure objects. The idea is that where one would normally store a
306 /// `Box<FnOnce()>` in a data structure, you should use
307 /// `Box<FnBox()>`. The two traits behave essentially the same, except
308 /// that a `FnBox` closure can only be called if it is boxed. (Note
309 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
310 /// closures become directly usable.)
311 ///
312 /// ### Example
313 ///
314 /// Here is a snippet of code which creates a hashmap full of boxed
315 /// once closures and then removes them one by one, calling each
316 /// closure as it is removed. Note that the type of the closures
317 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
318 /// -> i32>`.
319 ///
320 /// ```
321 /// #![feature(core)]
322 ///
323 /// use std::boxed::FnBox;
324 /// use std::collections::HashMap;
325 ///
326 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
327 ///     let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
328 ///     map.insert(1, Box::new(|| 22));
329 ///     map.insert(2, Box::new(|| 44));
330 ///     map
331 /// }
332 ///
333 /// fn main() {
334 ///     let mut map = make_map();
335 ///     for i in &[1, 2] {
336 ///         let f = map.remove(&i).unwrap();
337 ///         assert_eq!(f(), i * 22);
338 ///     }
339 /// }
340 /// ```
341 #[rustc_paren_sugar]
342 #[unstable(feature = "core", reason = "Newly introduced")]
343 pub trait FnBox<A> {
344     type Output;
345
346     fn call_box(self: Box<Self>, args: A) -> Self::Output;
347 }
348
349 impl<A,F> FnBox<A> for F
350     where F: FnOnce<A>
351 {
352     type Output = F::Output;
353
354     fn call_box(self: Box<F>, args: A) -> F::Output {
355         self.call_once(args)
356     }
357 }
358
359 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
360     type Output = R;
361
362     extern "rust-call" fn call_once(self, args: A) -> R {
363         self.call_box(args)
364     }
365 }
366
367 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
368     type Output = R;
369
370     extern "rust-call" fn call_once(self, args: A) -> R {
371         self.call_box(args)
372     }
373 }