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.
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.
11 //! A pointer type for heap allocation.
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.
22 //! let x = Box::new(5);
25 //! Creating a recursive data structure:
30 //! Cons(T, Box<List<T>>),
35 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
36 //! println!("{:?}", list);
40 //! This will print `Cons(1, Cons(2, Nil))`.
42 //! Recursive structures must be boxed, because if the definition of `Cons`
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.
54 #![stable(feature = "rust1", since = "1.0.0")]
59 use core::cmp::Ordering;
61 use core::hash::{self, Hash};
62 use core::marker::Unsize;
64 use core::ops::{CoerceUnsized, Deref, DerefMut};
65 use core::ptr::{Unique};
66 use core::raw::{TraitObject};
68 /// A value that represents the heap. This is the default place that the `box`
69 /// keyword allocates into when no place is supplied.
71 /// The following two examples are equivalent:
74 /// # #![feature(box_heap)]
75 /// #![feature(box_syntax)]
76 /// use std::boxed::HEAP;
79 /// let foo = box(HEAP) 5;
83 #[lang = "exchange_heap"]
84 #[unstable(feature = "box_heap",
85 reason = "may be renamed; uncertain about custom allocator design")]
86 pub const HEAP: () = ();
88 /// A pointer type for heap allocation.
90 /// See the [module-level documentation](../../std/boxed/index.html) for more.
92 #[stable(feature = "rust1", since = "1.0.0")]
94 pub struct Box<T>(Unique<T>);
97 /// Allocates memory on the heap and then moves `x` into it.
102 /// let x = Box::new(5);
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub fn new(x: T) -> Box<T> {
111 impl<T : ?Sized> Box<T> {
112 /// Constructs a box from the raw pointer.
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.
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")]
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 {
132 /// Consumes the `Box`, returning the wrapped raw pointer.
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.
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) };
147 #[unstable(feature = "box_raw", reason = "may be renamed")]
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) }
155 /// Consumes the `Box`, returning the wrapped raw pointer.
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.
165 /// # #![feature(box_raw)]
168 /// let seventeen = Box::new(17u32);
169 /// let raw = boxed::into_raw(seventeen);
170 /// let boxed_again = unsafe { Box::from_raw(raw) };
172 #[unstable(feature = "box_raw", reason = "may be renamed")]
173 #[deprecated(since = "1.2.0", reason = "renamed to Box::into_raw")]
175 pub fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
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() }
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([]) }
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.
198 /// let x = Box::new(5);
199 /// let y = x.clone();
202 fn clone(&self) -> Box<T> { box {(**self).clone()} }
204 /// Copies `source`'s contents into `self` without creating a new allocation.
209 /// # #![feature(box_raw)]
210 /// let x = Box::new(5);
211 /// let mut y = Box::new(10);
213 /// y.clone_from(&x);
215 /// assert_eq!(*y, 5);
218 fn clone_from(&mut self, source: &Box<T>) {
219 (**self).clone_from(&(**source));
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
226 fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
228 fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
230 #[stable(feature = "rust1", since = "1.0.0")]
231 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
233 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
234 PartialOrd::partial_cmp(&**self, &**other)
237 fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
239 fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
241 fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
243 fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
245 #[stable(feature = "rust1", since = "1.0.0")]
246 impl<T: ?Sized + Ord> Ord for Box<T> {
248 fn cmp(&self, other: &Box<T>) -> Ordering {
249 Ord::cmp(&**self, &**other)
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<T: ?Sized + Eq> Eq for Box<T> {}
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);
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>> {
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);
274 // Extract the data pointer
275 Ok(Box::from_raw(to.data as *mut T))
283 impl Box<Any + Send> {
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)
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)
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)
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)
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<T: ?Sized> Deref for Box<T> {
323 fn deref(&self) -> &T { &**self }
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 }
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<I: Iterator + ?Sized> Iterator for Box<I> {
334 fn next(&mut self) -> Option<I::Item> { (**self).next() }
335 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
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() }
341 #[stable(feature = "rust1", since = "1.0.0")]
342 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
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.)
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()
362 /// #![feature(fnbox)]
364 /// use std::boxed::FnBox;
365 /// use std::collections::HashMap;
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));
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);
383 #[unstable(feature = "fnbox", reason = "Newly introduced")]
387 fn call_box(self: Box<Self>, args: A) -> Self::Output;
390 impl<A,F> FnBox<A> for F
393 type Output = F::Output;
395 fn call_box(self: Box<F>, args: A) -> F::Output {
400 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
403 extern "rust-call" fn call_once(self, args: A) -> R {
408 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
411 extern "rust-call" fn call_once(self, args: A) -> R {
416 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}