]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
Remove `Thunk` struct and `Invoke` trait; change `Thunk` to be an alias
[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::error::Error;
55 use core::fmt;
56 use core::hash::{self, Hash};
57 use core::mem;
58 use core::ops::{Deref, DerefMut};
59 use core::ptr::{self, Unique};
60 use core::raw::{TraitObject, Slice};
61
62 use heap;
63
64 /// A value that represents the heap. This is the default place that the `box`
65 /// keyword allocates into when no place is supplied.
66 ///
67 /// The following two examples are equivalent:
68 ///
69 /// ```
70 /// # #![feature(alloc)]
71 /// #![feature(box_syntax)]
72 /// use std::boxed::HEAP;
73 ///
74 /// fn main() {
75 ///     let foo = box(HEAP) 5;
76 ///     let foo = box 5;
77 /// }
78 /// ```
79 #[lang = "exchange_heap"]
80 #[unstable(feature = "alloc",
81            reason = "may be renamed; uncertain about custom allocator design")]
82 pub static HEAP: () = ();
83
84 /// A pointer type for heap allocation.
85 ///
86 /// See the [module-level documentation](../../std/boxed/index.html) for more.
87 #[lang = "owned_box"]
88 #[stable(feature = "rust1", since = "1.0.0")]
89 pub struct Box<T>(Unique<T>);
90
91 impl<T> Box<T> {
92     /// Allocates memory on the heap and then moves `x` into it.
93     ///
94     /// # Examples
95     ///
96     /// ```
97     /// let x = Box::new(5);
98     /// ```
99     #[stable(feature = "rust1", since = "1.0.0")]
100     #[inline(always)]
101     pub fn new(x: T) -> Box<T> {
102         box x
103     }
104 }
105
106 impl<T : ?Sized> Box<T> {
107     /// Constructs a box from the raw pointer.
108     ///
109     /// After this function call, pointer is owned by resulting box.
110     /// In particular, it means that `Box` destructor calls destructor
111     /// of `T` and releases memory. Since the way `Box` allocates and
112     /// releases memory is unspecified, the only valid pointer to pass
113     /// to this function is the one taken from another `Box` with
114     /// `boxed::into_raw` function.
115     ///
116     /// Function is unsafe, because improper use of this function may
117     /// lead to memory problems like double-free, for example if the
118     /// function is called twice on the same raw pointer.
119     #[unstable(feature = "alloc",
120                reason = "may be renamed or moved out of Box scope")]
121     #[inline]
122     pub unsafe fn from_raw(raw: *mut T) -> Self {
123         mem::transmute(raw)
124     }
125 }
126
127 /// Consumes the `Box`, returning the wrapped raw pointer.
128 ///
129 /// After call to this function, caller is responsible for the memory
130 /// previously managed by `Box`, in particular caller should properly
131 /// destroy `T` and release memory. The proper way to do it is to
132 /// convert pointer back to `Box` with `Box::from_raw` function, because
133 /// `Box` does not specify, how memory is allocated.
134 ///
135 /// Function is unsafe, because result of this function is no longer
136 /// automatically managed that may lead to memory or other resource
137 /// leak.
138 ///
139 /// # Examples
140 /// ```
141 /// # #![feature(alloc)]
142 /// use std::boxed;
143 ///
144 /// let seventeen = Box::new(17u32);
145 /// let raw = unsafe { boxed::into_raw(seventeen) };
146 /// let boxed_again = unsafe { Box::from_raw(raw) };
147 /// ```
148 #[unstable(feature = "alloc",
149            reason = "may be renamed")]
150 #[inline]
151 pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
152     mem::transmute(b)
153 }
154
155 #[stable(feature = "rust1", since = "1.0.0")]
156 impl<T: Default> Default for Box<T> {
157     #[stable(feature = "rust1", since = "1.0.0")]
158     fn default() -> Box<T> { box Default::default() }
159 }
160
161 #[stable(feature = "rust1", since = "1.0.0")]
162 impl<T> Default for Box<[T]> {
163     #[stable(feature = "rust1", since = "1.0.0")]
164     fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
165 }
166
167 #[stable(feature = "rust1", since = "1.0.0")]
168 impl<T: Clone> Clone for Box<T> {
169     /// Returns a new box with a `clone()` of this box's contents.
170     ///
171     /// # Examples
172     ///
173     /// ```
174     /// let x = Box::new(5);
175     /// let y = x.clone();
176     /// ```
177     #[inline]
178     fn clone(&self) -> Box<T> { box {(**self).clone()} }
179
180     /// Copies `source`'s contents into `self` without creating a new allocation.
181     ///
182     /// # Examples
183     ///
184     /// ```
185     /// # #![feature(alloc, core)]
186     /// let x = Box::new(5);
187     /// let mut y = Box::new(10);
188     ///
189     /// y.clone_from(&x);
190     ///
191     /// assert_eq!(*y, 5);
192     /// ```
193     #[inline]
194     fn clone_from(&mut self, source: &Box<T>) {
195         (**self).clone_from(&(**source));
196     }
197 }
198
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
201     #[inline]
202     fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
203     #[inline]
204     fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
205 }
206 #[stable(feature = "rust1", since = "1.0.0")]
207 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
208     #[inline]
209     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
210         PartialOrd::partial_cmp(&**self, &**other)
211     }
212     #[inline]
213     fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
214     #[inline]
215     fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
216     #[inline]
217     fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
218     #[inline]
219     fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
220 }
221 #[stable(feature = "rust1", since = "1.0.0")]
222 impl<T: ?Sized + Ord> Ord for Box<T> {
223     #[inline]
224     fn cmp(&self, other: &Box<T>) -> Ordering {
225         Ord::cmp(&**self, &**other)
226     }
227 }
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl<T: ?Sized + Eq> Eq for Box<T> {}
230
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 impl Box<Any> {
239     #[inline]
240     #[stable(feature = "rust1", since = "1.0.0")]
241     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
242         if self.is::<T>() {
243             unsafe {
244                 // Get the raw representation of the trait object
245                 let raw = into_raw(self);
246                 let to: TraitObject =
247                     mem::transmute::<*mut Any, TraitObject>(raw);
248
249                 // Extract the data pointer
250                 Ok(Box::from_raw(to.data as *mut T))
251             }
252         } else {
253             Err(self)
254         }
255     }
256 }
257
258 impl Box<Any+Send> {
259     #[inline]
260     #[stable(feature = "rust1", since = "1.0.0")]
261     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
262         <Box<Any>>::downcast(self)
263     }
264 }
265
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
268     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
269         fmt::Display::fmt(&**self, f)
270     }
271 }
272
273 #[stable(feature = "rust1", since = "1.0.0")]
274 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
275     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
276         fmt::Debug::fmt(&**self, f)
277     }
278 }
279
280 #[stable(feature = "rust1", since = "1.0.0")]
281 impl fmt::Debug for Box<Any> {
282     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
283         f.pad("Box<Any>")
284     }
285 }
286
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: ?Sized> Deref for Box<T> {
289     type Target = T;
290
291     fn deref(&self) -> &T { &**self }
292 }
293
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl<T: ?Sized> DerefMut for Box<T> {
296     fn deref_mut(&mut self) -> &mut T { &mut **self }
297 }
298
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<I: Iterator + ?Sized> Iterator for Box<I> {
301     type Item = I::Item;
302     fn next(&mut self) -> Option<I::Item> { (**self).next() }
303     fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
304 }
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
307     fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
308 }
309 #[stable(feature = "rust1", since = "1.0.0")]
310 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
311
312 #[stable(feature = "rust1", since = "1.0.0")]
313 impl<'a, E: Error + 'a> From<E> for Box<Error + 'a> {
314     fn from(err: E) -> Box<Error + 'a> {
315         Box::new(err)
316     }
317 }
318
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<'a, E: Error + Send + 'a> From<E> for Box<Error + Send + 'a> {
321     fn from(err: E) -> Box<Error + Send + 'a> {
322         Box::new(err)
323     }
324 }
325
326 #[stable(feature = "rust1", since = "1.0.0")]
327 impl<'a, 'b> From<&'b str> for Box<Error + Send + 'a> {
328     fn from(err: &'b str) -> Box<Error + Send + 'a> {
329         #[derive(Debug)]
330         struct StringError(Box<str>);
331         impl Error for StringError {
332             fn description(&self) -> &str { &self.0 }
333         }
334         impl fmt::Display for StringError {
335             fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
336                 self.0.fmt(f)
337             }
338         }
339
340         // Unfortunately `String` is located in libcollections, so we construct
341         // a `Box<str>` manually here.
342         unsafe {
343             let alloc = if err.len() == 0 {
344                 0 as *mut u8
345             } else {
346                 let ptr = heap::allocate(err.len(), 1);
347                 if ptr.is_null() { ::oom(); }
348                 ptr as *mut u8
349             };
350             ptr::copy(err.as_bytes().as_ptr(), alloc, err.len());
351             Box::new(StringError(mem::transmute(Slice {
352                 data: alloc,
353                 len: err.len(),
354             })))
355         }
356     }
357 }
358
359 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
360 /// closure objects. The idea is that where one would normally store a
361 /// `Box<FnOnce()>` in a data structure, you should use
362 /// `Box<FnBox()>`. The two traits behave essentially the same, except
363 /// that a `FnBox` closure can only be called if it is boxed. (Note
364 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
365 /// closures become directly usable.)
366 ///
367 /// ### Example
368 ///
369 /// Here is a snippet of code which creates a hashmap full of boxed
370 /// once closures and then removes them one by one, calling each
371 /// closure as it is removed. Note that the type of the closures
372 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
373 /// -> i32>`.
374 ///
375 /// ```
376 /// #![feature(core)]
377 ///
378 /// use std::boxed::FnBox;
379 /// use std::collections::HashMap;
380 ///
381 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
382 ///     let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
383 ///     map.insert(1, Box::new(|| 22));
384 ///     map.insert(2, Box::new(|| 44));
385 ///     map
386 /// }
387 ///
388 /// fn main() {
389 ///     let mut map = make_map();
390 ///     for i in &[1, 2] {
391 ///         let f = map.remove(&i).unwrap();
392 ///         assert_eq!(f(), i * 22);
393 ///     }
394 /// }
395 /// ```
396 #[rustc_paren_sugar]
397 #[unstable(feature = "core", reason = "Newly introduced")]
398 pub trait FnBox<A> {
399     type Output;
400
401     fn call_box(self: Box<Self>, args: A) -> Self::Output;
402 }
403
404 impl<A,F> FnBox<A> for F
405     where F: FnOnce<A>
406 {
407     type Output = F::Output;
408
409     fn call_box(self: Box<F>, args: A) -> F::Output {
410         self.call_once(args)
411     }
412 }
413
414 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
415     type Output = R;
416
417     extern "rust-call" fn call_once(self, args: A) -> R {
418         self.call_box(args)
419     }
420 }
421
422 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
423     type Output = R;
424
425     extern "rust-call" fn call_once(self, args: A) -> R {
426         self.call_box(args)
427     }
428 }