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
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` looked like this:
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.
52 #![stable(feature = "rust1", since = "1.0.0")]
57 use core
::cmp
::Ordering
;
59 use core
::hash
::{self, Hash}
;
61 use core
::ops
::{Deref, DerefMut}
;
62 use core
::ptr
::{Unique}
;
63 use core
::raw
::{TraitObject}
;
66 use core
::marker
::Unsize
;
68 use core
::ops
::CoerceUnsized
;
70 /// A value that represents the heap. This is the default place that the `box`
71 /// keyword allocates into when no place is supplied.
73 /// The following two examples are equivalent:
76 /// # #![feature(alloc)]
77 /// #![feature(box_syntax)]
78 /// use std::boxed::HEAP;
81 /// let foo = box(HEAP) 5;
85 #[lang = "exchange_heap"]
86 #[unstable(feature = "alloc",
87 reason
= "may be renamed; uncertain about custom allocator design")]
88 pub static HEAP
: () = ();
90 /// A pointer type for heap allocation.
92 /// See the [module-level documentation](../../std/boxed/index.html) for more.
94 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Box
<T
>(Unique
<T
>);
99 /// Allocates memory on the heap and then moves `x` into it.
104 /// let x = Box::new(5);
106 #[stable(feature = "rust1", since = "1.0.0")]
108 pub fn new(x
: T
) -> Box
<T
> {
113 impl<T
: ?Sized
> Box
<T
> {
114 /// Constructs a box from the raw pointer.
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.
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")]
129 pub unsafe fn from_raw(raw
: *mut T
) -> Self {
134 /// Consumes the `Box`, returning the wrapped raw pointer.
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.
142 /// Function is unsafe, because result of this function is no longer
143 /// automatically managed that may lead to memory or other resource
148 /// # #![feature(alloc)]
151 /// let seventeen = Box::new(17u32);
152 /// let raw = unsafe { boxed::into_raw(seventeen) };
153 /// let boxed_again = unsafe { Box::from_raw(raw) };
155 #[unstable(feature = "alloc",
156 reason
= "may be renamed")]
158 pub unsafe fn into_raw
<T
: ?Sized
>(b
: Box
<T
>) -> *mut T
{
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() }
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([]) }
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.
181 /// let x = Box::new(5);
182 /// let y = x.clone();
185 fn clone(&self) -> Box
<T
> { box {(**self).clone()}
}
187 /// Copies `source`'s contents into `self` without creating a new allocation.
192 /// # #![feature(alloc, core)]
193 /// let x = Box::new(5);
194 /// let mut y = Box::new(10);
196 /// y.clone_from(&x);
198 /// assert_eq!(*y, 5);
201 fn clone_from(&mut self, source
: &Box
<T
>) {
202 (**self).clone_from(&(**source
));
206 #[stable(feature = "rust1", since = "1.0.0")]
207 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Box
<T
> {
209 fn eq(&self, other
: &Box
<T
>) -> bool { PartialEq::eq(&**self, &**other) }
211 fn ne(&self, other
: &Box
<T
>) -> bool { PartialEq::ne(&**self, &**other) }
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Box
<T
> {
216 fn partial_cmp(&self, other
: &Box
<T
>) -> Option
<Ordering
> {
217 PartialOrd
::partial_cmp(&**self, &**other
)
220 fn lt(&self, other
: &Box
<T
>) -> bool { PartialOrd::lt(&**self, &**other) }
222 fn le(&self, other
: &Box
<T
>) -> bool { PartialOrd::le(&**self, &**other) }
224 fn ge(&self, other
: &Box
<T
>) -> bool { PartialOrd::ge(&**self, &**other) }
226 fn gt(&self, other
: &Box
<T
>) -> bool { PartialOrd::gt(&**self, &**other) }
228 #[stable(feature = "rust1", since = "1.0.0")]
229 impl<T
: ?Sized
+ Ord
> Ord
for Box
<T
> {
231 fn cmp(&self, other
: &Box
<T
>) -> Ordering
{
232 Ord
::cmp(&**self, &**other
)
235 #[stable(feature = "rust1", since = "1.0.0")]
236 impl<T
: ?Sized
+ Eq
> Eq
for Box
<T
> {}
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
);
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
>> {
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
);
257 // Extract the data pointer
258 Ok(Box
::from_raw(to
.data
as *mut T
))
266 impl Box
<Any
+ Send
> {
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
)
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<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
)
302 #[stable(feature = "rust1", since = "1.0.0")]
303 impl<T
: ?Sized
> Deref
for Box
<T
> {
306 fn deref(&self) -> &T { &**self }
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 }
314 #[stable(feature = "rust1", since = "1.0.0")]
315 impl<I
: Iterator
+ ?Sized
> Iterator
for Box
<I
> {
317 fn next(&mut self) -> Option
<I
::Item
> { (**self).next() }
318 fn size_hint(&self) -> (usize, Option
<usize>) { (**self).size_hint() }
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() }
324 #[stable(feature = "rust1", since = "1.0.0")]
325 impl<I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for Box
<I
> {}
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.)
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()
345 /// #![feature(core)]
347 /// use std::boxed::FnBox;
348 /// use std::collections::HashMap;
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));
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);
366 #[unstable(feature = "core", reason = "Newly introduced")]
370 fn call_box(self: Box
<Self>, args
: A
) -> Self::Output
;
373 impl<A
,F
> FnBox
<A
> for F
376 type Output
= F
::Output
;
378 fn call_box(self: Box
<F
>, args
: A
) -> F
::Output
{
383 impl<'a
,A
,R
> FnOnce
<A
> for Box
<FnBox
<A
,Output
=R
>+'a
> {
386 extern "rust-call" fn call_once(self, args
: A
) -> R
{
391 impl<'a
,A
,R
> FnOnce
<A
> for Box
<FnBox
<A
,Output
=R
>+Send
+'a
> {
394 extern "rust-call" fn call_once(self, args
: A
) -> R
{
400 impl<T
: ?Sized
+Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Box
<U
>> for Box
<T
> {}