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 heap allocation in
14 //! Rust. Boxes provide ownership for this allocation, and drop their contents when they go out of
17 //! Boxes are useful in two situations: recursive data structures, and occasionally when returning
18 //! data. [The Pointer chapter of the Book](../../../book/pointers.html#best-practices-1) explains
19 //! these cases in detail.
26 //! let x = Box::new(5);
29 //! Creating a recursive data structure:
34 //! Cons(T, Box<List<T>>),
39 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
40 //! println!("{:?}", list);
44 //! This will print `Cons(1i32, Box(Cons(2i32, Box(Nil))))`.
46 #![stable(feature = "rust1", since = "1.0.0")]
51 use core::cmp::Ordering;
52 use core::default::Default;
53 use core::error::{Error, FromError};
55 use core::hash::{self, Hash};
57 use core::ops::{Deref, DerefMut};
58 use core::ptr::Unique;
59 use core::raw::TraitObject;
61 /// A value that represents the heap. This is the default place that the `box` keyword allocates
62 /// into when no place is supplied.
64 /// The following two examples are equivalent:
67 /// #![feature(box_syntax)]
68 /// use std::boxed::HEAP;
71 /// let foo = box(HEAP) 5;
75 #[lang = "exchange_heap"]
76 #[unstable(feature = "alloc",
77 reason = "may be renamed; uncertain about custom allocator design")]
78 pub static HEAP: () = ();
80 /// A pointer type for heap allocation.
82 /// See the [module-level documentation](../../std/boxed/index.html) for more.
84 #[stable(feature = "rust1", since = "1.0.0")]
85 pub struct Box<T>(Unique<T>);
88 /// Allocates memory on the heap and then moves `x` into it.
93 /// let x = Box::new(5);
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub fn new(x: T) -> Box<T> {
101 impl<T : ?Sized> Box<T> {
102 /// Constructs a box from the raw pointer.
104 /// After this function call, pointer is owned by resulting box.
105 /// In particular, it means that `Box` destructor calls destructor
106 /// of `T` and releases memory. Since the way `Box` allocates and
107 /// releases memory is unspecified, so the only valid pointer to
108 /// pass to this function is the one taken from another `Box` with
109 /// `box::into_raw` function.
111 /// Function is unsafe, because improper use of this function may
112 /// lead to memory problems like double-free, for example if the
113 /// function is called twice on the same raw pointer.
114 #[unstable(feature = "alloc",
115 reason = "may be renamed or moved out of Box scope")]
116 pub unsafe fn from_raw(raw: *mut T) -> Self {
121 /// Consumes the `Box`, returning the wrapped raw pointer.
123 /// After call to this function, caller is responsible for the memory
124 /// previously managed by `Box`, in particular caller should properly
125 /// destroy `T` and release memory. The proper way to do it is to
126 /// convert pointer back to `Box` with `Box::from_raw` function, because
127 /// `Box` does not specify, how memory is allocated.
129 /// Function is unsafe, because result of this function is no longer
130 /// automatically managed that may lead to memory or other resource
137 /// let seventeen = Box::new(17u32);
138 /// let raw = unsafe { boxed::into_raw(seventeen) };
139 /// let boxed_again = unsafe { Box::from_raw(raw) };
141 #[unstable(feature = "alloc",
142 reason = "may be renamed")]
143 pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
147 #[stable(feature = "rust1", since = "1.0.0")]
148 impl<T: Default> Default for Box<T> {
149 #[stable(feature = "rust1", since = "1.0.0")]
150 fn default() -> Box<T> { box Default::default() }
153 #[stable(feature = "rust1", since = "1.0.0")]
154 impl<T> Default for Box<[T]> {
155 #[stable(feature = "rust1", since = "1.0.0")]
156 fn default() -> Box<[T]> { box [] }
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl<T: Clone> Clone for Box<T> {
161 /// Returns a new box with a `clone()` of this box's contents.
166 /// let x = Box::new(5);
167 /// let y = x.clone();
170 fn clone(&self) -> Box<T> { box {(**self).clone()} }
172 /// Copies `source`'s contents into `self` without creating a new allocation.
177 /// let x = Box::new(5);
178 /// let mut y = Box::new(10);
180 /// y.clone_from(&x);
182 /// assert_eq!(*y, 5);
185 fn clone_from(&mut self, source: &Box<T>) {
186 (**self).clone_from(&(**source));
190 #[stable(feature = "rust1", since = "1.0.0")]
191 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
193 fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
195 fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
200 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
201 PartialOrd::partial_cmp(&**self, &**other)
204 fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
206 fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
208 fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
210 fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
212 #[stable(feature = "rust1", since = "1.0.0")]
213 impl<T: ?Sized + Ord> Ord for Box<T> {
215 fn cmp(&self, other: &Box<T>) -> Ordering {
216 Ord::cmp(&**self, &**other)
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl<T: ?Sized + Eq> Eq for Box<T> {}
222 impl<S: hash::Hasher, T: ?Sized + Hash<S>> Hash<S> for Box<T> {
224 fn hash(&self, state: &mut S) {
225 (**self).hash(state);
229 /// Extension methods for an owning `Any` trait object.
230 #[unstable(feature = "alloc",
231 reason = "this trait will likely disappear once compiler bugs blocking \
232 a direct impl on `Box<Any>` have been fixed ")]
233 // FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
234 // removing this please make sure that you can downcase on
235 // `Box<Any + Send>` as well as `Box<Any>`
237 /// Returns the boxed value if it is of type `T`, or
238 /// `Err(Self)` if it isn't.
239 #[stable(feature = "rust1", since = "1.0.0")]
240 fn downcast<T: 'static>(self) -> Result<Box<T>, Self>;
243 #[stable(feature = "rust1", since = "1.0.0")]
244 impl BoxAny for Box<Any> {
246 fn downcast<T: 'static>(self) -> Result<Box<T>, Box<Any>> {
249 // Get the raw representation of the trait object
250 let to: TraitObject =
251 mem::transmute::<Box<Any>, TraitObject>(self);
253 // Extract the data pointer
254 Ok(mem::transmute(to.data))
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
264 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
265 fmt::Display::fmt(&**self, f)
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
271 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
272 fmt::Debug::fmt(&**self, f)
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl fmt::Debug for Box<Any> {
278 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
283 #[stable(feature = "rust1", since = "1.0.0")]
284 impl<T: ?Sized> Deref for Box<T> {
287 fn deref(&self) -> &T { &**self }
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T: ?Sized> DerefMut for Box<T> {
292 fn deref_mut(&mut self) -> &mut T { &mut **self }
295 #[stable(feature = "rust1", since = "1.0.0")]
296 impl<I: Iterator + ?Sized> Iterator for Box<I> {
298 fn next(&mut self) -> Option<I::Item> { (**self).next() }
299 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
301 #[stable(feature = "rust1", since = "1.0.0")]
302 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
303 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
308 #[stable(feature = "rust1", since = "1.0.0")]
309 impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
310 fn from_error(err: E) -> Box<Error + 'a> {