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