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")]
61 use core
::cmp
::Ordering
;
63 use core
::hash
::{self, Hash}
;
64 use core
::marker
::{self, Unsize}
;
66 use core
::ops
::{CoerceUnsized, Deref, DerefMut}
;
67 use core
::ops
::{Placer, Boxed, Place, InPlace, BoxPlace}
;
68 use core
::ptr
::{self, Unique}
;
69 use core
::raw
::TraitObject
;
70 use core
::convert
::From
;
72 /// A value that represents the heap. This is the default place that the `box`
73 /// keyword allocates into when no place is supplied.
75 /// The following two examples are equivalent:
78 /// #![feature(box_heap)]
80 /// #![feature(box_syntax, placement_in_syntax)]
81 /// use std::boxed::HEAP;
84 /// let foo: Box<i32> = in HEAP { 5 };
88 #[unstable(feature = "box_heap",
89 reason
= "may be renamed; uncertain about custom allocator design",
91 pub const HEAP
: ExchangeHeapSingleton
= ExchangeHeapSingleton { _force_singleton: () }
;
93 /// This the singleton type used solely for `boxed::HEAP`.
94 #[unstable(feature = "box_heap",
95 reason
= "may be renamed; uncertain about custom allocator design",
97 #[derive(Copy, Clone)]
98 pub struct ExchangeHeapSingleton
{
102 /// A pointer type for heap allocation.
104 /// See the [module-level documentation](../../std/boxed/index.html) for more.
105 #[lang = "owned_box"]
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct Box
<T
: ?Sized
>(Unique
<T
>);
109 /// `IntermediateBox` represents uninitialized backing storage for `Box`.
111 /// FIXME (pnkfelix): Ideally we would just reuse `Box<T>` instead of
112 /// introducing a separate `IntermediateBox<T>`; but then you hit
113 /// issues when you e.g. attempt to destructure an instance of `Box`,
114 /// since it is a lang item and so it gets special handling by the
115 /// compiler. Easier just to make this parallel type for now.
117 /// FIXME (pnkfelix): Currently the `box` protocol only supports
118 /// creating instances of sized types. This IntermediateBox is
119 /// designed to be forward-compatible with a future protocol that
120 /// supports creating instances of unsized types; that is why the type
121 /// parameter has the `?Sized` generalization marker, and is also why
122 /// this carries an explicit size. However, it probably does not need
123 /// to carry the explicit alignment; that is just a work-around for
124 /// the fact that the `align_of` intrinsic currently requires the
125 /// input type to be Sized (which I do not think is strictly
127 #[unstable(feature = "placement_in",
128 reason
= "placement box design is still being worked out.",
130 pub struct IntermediateBox
<T
: ?Sized
> {
134 marker
: marker
::PhantomData
<*mut T
>,
137 #[unstable(feature = "placement_in",
138 reason
= "placement box design is still being worked out.",
140 impl<T
> Place
<T
> for IntermediateBox
<T
> {
141 fn pointer(&mut self) -> *mut T
{
146 unsafe fn finalize
<T
>(b
: IntermediateBox
<T
>) -> Box
<T
> {
147 let p
= b
.ptr
as *mut T
;
152 fn make_place
<T
>() -> IntermediateBox
<T
> {
153 let size
= mem
::size_of
::<T
>();
154 let align
= mem
::align_of
::<T
>();
156 let p
= if size
== 0 {
157 heap
::EMPTY
as *mut u8
159 let p
= unsafe { heap::allocate(size, align) }
;
161 panic
!("Box make_place allocation failure.");
170 marker
: marker
::PhantomData
,
174 #[unstable(feature = "placement_in",
175 reason
= "placement box design is still being worked out.",
177 impl<T
> BoxPlace
<T
> for IntermediateBox
<T
> {
178 fn make_place() -> IntermediateBox
<T
> {
183 #[unstable(feature = "placement_in",
184 reason
= "placement box design is still being worked out.",
186 impl<T
> InPlace
<T
> for IntermediateBox
<T
> {
188 unsafe fn finalize(self) -> Box
<T
> {
193 #[unstable(feature = "placement_new_protocol", issue = "27779")]
194 impl<T
> Boxed
for Box
<T
> {
196 type Place
= IntermediateBox
<T
>;
197 unsafe fn finalize(b
: IntermediateBox
<T
>) -> Box
<T
> {
202 #[unstable(feature = "placement_in",
203 reason
= "placement box design is still being worked out.",
205 impl<T
> Placer
<T
> for ExchangeHeapSingleton
{
206 type Place
= IntermediateBox
<T
>;
208 fn make_place(self) -> IntermediateBox
<T
> {
213 #[unstable(feature = "placement_in",
214 reason
= "placement box design is still being worked out.",
216 impl<T
: ?Sized
> Drop
for IntermediateBox
<T
> {
219 unsafe { heap::deallocate(self.ptr, self.size, self.align) }
225 /// Allocates memory on the heap and then places `x` into it.
230 /// let five = Box::new(5);
232 #[stable(feature = "rust1", since = "1.0.0")]
234 pub fn new(x
: T
) -> Box
<T
> {
239 impl<T
: ?Sized
> Box
<T
> {
240 /// Constructs a box from a raw pointer.
242 /// After calling this function, the raw pointer is owned by the
243 /// resulting `Box`. Specifically, the `Box` destructor will call
244 /// the destructor of `T` and free the allocated memory. Since the
245 /// way `Box` allocates and releases memory is unspecified, the
246 /// only valid pointer to pass to this function is the one taken
247 /// from another `Box` via the `Box::into_raw` function.
249 /// This function is unsafe because improper use may lead to
250 /// memory problems. For example, a double-free may occur if the
251 /// function is called twice on the same raw pointer.
252 #[stable(feature = "box_raw", since = "1.4.0")]
254 pub unsafe fn from_raw(raw
: *mut T
) -> Self {
258 /// Consumes the `Box`, returning the wrapped raw pointer.
260 /// After calling this function, the caller is responsible for the
261 /// memory previously managed by the `Box`. In particular, the
262 /// caller should properly destroy `T` and release the memory. The
263 /// proper way to do so is to convert the raw pointer back into a
264 /// `Box` with the `Box::from_raw` function.
269 /// let seventeen = Box::new(17);
270 /// let raw = Box::into_raw(seventeen);
271 /// let boxed_again = unsafe { Box::from_raw(raw) };
273 #[stable(feature = "box_raw", since = "1.4.0")]
275 pub fn into_raw(b
: Box
<T
>) -> *mut T
{
276 unsafe { mem::transmute(b) }
280 #[stable(feature = "rust1", since = "1.0.0")]
281 impl<T
: Default
> Default
for Box
<T
> {
282 fn default() -> Box
<T
> {
283 box Default
::default()
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T
> Default
for Box
<[T
]> {
289 fn default() -> Box
<[T
]> {
290 Box
::<[T
; 0]>::new([])
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl<T
: Clone
> Clone
for Box
<T
> {
296 /// Returns a new box with a `clone()` of this box's contents.
301 /// let x = Box::new(5);
302 /// let y = x.clone();
306 fn clone(&self) -> Box
<T
> {
307 box { (**self).clone() }
309 /// Copies `source`'s contents into `self` without creating a new allocation.
314 /// let x = Box::new(5);
315 /// let mut y = Box::new(10);
317 /// y.clone_from(&x);
319 /// assert_eq!(*y, 5);
322 fn clone_from(&mut self, source
: &Box
<T
>) {
323 (**self).clone_from(&(**source
));
328 #[stable(feature = "box_slice_clone", since = "1.3.0")]
329 impl Clone
for Box
<str> {
330 fn clone(&self) -> Self {
331 let len
= self.len();
332 let buf
= RawVec
::with_capacity(len
);
334 ptr
::copy_nonoverlapping(self.as_ptr(), buf
.ptr(), len
);
335 mem
::transmute(buf
.into_box()) // bytes to str ~magic
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Box
<T
> {
343 fn eq(&self, other
: &Box
<T
>) -> bool
{
344 PartialEq
::eq(&**self, &**other
)
347 fn ne(&self, other
: &Box
<T
>) -> bool
{
348 PartialEq
::ne(&**self, &**other
)
351 #[stable(feature = "rust1", since = "1.0.0")]
352 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Box
<T
> {
354 fn partial_cmp(&self, other
: &Box
<T
>) -> Option
<Ordering
> {
355 PartialOrd
::partial_cmp(&**self, &**other
)
358 fn lt(&self, other
: &Box
<T
>) -> bool
{
359 PartialOrd
::lt(&**self, &**other
)
362 fn le(&self, other
: &Box
<T
>) -> bool
{
363 PartialOrd
::le(&**self, &**other
)
366 fn ge(&self, other
: &Box
<T
>) -> bool
{
367 PartialOrd
::ge(&**self, &**other
)
370 fn gt(&self, other
: &Box
<T
>) -> bool
{
371 PartialOrd
::gt(&**self, &**other
)
374 #[stable(feature = "rust1", since = "1.0.0")]
375 impl<T
: ?Sized
+ Ord
> Ord
for Box
<T
> {
377 fn cmp(&self, other
: &Box
<T
>) -> Ordering
{
378 Ord
::cmp(&**self, &**other
)
381 #[stable(feature = "rust1", since = "1.0.0")]
382 impl<T
: ?Sized
+ Eq
> Eq
for Box
<T
> {}
384 #[stable(feature = "rust1", since = "1.0.0")]
385 impl<T
: ?Sized
+ Hash
> Hash
for Box
<T
> {
386 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
387 (**self).hash(state
);
391 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
392 impl<T
> From
<T
> for Box
<T
> {
393 fn from(t
: T
) -> Self {
400 #[stable(feature = "rust1", since = "1.0.0")]
401 /// Attempt to downcast the box to a concrete type.
402 pub fn downcast
<T
: Any
>(self) -> Result
<Box
<T
>, Box
<Any
>> {
405 // Get the raw representation of the trait object
406 let raw
= Box
::into_raw(self);
407 let to
: TraitObject
= mem
::transmute
::<*mut Any
, TraitObject
>(raw
);
409 // Extract the data pointer
410 Ok(Box
::from_raw(to
.data
as *mut T
))
418 impl Box
<Any
+ Send
> {
420 #[stable(feature = "rust1", since = "1.0.0")]
421 /// Attempt to downcast the box to a concrete type.
422 pub fn downcast
<T
: Any
>(self) -> Result
<Box
<T
>, Box
<Any
+ Send
>> {
423 <Box
<Any
>>::downcast(self).map_err(|s
| unsafe {
424 // reapply the Send marker
425 mem
::transmute
::<Box
<Any
>, Box
<Any
+ Send
>>(s
)
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<T
: fmt
::Display
+ ?Sized
> fmt
::Display
for Box
<T
> {
432 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
433 fmt
::Display
::fmt(&**self, f
)
437 #[stable(feature = "rust1", since = "1.0.0")]
438 impl<T
: fmt
::Debug
+ ?Sized
> fmt
::Debug
for Box
<T
> {
439 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
440 fmt
::Debug
::fmt(&**self, f
)
444 #[stable(feature = "rust1", since = "1.0.0")]
445 impl<T
: ?Sized
> fmt
::Pointer
for Box
<T
> {
446 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
447 // It's not possible to extract the inner Uniq directly from the Box,
448 // instead we cast it to a *const which aliases the Unique
449 let ptr
: *const T
= &**self;
450 fmt
::Pointer
::fmt(&ptr
, f
)
454 #[stable(feature = "rust1", since = "1.0.0")]
455 impl<T
: ?Sized
> Deref
for Box
<T
> {
458 fn deref(&self) -> &T
{
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl<T
: ?Sized
> DerefMut
for Box
<T
> {
465 fn deref_mut(&mut self) -> &mut T
{
470 #[stable(feature = "rust1", since = "1.0.0")]
471 impl<I
: Iterator
+ ?Sized
> Iterator
for Box
<I
> {
473 fn next(&mut self) -> Option
<I
::Item
> {
476 fn size_hint(&self) -> (usize, Option
<usize>) {
480 #[stable(feature = "rust1", since = "1.0.0")]
481 impl<I
: DoubleEndedIterator
+ ?Sized
> DoubleEndedIterator
for Box
<I
> {
482 fn next_back(&mut self) -> Option
<I
::Item
> {
486 #[stable(feature = "rust1", since = "1.0.0")]
487 impl<I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for Box
<I
> {}
490 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
491 /// closure objects. The idea is that where one would normally store a
492 /// `Box<FnOnce()>` in a data structure, you should use
493 /// `Box<FnBox()>`. The two traits behave essentially the same, except
494 /// that a `FnBox` closure can only be called if it is boxed. (Note
495 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
496 /// closures become directly usable.)
500 /// Here is a snippet of code which creates a hashmap full of boxed
501 /// once closures and then removes them one by one, calling each
502 /// closure as it is removed. Note that the type of the closures
503 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
507 /// #![feature(fnbox)]
509 /// use std::boxed::FnBox;
510 /// use std::collections::HashMap;
512 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
513 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
514 /// map.insert(1, Box::new(|| 22));
515 /// map.insert(2, Box::new(|| 44));
520 /// let mut map = make_map();
521 /// for i in &[1, 2] {
522 /// let f = map.remove(&i).unwrap();
523 /// assert_eq!(f(), i * 22);
528 #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "28796")]
532 fn call_box(self: Box
<Self>, args
: A
) -> Self::Output
;
535 #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "28796")]
536 impl<A
, F
> FnBox
<A
> for F
where F
: FnOnce
<A
>
538 type Output
= F
::Output
;
540 fn call_box(self: Box
<F
>, args
: A
) -> F
::Output
{
545 #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "28796")]
546 impl<'a
, A
, R
> FnOnce
<A
> for Box
<FnBox
<A
, Output
= R
> + 'a
> {
549 extern "rust-call" fn call_once(self, args
: A
) -> R
{
554 #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "28796")]
555 impl<'a
, A
, R
> FnOnce
<A
> for Box
<FnBox
<A
, Output
= R
> + Send
+ 'a
> {
558 extern "rust-call" fn call_once(self, args
: A
) -> R
{
563 #[unstable(feature = "coerce_unsized", issue = "27732")]
564 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Box
<U
>> for Box
<T
> {}
566 #[stable(feature = "box_slice_clone", since = "1.3.0")]
567 impl<T
: Clone
> Clone
for Box
<[T
]> {
568 fn clone(&self) -> Self {
569 let mut new
= BoxBuilder
{
570 data
: RawVec
::with_capacity(self.len()),
574 let mut target
= new
.data
.ptr();
576 for item
in self.iter() {
578 ptr
::write(target
, item
.clone());
579 target
= target
.offset(1);
585 return unsafe { new.into_box() }
;
587 // Helper type for responding to panics correctly.
588 struct BoxBuilder
<T
> {
593 impl<T
> BoxBuilder
<T
> {
594 unsafe fn into_box(self) -> Box
<[T
]> {
595 let raw
= ptr
::read(&self.data
);
601 impl<T
> Drop
for BoxBuilder
<T
> {
603 let mut data
= self.data
.ptr();
604 let max
= unsafe { data.offset(self.len as isize) }
;
609 data
= data
.offset(1);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 impl<T
: ?Sized
> borrow
::Borrow
<T
> for Box
<T
> {
619 fn borrow(&self) -> &T
{
624 #[stable(feature = "rust1", since = "1.0.0")]
625 impl<T
: ?Sized
> borrow
::BorrowMut
<T
> for Box
<T
> {
626 fn borrow_mut(&mut self) -> &mut T
{
631 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
632 impl<T
: ?Sized
> AsRef
<T
> for Box
<T
> {
633 fn as_ref(&self) -> &T
{
638 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
639 impl<T
: ?Sized
> AsMut
<T
> for Box
<T
> {
640 fn as_mut(&mut self) -> &mut T
{