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