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;
71 /// A value that represents the heap. This is the default place that the `box`
72 /// keyword allocates into when no place is supplied.
74 /// The following two examples are equivalent:
77 /// #![feature(box_heap)]
79 /// #![feature(box_syntax, placement_in_syntax)]
80 /// use std::boxed::HEAP;
83 /// let foo = box(HEAP) 5;
87 #[lang = "exchange_heap"]
88 #[unstable(feature = "box_heap",
89 reason = "may be renamed; uncertain about custom allocator design",
91 pub const HEAP: ExchangeHeapSingleton =
92 ExchangeHeapSingleton { _force_singleton: () };
94 /// This the singleton type used solely for `boxed::HEAP`.
95 #[unstable(feature = "box_heap",
96 reason = "may be renamed; uncertain about custom allocator design",
98 #[derive(Copy, Clone)]
99 pub struct ExchangeHeapSingleton {
100 _force_singleton: (),
103 /// A pointer type for heap allocation.
105 /// See the [module-level documentation](../../std/boxed/index.html) for more.
106 #[lang = "owned_box"]
107 #[stable(feature = "rust1", since = "1.0.0")]
109 pub struct Box<T: ?Sized>(Unique<T>);
111 /// `IntermediateBox` represents uninitialized backing storage for `Box`.
113 /// FIXME (pnkfelix): Ideally we would just reuse `Box<T>` instead of
114 /// introducing a separate `IntermediateBox<T>`; but then you hit
115 /// issues when you e.g. attempt to destructure an instance of `Box`,
116 /// since it is a lang item and so it gets special handling by the
117 /// compiler. Easier just to make this parallel type for now.
119 /// FIXME (pnkfelix): Currently the `box` protocol only supports
120 /// creating instances of sized types. This IntermediateBox is
121 /// designed to be forward-compatible with a future protocol that
122 /// supports creating instances of unsized types; that is why the type
123 /// parameter has the `?Sized` generalization marker, and is also why
124 /// this carries an explicit size. However, it probably does not need
125 /// to carry the explicit alignment; that is just a work-around for
126 /// the fact that the `align_of` intrinsic currently requires the
127 /// input type to be Sized (which I do not think is strictly
129 #[unstable(feature = "placement_in",
130 reason = "placement box design is still being worked out.",
132 pub struct IntermediateBox<T: ?Sized> {
136 marker: marker::PhantomData<*mut T>,
139 impl<T> Place<T> for IntermediateBox<T> {
140 fn pointer(&mut self) -> *mut T {
141 unsafe { ::core::mem::transmute(self.ptr) }
145 unsafe fn finalize<T>(b: IntermediateBox<T>) -> Box<T> {
146 let p = b.ptr as *mut T;
151 fn make_place<T>() -> IntermediateBox<T> {
152 let size = mem::size_of::<T>();
153 let align = mem::align_of::<T>();
155 let p = if size == 0 {
156 heap::EMPTY as *mut u8
158 let p = unsafe { heap::allocate(size, align) };
160 panic!("Box make_place allocation failure.");
165 IntermediateBox { ptr: p, size: size, align: align, marker: marker::PhantomData }
168 impl<T> BoxPlace<T> for IntermediateBox<T> {
169 fn make_place() -> IntermediateBox<T> {
174 impl<T> InPlace<T> for IntermediateBox<T> {
176 unsafe fn finalize(self) -> Box<T> {
181 impl<T> Boxed for Box<T> {
183 type Place = IntermediateBox<T>;
184 unsafe fn finalize(b: IntermediateBox<T>) -> Box<T> {
189 impl<T> Placer<T> for ExchangeHeapSingleton {
190 type Place = IntermediateBox<T>;
192 fn make_place(self) -> IntermediateBox<T> {
197 impl<T: ?Sized> Drop for IntermediateBox<T> {
200 unsafe { heap::deallocate(self.ptr, self.size, self.align) }
206 /// Allocates memory on the heap and then moves `x` into it.
211 /// let x = Box::new(5);
213 #[stable(feature = "rust1", since = "1.0.0")]
215 pub fn new(x: T) -> Box<T> {
220 impl<T : ?Sized> Box<T> {
221 /// Constructs a box from the raw pointer.
223 /// After this function call, pointer is owned by resulting box.
224 /// In particular, it means that `Box` destructor calls destructor
225 /// of `T` and releases memory. Since the way `Box` allocates and
226 /// releases memory is unspecified, the only valid pointer to pass
227 /// to this function is the one taken from another `Box` with
228 /// `Box::into_raw` function.
230 /// Function is unsafe, because improper use of this function may
231 /// lead to memory problems like double-free, for example if the
232 /// function is called twice on the same raw pointer.
233 #[stable(feature = "box_raw", since = "1.4.0")]
235 pub unsafe fn from_raw(raw: *mut T) -> Self {
239 /// Consumes the `Box`, returning the wrapped raw pointer.
241 /// After call to this function, caller is responsible for the memory
242 /// previously managed by `Box`, in particular caller should properly
243 /// destroy `T` and release memory. The proper way to do it is to
244 /// convert pointer back to `Box` with `Box::from_raw` function, because
245 /// `Box` does not specify, how memory is allocated.
250 /// let seventeen = Box::new(17u32);
251 /// let raw = Box::into_raw(seventeen);
252 /// let boxed_again = unsafe { Box::from_raw(raw) };
254 #[stable(feature = "box_raw", since = "1.4.0")]
256 pub fn into_raw(b: Box<T>) -> *mut T {
257 unsafe { mem::transmute(b) }
261 #[stable(feature = "rust1", since = "1.0.0")]
262 impl<T: Default> Default for Box<T> {
263 #[stable(feature = "rust1", since = "1.0.0")]
264 fn default() -> Box<T> {
265 box Default::default()
269 #[stable(feature = "rust1", since = "1.0.0")]
270 impl<T> Default for Box<[T]> {
271 #[stable(feature = "rust1", since = "1.0.0")]
272 fn default() -> Box<[T]> {
273 Box::<[T; 0]>::new([])
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl<T: Clone> Clone for Box<T> {
279 /// Returns a new box with a `clone()` of this box's contents.
284 /// let x = Box::new(5);
285 /// let y = x.clone();
289 fn clone(&self) -> Box<T> {
290 box { (**self).clone() }
292 /// Copies `source`'s contents into `self` without creating a new allocation.
297 /// let x = Box::new(5);
298 /// let mut y = Box::new(10);
300 /// y.clone_from(&x);
302 /// assert_eq!(*y, 5);
305 fn clone_from(&mut self, source: &Box<T>) {
306 (**self).clone_from(&(**source));
311 #[stable(feature = "box_slice_clone", since = "1.3.0")]
312 impl Clone for Box<str> {
313 fn clone(&self) -> Self {
314 let len = self.len();
315 let buf = RawVec::with_capacity(len);
317 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
318 mem::transmute(buf.into_box()) // bytes to str ~magic
323 #[stable(feature = "rust1", since = "1.0.0")]
324 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
326 fn eq(&self, other: &Box<T>) -> bool {
327 PartialEq::eq(&**self, &**other)
330 fn ne(&self, other: &Box<T>) -> bool {
331 PartialEq::ne(&**self, &**other)
334 #[stable(feature = "rust1", since = "1.0.0")]
335 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
337 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
338 PartialOrd::partial_cmp(&**self, &**other)
341 fn lt(&self, other: &Box<T>) -> bool {
342 PartialOrd::lt(&**self, &**other)
345 fn le(&self, other: &Box<T>) -> bool {
346 PartialOrd::le(&**self, &**other)
349 fn ge(&self, other: &Box<T>) -> bool {
350 PartialOrd::ge(&**self, &**other)
353 fn gt(&self, other: &Box<T>) -> bool {
354 PartialOrd::gt(&**self, &**other)
357 #[stable(feature = "rust1", since = "1.0.0")]
358 impl<T: ?Sized + Ord> Ord for Box<T> {
360 fn cmp(&self, other: &Box<T>) -> Ordering {
361 Ord::cmp(&**self, &**other)
364 #[stable(feature = "rust1", since = "1.0.0")]
365 impl<T: ?Sized + Eq> Eq for Box<T> {}
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<T: ?Sized + Hash> Hash for Box<T> {
369 fn hash<H: hash::Hasher>(&self, state: &mut H) {
370 (**self).hash(state);
376 #[stable(feature = "rust1", since = "1.0.0")]
377 /// Attempt to downcast the box to a concrete type.
378 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
381 // Get the raw representation of the trait object
382 let raw = Box::into_raw(self);
383 let to: TraitObject = mem::transmute::<*mut Any, TraitObject>(raw);
385 // Extract the data pointer
386 Ok(Box::from_raw(to.data as *mut T))
394 impl Box<Any + Send> {
396 #[stable(feature = "rust1", since = "1.0.0")]
397 /// Attempt to downcast the box to a concrete type.
398 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
399 <Box<Any>>::downcast(self).map_err(|s| unsafe {
400 // reapply the Send marker
401 mem::transmute::<Box<Any>, Box<Any + Send>>(s)
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
408 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
409 fmt::Display::fmt(&**self, f)
413 #[stable(feature = "rust1", since = "1.0.0")]
414 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
415 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
416 fmt::Debug::fmt(&**self, f)
420 #[stable(feature = "rust1", since = "1.0.0")]
421 impl<T> fmt::Pointer for Box<T> {
422 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
423 // It's not possible to extract the inner Uniq directly from the Box,
424 // instead we cast it to a *const which aliases the Unique
425 let ptr: *const T = &**self;
426 fmt::Pointer::fmt(&ptr, f)
430 #[stable(feature = "rust1", since = "1.0.0")]
431 impl<T: ?Sized> Deref for Box<T> {
434 fn deref(&self) -> &T {
439 #[stable(feature = "rust1", since = "1.0.0")]
440 impl<T: ?Sized> DerefMut for Box<T> {
441 fn deref_mut(&mut self) -> &mut T {
446 #[stable(feature = "rust1", since = "1.0.0")]
447 impl<I: Iterator + ?Sized> Iterator for Box<I> {
449 fn next(&mut self) -> Option<I::Item> {
452 fn size_hint(&self) -> (usize, Option<usize>) {
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
458 fn next_back(&mut self) -> Option<I::Item> {
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
466 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
467 /// closure objects. The idea is that where one would normally store a
468 /// `Box<FnOnce()>` in a data structure, you should use
469 /// `Box<FnBox()>`. The two traits behave essentially the same, except
470 /// that a `FnBox` closure can only be called if it is boxed. (Note
471 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
472 /// closures become directly usable.)
476 /// Here is a snippet of code which creates a hashmap full of boxed
477 /// once closures and then removes them one by one, calling each
478 /// closure as it is removed. Note that the type of the closures
479 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
483 /// #![feature(fnbox)]
485 /// use std::boxed::FnBox;
486 /// use std::collections::HashMap;
488 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
489 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
490 /// map.insert(1, Box::new(|| 22));
491 /// map.insert(2, Box::new(|| 44));
496 /// let mut map = make_map();
497 /// for i in &[1, 2] {
498 /// let f = map.remove(&i).unwrap();
499 /// assert_eq!(f(), i * 22);
504 #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "0")]
508 fn call_box(self: Box<Self>, args: A) -> Self::Output;
511 impl<A,F> FnBox<A> for F
514 type Output = F::Output;
516 fn call_box(self: Box<F>, args: A) -> F::Output {
521 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
524 extern "rust-call" fn call_once(self, args: A) -> R {
529 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
532 extern "rust-call" fn call_once(self, args: A) -> R {
537 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
539 #[stable(feature = "box_slice_clone", since = "1.3.0")]
540 impl<T: Clone> Clone for Box<[T]> {
541 fn clone(&self) -> Self {
542 let mut new = BoxBuilder { data: RawVec::with_capacity(self.len()), len: 0 };
544 let mut target = new.data.ptr();
546 for item in self.iter() {
548 ptr::write(target, item.clone());
549 target = target.offset(1);
555 return unsafe { new.into_box() };
557 // Helper type for responding to panics correctly.
558 struct BoxBuilder<T> {
563 impl<T> BoxBuilder<T> {
564 unsafe fn into_box(self) -> Box<[T]> {
565 let raw = ptr::read(&self.data);
571 impl<T> Drop for BoxBuilder<T> {
573 let mut data = self.data.ptr();
574 let max = unsafe { data.offset(self.len as isize) };
579 data = data.offset(1);
587 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
588 fn borrow(&self) -> &T {
593 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
594 fn borrow_mut(&mut self) -> &mut T {