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.
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
27 //! let x = Box::new(5);
30 //! Creating a recursive data structure:
35 //! Cons(T, Box<List<T>>),
40 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
41 //! println!("{:?}", list);
45 //! This will print `Cons(1, Box(Cons(2, Box(Nil))))`.
47 #![stable(feature = "rust1", since = "1.0.0")]
52 use core::cmp::Ordering;
53 use core::default::Default;
54 use core::error::{Error, FromError};
56 use core::hash::{self, Hash};
58 use core::ops::{Deref, DerefMut};
59 use core::ptr::Unique;
60 use core::raw::TraitObject;
62 /// A value that represents the heap. This is the default place that the `box`
63 /// keyword allocates into when no place is supplied.
65 /// The following two examples are equivalent:
68 /// # #![feature(alloc)]
69 /// #![feature(box_syntax)]
70 /// use std::boxed::HEAP;
73 /// let foo = box(HEAP) 5;
77 #[lang = "exchange_heap"]
78 #[unstable(feature = "alloc",
79 reason = "may be renamed; uncertain about custom allocator design")]
80 pub static HEAP: () = ();
82 /// A pointer type for heap allocation.
84 /// See the [module-level documentation](../../std/boxed/index.html) for more.
86 #[stable(feature = "rust1", since = "1.0.0")]
87 pub struct Box<T>(Unique<T>);
90 /// Allocates memory on the heap and then moves `x` into it.
95 /// let x = Box::new(5);
97 #[stable(feature = "rust1", since = "1.0.0")]
99 pub fn new(x: T) -> Box<T> {
104 impl<T : ?Sized> Box<T> {
105 /// Constructs a box from the raw pointer.
107 /// After this function call, pointer is owned by resulting box.
108 /// In particular, it means that `Box` destructor calls destructor
109 /// of `T` and releases memory. Since the way `Box` allocates and
110 /// releases memory is unspecified, the only valid pointer to pass
111 /// to this function is the one taken from another `Box` with
112 /// `boxed::into_raw` function.
114 /// Function is unsafe, because improper use of this function may
115 /// lead to memory problems like double-free, for example if the
116 /// function is called twice on the same raw pointer.
117 #[unstable(feature = "alloc",
118 reason = "may be renamed or moved out of Box scope")]
120 pub unsafe fn from_raw(raw: *mut T) -> Self {
125 /// Consumes the `Box`, returning the wrapped raw pointer.
127 /// After call to this function, caller is responsible for the memory
128 /// previously managed by `Box`, in particular caller should properly
129 /// destroy `T` and release memory. The proper way to do it is to
130 /// convert pointer back to `Box` with `Box::from_raw` function, because
131 /// `Box` does not specify, how memory is allocated.
133 /// Function is unsafe, because result of this function is no longer
134 /// automatically managed that may lead to memory or other resource
139 /// # #![feature(alloc)]
142 /// let seventeen = Box::new(17u32);
143 /// let raw = unsafe { boxed::into_raw(seventeen) };
144 /// let boxed_again = unsafe { Box::from_raw(raw) };
146 #[unstable(feature = "alloc",
147 reason = "may be renamed")]
149 pub unsafe fn into_raw<T : ?Sized>(b: Box<T>) -> *mut T {
153 #[stable(feature = "rust1", since = "1.0.0")]
154 impl<T: Default> Default for Box<T> {
155 #[stable(feature = "rust1", since = "1.0.0")]
156 fn default() -> Box<T> { box Default::default() }
159 #[stable(feature = "rust1", since = "1.0.0")]
160 impl<T> Default for Box<[T]> {
161 #[stable(feature = "rust1", since = "1.0.0")]
162 fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
165 #[stable(feature = "rust1", since = "1.0.0")]
166 impl<T: Clone> Clone for Box<T> {
167 /// Returns a new box with a `clone()` of this box's contents.
172 /// let x = Box::new(5);
173 /// let y = x.clone();
176 fn clone(&self) -> Box<T> { box {(**self).clone()} }
178 /// Copies `source`'s contents into `self` without creating a new allocation.
183 /// # #![feature(alloc, core)]
184 /// let x = Box::new(5);
185 /// let mut y = Box::new(10);
187 /// y.clone_from(&x);
189 /// assert_eq!(*y, 5);
192 fn clone_from(&mut self, source: &Box<T>) {
193 (**self).clone_from(&(**source));
197 #[stable(feature = "rust1", since = "1.0.0")]
198 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
200 fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
202 fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
204 #[stable(feature = "rust1", since = "1.0.0")]
205 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
207 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
208 PartialOrd::partial_cmp(&**self, &**other)
211 fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
213 fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
215 fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
217 fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
219 #[stable(feature = "rust1", since = "1.0.0")]
220 impl<T: ?Sized + Ord> Ord for Box<T> {
222 fn cmp(&self, other: &Box<T>) -> Ordering {
223 Ord::cmp(&**self, &**other)
226 #[stable(feature = "rust1", since = "1.0.0")]
227 impl<T: ?Sized + Eq> Eq for Box<T> {}
229 #[stable(feature = "rust1", since = "1.0.0")]
230 impl<T: ?Sized + Hash> Hash for Box<T> {
231 fn hash<H: hash::Hasher>(&self, state: &mut H) {
232 (**self).hash(state);
236 /// Extension methods for an owning `Any` trait object.
237 #[unstable(feature = "alloc",
238 reason = "this trait will likely disappear once compiler bugs blocking \
239 a direct impl on `Box<Any>` have been fixed ")]
240 // FIXME(#18737): this should be a direct impl on `Box<Any>`. If you're
241 // removing this please make sure that you can downcase on
242 // `Box<Any + Send>` as well as `Box<Any>`
244 /// Returns the boxed value if it is of type `T`, or
245 /// `Err(Self)` if it isn't.
246 #[stable(feature = "rust1", since = "1.0.0")]
247 fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>>;
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl BoxAny for Box<Any> {
253 fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
256 // Get the raw representation of the trait object
257 let raw = into_raw(self);
258 let to: TraitObject =
259 mem::transmute::<*mut Any, TraitObject>(raw);
261 // Extract the data pointer
262 Ok(Box::from_raw(to.data as *mut T))
270 #[stable(feature = "rust1", since = "1.0.0")]
271 impl BoxAny for Box<Any+Send> {
273 fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
274 <Box<Any>>::downcast(self)
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)
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)
292 #[stable(feature = "rust1", since = "1.0.0")]
293 impl fmt::Debug for Box<Any> {
294 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<T: ?Sized> Deref for Box<T> {
303 fn deref(&self) -> &T { &**self }
306 #[stable(feature = "rust1", since = "1.0.0")]
307 impl<T: ?Sized> DerefMut for Box<T> {
308 fn deref_mut(&mut self) -> &mut T { &mut **self }
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<I: Iterator + ?Sized> Iterator for Box<I> {
314 fn next(&mut self) -> Option<I::Item> { (**self).next() }
315 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
317 #[stable(feature = "rust1", since = "1.0.0")]
318 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
319 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl<'a, E: Error + 'a> FromError<E> for Box<Error + 'a> {
326 fn from_error(err: E) -> Box<Error + 'a> {