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`
45 //! ```compile_fail,E0072
51 //! It wouldn't work. This is because the size of a `List` depends on how many
52 //! elements are in the list, and so we don't know how much memory to allocate
53 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
54 //! big `Cons` needs to be.
56 #![stable(feature = "rust1", since = "1.0.0")]
63 use core::cmp::Ordering;
65 use core::hash::{self, Hash};
66 use core::iter::FusedIterator;
67 use core::marker::{self, Unsize};
69 use core::ops::{CoerceUnsized, Deref, DerefMut};
70 use core::ops::{BoxPlace, Boxed, InPlace, Place, Placer};
71 use core::ptr::{self, Unique};
72 use core::convert::From;
73 use str::from_boxed_utf8_unchecked;
75 /// A value that represents the heap. This is the default place that the `box`
76 /// keyword allocates into when no place is supplied.
78 /// The following two examples are equivalent:
81 /// #![feature(box_heap)]
83 /// #![feature(box_syntax, placement_in_syntax)]
84 /// use std::boxed::HEAP;
87 /// let foo: Box<i32> = in HEAP { 5 };
91 #[unstable(feature = "box_heap",
92 reason = "may be renamed; uncertain about custom allocator design",
94 pub const HEAP: ExchangeHeapSingleton = ExchangeHeapSingleton { _force_singleton: () };
96 /// This the singleton type used solely for `boxed::HEAP`.
97 #[unstable(feature = "box_heap",
98 reason = "may be renamed; uncertain about custom allocator design",
100 #[allow(missing_debug_implementations)]
101 #[derive(Copy, Clone)]
102 pub struct ExchangeHeapSingleton {
103 _force_singleton: (),
106 /// A pointer type for heap allocation.
108 /// See the [module-level documentation](../../std/boxed/index.html) for more.
109 #[lang = "owned_box"]
111 #[stable(feature = "rust1", since = "1.0.0")]
112 pub struct Box<T: ?Sized>(Unique<T>);
114 /// `IntermediateBox` represents uninitialized backing storage for `Box`.
116 /// FIXME (pnkfelix): Ideally we would just reuse `Box<T>` instead of
117 /// introducing a separate `IntermediateBox<T>`; but then you hit
118 /// issues when you e.g. attempt to destructure an instance of `Box`,
119 /// since it is a lang item and so it gets special handling by the
120 /// compiler. Easier just to make this parallel type for now.
122 /// FIXME (pnkfelix): Currently the `box` protocol only supports
123 /// creating instances of sized types. This IntermediateBox is
124 /// designed to be forward-compatible with a future protocol that
125 /// supports creating instances of unsized types; that is why the type
126 /// parameter has the `?Sized` generalization marker, and is also why
127 /// this carries an explicit size. However, it probably does not need
128 /// to carry the explicit alignment; that is just a work-around for
129 /// the fact that the `align_of` intrinsic currently requires the
130 /// input type to be Sized (which I do not think is strictly
132 #[unstable(feature = "placement_in",
133 reason = "placement box design is still being worked out.",
135 #[allow(missing_debug_implementations)]
136 pub struct IntermediateBox<T: ?Sized> {
140 marker: marker::PhantomData<*mut T>,
143 #[unstable(feature = "placement_in",
144 reason = "placement box design is still being worked out.",
146 impl<T> Place<T> for IntermediateBox<T> {
147 fn pointer(&mut self) -> *mut T {
152 unsafe fn finalize<T>(b: IntermediateBox<T>) -> Box<T> {
153 let p = b.ptr as *mut T;
158 fn make_place<T>() -> IntermediateBox<T> {
159 let size = mem::size_of::<T>();
160 let align = mem::align_of::<T>();
162 let p = if size == 0 {
163 mem::align_of::<T>() as *mut u8
165 let p = unsafe { heap::allocate(size, align) };
167 panic!("Box make_place allocation failure.");
176 marker: marker::PhantomData,
180 #[unstable(feature = "placement_in",
181 reason = "placement box design is still being worked out.",
183 impl<T> BoxPlace<T> for IntermediateBox<T> {
184 fn make_place() -> IntermediateBox<T> {
189 #[unstable(feature = "placement_in",
190 reason = "placement box design is still being worked out.",
192 impl<T> InPlace<T> for IntermediateBox<T> {
194 unsafe fn finalize(self) -> Box<T> {
199 #[unstable(feature = "placement_new_protocol", issue = "27779")]
200 impl<T> Boxed for Box<T> {
202 type Place = IntermediateBox<T>;
203 unsafe fn finalize(b: IntermediateBox<T>) -> Box<T> {
208 #[unstable(feature = "placement_in",
209 reason = "placement box design is still being worked out.",
211 impl<T> Placer<T> for ExchangeHeapSingleton {
212 type Place = IntermediateBox<T>;
214 fn make_place(self) -> IntermediateBox<T> {
219 #[unstable(feature = "placement_in",
220 reason = "placement box design is still being worked out.",
222 impl<T: ?Sized> Drop for IntermediateBox<T> {
225 unsafe { heap::deallocate(self.ptr, self.size, self.align) }
231 /// Allocates memory on the heap and then places `x` into it.
233 /// This doesn't actually allocate if `T` is zero-sized.
238 /// let five = Box::new(5);
240 #[stable(feature = "rust1", since = "1.0.0")]
242 pub fn new(x: T) -> Box<T> {
247 impl<T: ?Sized> Box<T> {
248 /// Constructs a box from a raw pointer.
250 /// After calling this function, the raw pointer is owned by the
251 /// resulting `Box`. Specifically, the `Box` destructor will call
252 /// the destructor of `T` and free the allocated memory. Since the
253 /// way `Box` allocates and releases memory is unspecified, the
254 /// only valid pointer to pass to this function is the one taken
255 /// from another `Box` via the [`Box::into_raw`] function.
257 /// This function is unsafe because improper use may lead to
258 /// memory problems. For example, a double-free may occur if the
259 /// function is called twice on the same raw pointer.
261 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
266 /// let x = Box::new(5);
267 /// let ptr = Box::into_raw(x);
268 /// let x = unsafe { Box::from_raw(ptr) };
270 #[stable(feature = "box_raw", since = "1.4.0")]
272 pub unsafe fn from_raw(raw: *mut T) -> Self {
276 /// Consumes the `Box`, returning the wrapped raw pointer.
278 /// After calling this function, the caller is responsible for the
279 /// memory previously managed by the `Box`. In particular, the
280 /// caller should properly destroy `T` and release the memory. The
281 /// proper way to do so is to convert the raw pointer back into a
282 /// `Box` with the [`Box::from_raw`] function.
284 /// Note: this is an associated function, which means that you have
285 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
286 /// is so that there is no conflict with a method on the inner type.
288 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
293 /// let x = Box::new(5);
294 /// let ptr = Box::into_raw(x);
296 #[stable(feature = "box_raw", since = "1.4.0")]
298 pub fn into_raw(b: Box<T>) -> *mut T {
299 unsafe { mem::transmute(b) }
303 #[stable(feature = "rust1", since = "1.0.0")]
304 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
306 // FIXME: Do nothing, drop is currently performed by compiler.
310 #[stable(feature = "rust1", since = "1.0.0")]
311 impl<T: Default> Default for Box<T> {
312 /// Creates a `Box<T>`, with the `Default` value for T.
313 fn default() -> Box<T> {
314 box Default::default()
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl<T> Default for Box<[T]> {
320 fn default() -> Box<[T]> {
321 Box::<[T; 0]>::new([])
325 #[stable(feature = "default_box_extra", since = "1.17.0")]
326 impl Default for Box<str> {
327 fn default() -> Box<str> {
328 unsafe { from_boxed_utf8_unchecked(Default::default()) }
332 #[stable(feature = "rust1", since = "1.0.0")]
333 impl<T: Clone> Clone for Box<T> {
334 /// Returns a new box with a `clone()` of this box's contents.
339 /// let x = Box::new(5);
340 /// let y = x.clone();
344 fn clone(&self) -> Box<T> {
345 box { (**self).clone() }
347 /// Copies `source`'s contents into `self` without creating a new allocation.
352 /// let x = Box::new(5);
353 /// let mut y = Box::new(10);
355 /// y.clone_from(&x);
357 /// assert_eq!(*y, 5);
360 fn clone_from(&mut self, source: &Box<T>) {
361 (**self).clone_from(&(**source));
366 #[stable(feature = "box_slice_clone", since = "1.3.0")]
367 impl Clone for Box<str> {
368 fn clone(&self) -> Self {
369 let len = self.len();
370 let buf = RawVec::with_capacity(len);
372 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
373 from_boxed_utf8_unchecked(buf.into_box())
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
381 fn eq(&self, other: &Box<T>) -> bool {
382 PartialEq::eq(&**self, &**other)
385 fn ne(&self, other: &Box<T>) -> bool {
386 PartialEq::ne(&**self, &**other)
389 #[stable(feature = "rust1", since = "1.0.0")]
390 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
392 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
393 PartialOrd::partial_cmp(&**self, &**other)
396 fn lt(&self, other: &Box<T>) -> bool {
397 PartialOrd::lt(&**self, &**other)
400 fn le(&self, other: &Box<T>) -> bool {
401 PartialOrd::le(&**self, &**other)
404 fn ge(&self, other: &Box<T>) -> bool {
405 PartialOrd::ge(&**self, &**other)
408 fn gt(&self, other: &Box<T>) -> bool {
409 PartialOrd::gt(&**self, &**other)
412 #[stable(feature = "rust1", since = "1.0.0")]
413 impl<T: ?Sized + Ord> Ord for Box<T> {
415 fn cmp(&self, other: &Box<T>) -> Ordering {
416 Ord::cmp(&**self, &**other)
419 #[stable(feature = "rust1", since = "1.0.0")]
420 impl<T: ?Sized + Eq> Eq for Box<T> {}
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<T: ?Sized + Hash> Hash for Box<T> {
424 fn hash<H: hash::Hasher>(&self, state: &mut H) {
425 (**self).hash(state);
429 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
430 impl<T> From<T> for Box<T> {
431 fn from(t: T) -> Self {
436 #[stable(feature = "box_from_slice", since = "1.17.0")]
437 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
438 fn from(slice: &'a [T]) -> Box<[T]> {
439 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
440 boxed.copy_from_slice(slice);
445 #[stable(feature = "box_from_slice", since = "1.17.0")]
446 impl<'a> From<&'a str> for Box<str> {
447 fn from(s: &'a str) -> Box<str> {
448 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
452 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
453 impl From<Box<str>> for Box<[u8]> {
454 fn from(s: Box<str>) -> Self {
463 #[stable(feature = "rust1", since = "1.0.0")]
464 /// Attempt to downcast the box to a concrete type.
469 /// use std::any::Any;
471 /// fn print_if_string(value: Box<Any>) {
472 /// if let Ok(string) = value.downcast::<String>() {
473 /// println!("String ({}): {}", string.len(), string);
478 /// let my_string = "Hello World".to_string();
479 /// print_if_string(Box::new(my_string));
480 /// print_if_string(Box::new(0i8));
483 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
486 let raw: *mut Any = Box::into_raw(self);
487 Ok(Box::from_raw(raw as *mut T))
495 impl Box<Any + Send> {
497 #[stable(feature = "rust1", since = "1.0.0")]
498 /// Attempt to downcast the box to a concrete type.
503 /// use std::any::Any;
505 /// fn print_if_string(value: Box<Any + Send>) {
506 /// if let Ok(string) = value.downcast::<String>() {
507 /// println!("String ({}): {}", string.len(), string);
512 /// let my_string = "Hello World".to_string();
513 /// print_if_string(Box::new(my_string));
514 /// print_if_string(Box::new(0i8));
517 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
518 <Box<Any>>::downcast(self).map_err(|s| unsafe {
519 // reapply the Send marker
520 mem::transmute::<Box<Any>, Box<Any + Send>>(s)
525 #[stable(feature = "rust1", since = "1.0.0")]
526 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
527 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528 fmt::Display::fmt(&**self, f)
532 #[stable(feature = "rust1", since = "1.0.0")]
533 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
534 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
535 fmt::Debug::fmt(&**self, f)
539 #[stable(feature = "rust1", since = "1.0.0")]
540 impl<T: ?Sized> fmt::Pointer for Box<T> {
541 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
542 // It's not possible to extract the inner Uniq directly from the Box,
543 // instead we cast it to a *const which aliases the Unique
544 let ptr: *const T = &**self;
545 fmt::Pointer::fmt(&ptr, f)
549 #[stable(feature = "rust1", since = "1.0.0")]
550 impl<T: ?Sized> Deref for Box<T> {
553 fn deref(&self) -> &T {
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<T: ?Sized> DerefMut for Box<T> {
560 fn deref_mut(&mut self) -> &mut T {
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<I: Iterator + ?Sized> Iterator for Box<I> {
568 fn next(&mut self) -> Option<I::Item> {
571 fn size_hint(&self) -> (usize, Option<usize>) {
574 fn nth(&mut self, n: usize) -> Option<I::Item> {
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
580 fn next_back(&mut self) -> Option<I::Item> {
584 #[stable(feature = "rust1", since = "1.0.0")]
585 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
586 fn len(&self) -> usize {
589 fn is_empty(&self) -> bool {
594 #[unstable(feature = "fused", issue = "35602")]
595 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
598 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
599 /// closure objects. The idea is that where one would normally store a
600 /// `Box<FnOnce()>` in a data structure, you should use
601 /// `Box<FnBox()>`. The two traits behave essentially the same, except
602 /// that a `FnBox` closure can only be called if it is boxed. (Note
603 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
604 /// closures become directly usable.)
608 /// Here is a snippet of code which creates a hashmap full of boxed
609 /// once closures and then removes them one by one, calling each
610 /// closure as it is removed. Note that the type of the closures
611 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
615 /// #![feature(fnbox)]
617 /// use std::boxed::FnBox;
618 /// use std::collections::HashMap;
620 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
621 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
622 /// map.insert(1, Box::new(|| 22));
623 /// map.insert(2, Box::new(|| 44));
628 /// let mut map = make_map();
629 /// for i in &[1, 2] {
630 /// let f = map.remove(&i).unwrap();
631 /// assert_eq!(f(), i * 22);
636 #[unstable(feature = "fnbox",
637 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
641 fn call_box(self: Box<Self>, args: A) -> Self::Output;
644 #[unstable(feature = "fnbox",
645 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
646 impl<A, F> FnBox<A> for F
649 type Output = F::Output;
651 fn call_box(self: Box<F>, args: A) -> F::Output {
656 #[unstable(feature = "fnbox",
657 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
658 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + 'a> {
661 extern "rust-call" fn call_once(self, args: A) -> R {
666 #[unstable(feature = "fnbox",
667 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
668 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + Send + 'a> {
671 extern "rust-call" fn call_once(self, args: A) -> R {
676 #[unstable(feature = "coerce_unsized", issue = "27732")]
677 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
679 #[stable(feature = "box_slice_clone", since = "1.3.0")]
680 impl<T: Clone> Clone for Box<[T]> {
681 fn clone(&self) -> Self {
682 let mut new = BoxBuilder {
683 data: RawVec::with_capacity(self.len()),
687 let mut target = new.data.ptr();
689 for item in self.iter() {
691 ptr::write(target, item.clone());
692 target = target.offset(1);
698 return unsafe { new.into_box() };
700 // Helper type for responding to panics correctly.
701 struct BoxBuilder<T> {
706 impl<T> BoxBuilder<T> {
707 unsafe fn into_box(self) -> Box<[T]> {
708 let raw = ptr::read(&self.data);
714 impl<T> Drop for BoxBuilder<T> {
716 let mut data = self.data.ptr();
717 let max = unsafe { data.offset(self.len as isize) };
722 data = data.offset(1);
730 #[stable(feature = "rust1", since = "1.0.0")]
731 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
732 fn borrow(&self) -> &T {
737 #[stable(feature = "rust1", since = "1.0.0")]
738 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
739 fn borrow_mut(&mut self) -> &mut T {
744 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
745 impl<T: ?Sized> AsRef<T> for Box<T> {
746 fn as_ref(&self) -> &T {
751 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
752 impl<T: ?Sized> AsMut<T> for Box<T> {
753 fn as_mut(&mut self) -> &mut T {