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<i32> = in HEAP { 5 };
87 #[unstable(feature = "box_heap",
88 reason = "may be renamed; uncertain about custom allocator design",
90 pub const HEAP: ExchangeHeapSingleton =
91 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 { _force_singleton: () }
100 /// A pointer type for heap allocation.
102 /// See the [module-level documentation](../../std/boxed/index.html) for more.
103 #[lang = "owned_box"]
104 #[stable(feature = "rust1", since = "1.0.0")]
106 pub struct Box<T: ?Sized>(Unique<T>);
108 /// `IntermediateBox` represents uninitialized backing storage for `Box`.
110 /// FIXME (pnkfelix): Ideally we would just reuse `Box<T>` instead of
111 /// introducing a separate `IntermediateBox<T>`; but then you hit
112 /// issues when you e.g. attempt to destructure an instance of `Box`,
113 /// since it is a lang item and so it gets special handling by the
114 /// compiler. Easier just to make this parallel type for now.
116 /// FIXME (pnkfelix): Currently the `box` protocol only supports
117 /// creating instances of sized types. This IntermediateBox is
118 /// designed to be forward-compatible with a future protocol that
119 /// supports creating instances of unsized types; that is why the type
120 /// parameter has the `?Sized` generalization marker, and is also why
121 /// this carries an explicit size. However, it probably does not need
122 /// to carry the explicit alignment; that is just a work-around for
123 /// the fact that the `align_of` intrinsic currently requires the
124 /// input type to be Sized (which I do not think is strictly
126 #[unstable(feature = "placement_in",
127 reason = "placement box design is still being worked out.",
129 pub struct IntermediateBox<T: ?Sized>{
133 marker: marker::PhantomData<*mut T>,
136 impl<T> Place<T> for IntermediateBox<T> {
137 fn pointer(&mut self) -> *mut T {
138 unsafe { ::core::mem::transmute(self.ptr) }
142 unsafe fn finalize<T>(b: IntermediateBox<T>) -> Box<T> {
143 let p = b.ptr as *mut T;
148 fn make_place<T>() -> IntermediateBox<T> {
149 let size = mem::size_of::<T>();
150 let align = mem::align_of::<T>();
152 let p = if size == 0 {
153 heap::EMPTY as *mut u8
156 heap::allocate(size, align)
159 panic!("Box make_place allocation failure.");
164 IntermediateBox { ptr: p, size: size, align: align, marker: marker::PhantomData }
167 impl<T> BoxPlace<T> for IntermediateBox<T> {
168 fn make_place() -> IntermediateBox<T> { make_place() }
171 impl<T> InPlace<T> for IntermediateBox<T> {
173 unsafe fn finalize(self) -> Box<T> { finalize(self) }
176 impl<T> Boxed for Box<T> {
178 type Place = IntermediateBox<T>;
179 unsafe fn finalize(b: IntermediateBox<T>) -> Box<T> { finalize(b) }
182 impl<T> Placer<T> for ExchangeHeapSingleton {
183 type Place = IntermediateBox<T>;
185 fn make_place(self) -> IntermediateBox<T> {
190 impl<T: ?Sized> Drop for IntermediateBox<T> {
194 heap::deallocate(self.ptr, self.size, self.align)
201 /// Allocates memory on the heap and then moves `x` into it.
206 /// let x = Box::new(5);
208 #[stable(feature = "rust1", since = "1.0.0")]
210 pub fn new(x: T) -> Box<T> {
215 impl<T : ?Sized> Box<T> {
216 /// Constructs a box from the raw pointer.
218 /// After this function call, pointer is owned by resulting box.
219 /// In particular, it means that `Box` destructor calls destructor
220 /// of `T` and releases memory. Since the way `Box` allocates and
221 /// releases memory is unspecified, the only valid pointer to pass
222 /// to this function is the one taken from another `Box` with
223 /// `Box::into_raw` function.
225 /// Function is unsafe, because improper use of this function may
226 /// lead to memory problems like double-free, for example if the
227 /// function is called twice on the same raw pointer.
228 #[stable(feature = "box_raw", since = "1.4.0")]
230 pub unsafe fn from_raw(raw: *mut T) -> Self {
234 /// Consumes the `Box`, returning the wrapped raw pointer.
236 /// After call to this function, caller is responsible for the memory
237 /// previously managed by `Box`, in particular caller should properly
238 /// destroy `T` and release memory. The proper way to do it is to
239 /// convert pointer back to `Box` with `Box::from_raw` function, because
240 /// `Box` does not specify, how memory is allocated.
245 /// let seventeen = Box::new(17u32);
246 /// let raw = Box::into_raw(seventeen);
247 /// let boxed_again = unsafe { Box::from_raw(raw) };
249 #[stable(feature = "box_raw", since = "1.4.0")]
251 pub fn into_raw(b: Box<T>) -> *mut T {
252 unsafe { mem::transmute(b) }
256 #[stable(feature = "rust1", since = "1.0.0")]
257 impl<T: Default> Default for Box<T> {
258 #[stable(feature = "rust1", since = "1.0.0")]
259 fn default() -> Box<T> { box Default::default() }
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<T> Default for Box<[T]> {
264 #[stable(feature = "rust1", since = "1.0.0")]
265 fn default() -> Box<[T]> { Box::<[T; 0]>::new([]) }
268 #[stable(feature = "rust1", since = "1.0.0")]
269 impl<T: Clone> Clone for Box<T> {
270 /// Returns a new box with a `clone()` of this box's contents.
275 /// let x = Box::new(5);
276 /// let y = x.clone();
279 fn clone(&self) -> Box<T> { box {(**self).clone()} }
280 /// Copies `source`'s contents into `self` without creating a new allocation.
285 /// let x = Box::new(5);
286 /// let mut y = Box::new(10);
288 /// y.clone_from(&x);
290 /// assert_eq!(*y, 5);
293 fn clone_from(&mut self, source: &Box<T>) {
294 (**self).clone_from(&(**source));
299 #[stable(feature = "box_slice_clone", since = "1.3.0")]
300 impl Clone for Box<str> {
301 fn clone(&self) -> Self {
302 let len = self.len();
303 let buf = RawVec::with_capacity(len);
305 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
306 mem::transmute(buf.into_box()) // bytes to str ~magic
311 #[stable(feature = "rust1", since = "1.0.0")]
312 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
314 fn eq(&self, other: &Box<T>) -> bool { PartialEq::eq(&**self, &**other) }
316 fn ne(&self, other: &Box<T>) -> bool { PartialEq::ne(&**self, &**other) }
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
321 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
322 PartialOrd::partial_cmp(&**self, &**other)
325 fn lt(&self, other: &Box<T>) -> bool { PartialOrd::lt(&**self, &**other) }
327 fn le(&self, other: &Box<T>) -> bool { PartialOrd::le(&**self, &**other) }
329 fn ge(&self, other: &Box<T>) -> bool { PartialOrd::ge(&**self, &**other) }
331 fn gt(&self, other: &Box<T>) -> bool { PartialOrd::gt(&**self, &**other) }
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl<T: ?Sized + Ord> Ord for Box<T> {
336 fn cmp(&self, other: &Box<T>) -> Ordering {
337 Ord::cmp(&**self, &**other)
340 #[stable(feature = "rust1", since = "1.0.0")]
341 impl<T: ?Sized + Eq> Eq for Box<T> {}
343 #[stable(feature = "rust1", since = "1.0.0")]
344 impl<T: ?Sized + Hash> Hash for Box<T> {
345 fn hash<H: hash::Hasher>(&self, state: &mut H) {
346 (**self).hash(state);
352 #[stable(feature = "rust1", since = "1.0.0")]
353 /// Attempt to downcast the box to a concrete type.
354 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
357 // Get the raw representation of the trait object
358 let raw = Box::into_raw(self);
359 let to: TraitObject =
360 mem::transmute::<*mut Any, TraitObject>(raw);
362 // Extract the data pointer
363 Ok(Box::from_raw(to.data as *mut T))
371 impl Box<Any + Send> {
373 #[stable(feature = "rust1", since = "1.0.0")]
374 /// Attempt to downcast the box to a concrete type.
375 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
376 <Box<Any>>::downcast(self).map_err(|s| unsafe {
377 // reapply the Send marker
378 mem::transmute::<Box<Any>, Box<Any + Send>>(s)
383 #[stable(feature = "rust1", since = "1.0.0")]
384 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
385 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
386 fmt::Display::fmt(&**self, f)
390 #[stable(feature = "rust1", since = "1.0.0")]
391 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
392 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
393 fmt::Debug::fmt(&**self, f)
397 #[stable(feature = "rust1", since = "1.0.0")]
398 impl<T> fmt::Pointer for Box<T> {
399 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400 // It's not possible to extract the inner Uniq directly from the Box,
401 // instead we cast it to a *const which aliases the Unique
402 let ptr: *const T = &**self;
403 fmt::Pointer::fmt(&ptr, f)
407 #[stable(feature = "rust1", since = "1.0.0")]
408 impl<T: ?Sized> Deref for Box<T> {
411 fn deref(&self) -> &T { &**self }
414 #[stable(feature = "rust1", since = "1.0.0")]
415 impl<T: ?Sized> DerefMut for Box<T> {
416 fn deref_mut(&mut self) -> &mut T { &mut **self }
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl<I: Iterator + ?Sized> Iterator for Box<I> {
422 fn next(&mut self) -> Option<I::Item> { (**self).next() }
423 fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
425 #[stable(feature = "rust1", since = "1.0.0")]
426 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
427 fn next_back(&mut self) -> Option<I::Item> { (**self).next_back() }
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
433 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
434 /// closure objects. The idea is that where one would normally store a
435 /// `Box<FnOnce()>` in a data structure, you should use
436 /// `Box<FnBox()>`. The two traits behave essentially the same, except
437 /// that a `FnBox` closure can only be called if it is boxed. (Note
438 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
439 /// closures become directly usable.)
443 /// Here is a snippet of code which creates a hashmap full of boxed
444 /// once closures and then removes them one by one, calling each
445 /// closure as it is removed. Note that the type of the closures
446 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
450 /// #![feature(fnbox)]
452 /// use std::boxed::FnBox;
453 /// use std::collections::HashMap;
455 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
456 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
457 /// map.insert(1, Box::new(|| 22));
458 /// map.insert(2, Box::new(|| 44));
463 /// let mut map = make_map();
464 /// for i in &[1, 2] {
465 /// let f = map.remove(&i).unwrap();
466 /// assert_eq!(f(), i * 22);
471 #[unstable(feature = "fnbox", reason = "Newly introduced", issue = "0")]
475 fn call_box(self: Box<Self>, args: A) -> Self::Output;
478 impl<A,F> FnBox<A> for F
481 type Output = F::Output;
483 fn call_box(self: Box<F>, args: A) -> F::Output {
488 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+'a> {
491 extern "rust-call" fn call_once(self, args: A) -> R {
496 impl<'a,A,R> FnOnce<A> for Box<FnBox<A,Output=R>+Send+'a> {
499 extern "rust-call" fn call_once(self, args: A) -> R {
504 impl<T: ?Sized+Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
506 #[stable(feature = "box_slice_clone", since = "1.3.0")]
507 impl<T: Clone> Clone for Box<[T]> {
508 fn clone(&self) -> Self {
509 let mut new = BoxBuilder {
510 data: RawVec::with_capacity(self.len()),
514 let mut target = new.data.ptr();
516 for item in self.iter() {
518 ptr::write(target, item.clone());
519 target = target.offset(1);
525 return unsafe { new.into_box() };
527 // Helper type for responding to panics correctly.
528 struct BoxBuilder<T> {
533 impl<T> BoxBuilder<T> {
534 unsafe fn into_box(self) -> Box<[T]> {
535 let raw = ptr::read(&self.data);
541 impl<T> Drop for BoxBuilder<T> {
543 let mut data = self.data.ptr();
544 let max = unsafe { data.offset(self.len as isize) };
549 data = data.offset(1);
557 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
558 fn borrow(&self) -> &T { &**self }
561 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
562 fn borrow_mut(&mut self) -> &mut T { &mut **self }