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")]
60 use core::cmp::Ordering;
62 use core::hash::{Hash, Hasher};
63 use core::iter::FusedIterator;
64 use core::marker::{Unpin, Unsize};
65 use core::mem::{self, PinMut};
66 use core::ops::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState};
67 use core::ptr::{self, NonNull, Unique};
68 use core::convert::From;
71 use str::from_boxed_utf8_unchecked;
73 /// A pointer type for heap allocation.
75 /// See the [module-level documentation](../../std/boxed/index.html) for more.
78 #[stable(feature = "rust1", since = "1.0.0")]
79 pub struct Box<T: ?Sized>(Unique<T>);
82 /// Allocates memory on the heap and then places `x` into it.
84 /// This doesn't actually allocate if `T` is zero-sized.
89 /// let five = Box::new(5);
91 #[stable(feature = "rust1", since = "1.0.0")]
93 pub fn new(x: T) -> Box<T> {
98 impl<T: ?Sized> Box<T> {
99 /// Constructs a box from a raw pointer.
101 /// After calling this function, the raw pointer is owned by the
102 /// resulting `Box`. Specifically, the `Box` destructor will call
103 /// the destructor of `T` and free the allocated memory. Since the
104 /// way `Box` allocates and releases memory is unspecified, the
105 /// only valid pointer to pass to this function is the one taken
106 /// from another `Box` via the [`Box::into_raw`] function.
108 /// This function is unsafe because improper use may lead to
109 /// memory problems. For example, a double-free may occur if the
110 /// function is called twice on the same raw pointer.
112 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
117 /// let x = Box::new(5);
118 /// let ptr = Box::into_raw(x);
119 /// let x = unsafe { Box::from_raw(ptr) };
121 #[stable(feature = "box_raw", since = "1.4.0")]
123 pub unsafe fn from_raw(raw: *mut T) -> Self {
124 Box(Unique::new_unchecked(raw))
127 /// Consumes the `Box`, returning the wrapped raw pointer.
129 /// After calling this function, the caller is responsible for the
130 /// memory previously managed by the `Box`. In particular, the
131 /// caller should properly destroy `T` and release the memory. The
132 /// proper way to do so is to convert the raw pointer back into a
133 /// `Box` with the [`Box::from_raw`] function.
135 /// Note: this is an associated function, which means that you have
136 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
137 /// is so that there is no conflict with a method on the inner type.
139 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
144 /// let x = Box::new(5);
145 /// let ptr = Box::into_raw(x);
147 #[stable(feature = "box_raw", since = "1.4.0")]
149 pub fn into_raw(b: Box<T>) -> *mut T {
150 Box::into_raw_non_null(b).as_ptr()
153 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
155 /// After calling this function, the caller is responsible for the
156 /// memory previously managed by the `Box`. In particular, the
157 /// caller should properly destroy `T` and release the memory. The
158 /// proper way to do so is to convert the `NonNull<T>` pointer
159 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
162 /// Note: this is an associated function, which means that you have
163 /// to call it as `Box::into_raw_non_null(b)`
164 /// instead of `b.into_raw_non_null()`. This
165 /// is so that there is no conflict with a method on the inner type.
167 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
172 /// #![feature(box_into_raw_non_null)]
175 /// let x = Box::new(5);
176 /// let ptr = Box::into_raw_non_null(x);
179 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
181 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
182 Box::into_unique(b).into()
185 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
188 pub fn into_unique(b: Box<T>) -> Unique<T> {
194 /// Consumes and leaks the `Box`, returning a mutable reference,
195 /// `&'a mut T`. Here, the lifetime `'a` may be chosen to be `'static`.
197 /// This function is mainly useful for data that lives for the remainder of
198 /// the program's life. Dropping the returned reference will cause a memory
199 /// leak. If this is not acceptable, the reference should first be wrapped
200 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
201 /// then be dropped which will properly destroy `T` and release the
202 /// allocated memory.
204 /// Note: this is an associated function, which means that you have
205 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
206 /// is so that there is no conflict with a method on the inner type.
208 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
216 /// let x = Box::new(41);
217 /// let static_ref: &'static mut usize = Box::leak(x);
218 /// *static_ref += 1;
219 /// assert_eq!(*static_ref, 42);
227 /// let x = vec![1, 2, 3].into_boxed_slice();
228 /// let static_ref = Box::leak(x);
229 /// static_ref[0] = 4;
230 /// assert_eq!(*static_ref, [4, 2, 3]);
233 #[stable(feature = "box_leak", since = "1.26.0")]
235 pub fn leak<'a>(b: Box<T>) -> &'a mut T
237 T: 'a // Technically not needed, but kept to be explicit.
239 unsafe { &mut *Box::into_raw(b) }
243 #[stable(feature = "rust1", since = "1.0.0")]
244 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
246 // FIXME: Do nothing, drop is currently performed by compiler.
250 #[stable(feature = "rust1", since = "1.0.0")]
251 impl<T: Default> Default for Box<T> {
252 /// Creates a `Box<T>`, with the `Default` value for T.
253 fn default() -> Box<T> {
254 box Default::default()
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T> Default for Box<[T]> {
260 fn default() -> Box<[T]> {
261 Box::<[T; 0]>::new([])
265 #[stable(feature = "default_box_extra", since = "1.17.0")]
266 impl Default for Box<str> {
267 fn default() -> Box<str> {
268 unsafe { from_boxed_utf8_unchecked(Default::default()) }
272 #[stable(feature = "rust1", since = "1.0.0")]
273 impl<T: Clone> Clone for Box<T> {
274 /// Returns a new box with a `clone()` of this box's contents.
279 /// let x = Box::new(5);
280 /// let y = x.clone();
284 fn clone(&self) -> Box<T> {
285 box { (**self).clone() }
287 /// Copies `source`'s contents into `self` without creating a new allocation.
292 /// let x = Box::new(5);
293 /// let mut y = Box::new(10);
295 /// y.clone_from(&x);
297 /// assert_eq!(*y, 5);
300 fn clone_from(&mut self, source: &Box<T>) {
301 (**self).clone_from(&(**source));
306 #[stable(feature = "box_slice_clone", since = "1.3.0")]
307 impl Clone for Box<str> {
308 fn clone(&self) -> Self {
309 let len = self.len();
310 let buf = RawVec::with_capacity(len);
312 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
313 from_boxed_utf8_unchecked(buf.into_box())
318 #[stable(feature = "rust1", since = "1.0.0")]
319 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
321 fn eq(&self, other: &Box<T>) -> bool {
322 PartialEq::eq(&**self, &**other)
325 fn ne(&self, other: &Box<T>) -> bool {
326 PartialEq::ne(&**self, &**other)
329 #[stable(feature = "rust1", since = "1.0.0")]
330 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
332 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
333 PartialOrd::partial_cmp(&**self, &**other)
336 fn lt(&self, other: &Box<T>) -> bool {
337 PartialOrd::lt(&**self, &**other)
340 fn le(&self, other: &Box<T>) -> bool {
341 PartialOrd::le(&**self, &**other)
344 fn ge(&self, other: &Box<T>) -> bool {
345 PartialOrd::ge(&**self, &**other)
348 fn gt(&self, other: &Box<T>) -> bool {
349 PartialOrd::gt(&**self, &**other)
352 #[stable(feature = "rust1", since = "1.0.0")]
353 impl<T: ?Sized + Ord> Ord for Box<T> {
355 fn cmp(&self, other: &Box<T>) -> Ordering {
356 Ord::cmp(&**self, &**other)
359 #[stable(feature = "rust1", since = "1.0.0")]
360 impl<T: ?Sized + Eq> Eq for Box<T> {}
362 #[stable(feature = "rust1", since = "1.0.0")]
363 impl<T: ?Sized + Hash> Hash for Box<T> {
364 fn hash<H: Hasher>(&self, state: &mut H) {
365 (**self).hash(state);
369 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
370 impl<T: ?Sized + Hasher> Hasher for Box<T> {
371 fn finish(&self) -> u64 {
374 fn write(&mut self, bytes: &[u8]) {
375 (**self).write(bytes)
377 fn write_u8(&mut self, i: u8) {
380 fn write_u16(&mut self, i: u16) {
381 (**self).write_u16(i)
383 fn write_u32(&mut self, i: u32) {
384 (**self).write_u32(i)
386 fn write_u64(&mut self, i: u64) {
387 (**self).write_u64(i)
389 fn write_u128(&mut self, i: u128) {
390 (**self).write_u128(i)
392 fn write_usize(&mut self, i: usize) {
393 (**self).write_usize(i)
395 fn write_i8(&mut self, i: i8) {
398 fn write_i16(&mut self, i: i16) {
399 (**self).write_i16(i)
401 fn write_i32(&mut self, i: i32) {
402 (**self).write_i32(i)
404 fn write_i64(&mut self, i: i64) {
405 (**self).write_i64(i)
407 fn write_i128(&mut self, i: i128) {
408 (**self).write_i128(i)
410 fn write_isize(&mut self, i: isize) {
411 (**self).write_isize(i)
415 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
416 impl<T> From<T> for Box<T> {
417 fn from(t: T) -> Self {
422 #[stable(feature = "box_from_slice", since = "1.17.0")]
423 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
424 fn from(slice: &'a [T]) -> Box<[T]> {
425 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
426 boxed.copy_from_slice(slice);
431 #[stable(feature = "box_from_slice", since = "1.17.0")]
432 impl<'a> From<&'a str> for Box<str> {
434 fn from(s: &'a str) -> Box<str> {
435 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
439 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
440 impl From<Box<str>> for Box<[u8]> {
442 fn from(s: Box<str>) -> Self {
443 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
449 #[stable(feature = "rust1", since = "1.0.0")]
450 /// Attempt to downcast the box to a concrete type.
455 /// use std::any::Any;
457 /// fn print_if_string(value: Box<Any>) {
458 /// if let Ok(string) = value.downcast::<String>() {
459 /// println!("String ({}): {}", string.len(), string);
464 /// let my_string = "Hello World".to_string();
465 /// print_if_string(Box::new(my_string));
466 /// print_if_string(Box::new(0i8));
469 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
472 let raw: *mut Any = Box::into_raw(self);
473 Ok(Box::from_raw(raw as *mut T))
481 impl Box<Any + Send> {
483 #[stable(feature = "rust1", since = "1.0.0")]
484 /// Attempt to downcast the box to a concrete type.
489 /// use std::any::Any;
491 /// fn print_if_string(value: Box<Any + Send>) {
492 /// if let Ok(string) = value.downcast::<String>() {
493 /// println!("String ({}): {}", string.len(), string);
498 /// let my_string = "Hello World".to_string();
499 /// print_if_string(Box::new(my_string));
500 /// print_if_string(Box::new(0i8));
503 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
504 <Box<Any>>::downcast(self).map_err(|s| unsafe {
505 // reapply the Send marker
506 Box::from_raw(Box::into_raw(s) as *mut (Any + Send))
511 #[stable(feature = "rust1", since = "1.0.0")]
512 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
513 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
514 fmt::Display::fmt(&**self, f)
518 #[stable(feature = "rust1", since = "1.0.0")]
519 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
520 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
521 fmt::Debug::fmt(&**self, f)
525 #[stable(feature = "rust1", since = "1.0.0")]
526 impl<T: ?Sized> fmt::Pointer for Box<T> {
527 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
528 // It's not possible to extract the inner Uniq directly from the Box,
529 // instead we cast it to a *const which aliases the Unique
530 let ptr: *const T = &**self;
531 fmt::Pointer::fmt(&ptr, f)
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl<T: ?Sized> Deref for Box<T> {
539 fn deref(&self) -> &T {
544 #[stable(feature = "rust1", since = "1.0.0")]
545 impl<T: ?Sized> DerefMut for Box<T> {
546 fn deref_mut(&mut self) -> &mut T {
551 #[stable(feature = "rust1", since = "1.0.0")]
552 impl<I: Iterator + ?Sized> Iterator for Box<I> {
554 fn next(&mut self) -> Option<I::Item> {
557 fn size_hint(&self) -> (usize, Option<usize>) {
560 fn nth(&mut self, n: usize) -> Option<I::Item> {
564 #[stable(feature = "rust1", since = "1.0.0")]
565 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
566 fn next_back(&mut self) -> Option<I::Item> {
570 #[stable(feature = "rust1", since = "1.0.0")]
571 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
572 fn len(&self) -> usize {
575 fn is_empty(&self) -> bool {
580 #[stable(feature = "fused", since = "1.26.0")]
581 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
584 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
585 /// closure objects. The idea is that where one would normally store a
586 /// `Box<FnOnce()>` in a data structure, you should use
587 /// `Box<FnBox()>`. The two traits behave essentially the same, except
588 /// that a `FnBox` closure can only be called if it is boxed. (Note
589 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
590 /// closures become directly usable.)
594 /// Here is a snippet of code which creates a hashmap full of boxed
595 /// once closures and then removes them one by one, calling each
596 /// closure as it is removed. Note that the type of the closures
597 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
601 /// #![feature(fnbox)]
603 /// use std::boxed::FnBox;
604 /// use std::collections::HashMap;
606 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
607 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
608 /// map.insert(1, Box::new(|| 22));
609 /// map.insert(2, Box::new(|| 44));
614 /// let mut map = make_map();
615 /// for i in &[1, 2] {
616 /// let f = map.remove(&i).unwrap();
617 /// assert_eq!(f(), i * 22);
622 #[unstable(feature = "fnbox",
623 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
627 fn call_box(self: Box<Self>, args: A) -> Self::Output;
630 #[unstable(feature = "fnbox",
631 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
632 impl<A, F> FnBox<A> for F
635 type Output = F::Output;
637 fn call_box(self: Box<F>, args: A) -> F::Output {
642 #[unstable(feature = "fnbox",
643 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
644 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + 'a> {
647 extern "rust-call" fn call_once(self, args: A) -> R {
652 #[unstable(feature = "fnbox",
653 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
654 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + Send + 'a> {
657 extern "rust-call" fn call_once(self, args: A) -> R {
662 #[unstable(feature = "coerce_unsized", issue = "27732")]
663 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
665 #[stable(feature = "box_slice_clone", since = "1.3.0")]
666 impl<T: Clone> Clone for Box<[T]> {
667 fn clone(&self) -> Self {
668 let mut new = BoxBuilder {
669 data: RawVec::with_capacity(self.len()),
673 let mut target = new.data.ptr();
675 for item in self.iter() {
677 ptr::write(target, item.clone());
678 target = target.offset(1);
684 return unsafe { new.into_box() };
686 // Helper type for responding to panics correctly.
687 struct BoxBuilder<T> {
692 impl<T> BoxBuilder<T> {
693 unsafe fn into_box(self) -> Box<[T]> {
694 let raw = ptr::read(&self.data);
700 impl<T> Drop for BoxBuilder<T> {
702 let mut data = self.data.ptr();
703 let max = unsafe { data.offset(self.len as isize) };
708 data = data.offset(1);
716 #[stable(feature = "box_borrow", since = "1.1.0")]
717 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
718 fn borrow(&self) -> &T {
723 #[stable(feature = "box_borrow", since = "1.1.0")]
724 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
725 fn borrow_mut(&mut self) -> &mut T {
730 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
731 impl<T: ?Sized> AsRef<T> for Box<T> {
732 fn as_ref(&self) -> &T {
737 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
738 impl<T: ?Sized> AsMut<T> for Box<T> {
739 fn as_mut(&mut self) -> &mut T {
744 #[unstable(feature = "generator_trait", issue = "43122")]
745 impl<T> Generator for Box<T>
746 where T: Generator + ?Sized
748 type Yield = T::Yield;
749 type Return = T::Return;
750 unsafe fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> {
755 /// A pinned, heap allocated reference.
756 #[unstable(feature = "pin", issue = "49150")]
758 pub struct PinBox<T: ?Sized> {
762 #[unstable(feature = "pin", issue = "49150")]
764 /// Allocate memory on the heap, move the data into it and pin it.
765 #[unstable(feature = "pin", issue = "49150")]
766 pub fn new(data: T) -> PinBox<T> {
767 PinBox { inner: Box::new(data) }
771 #[unstable(feature = "pin", issue = "49150")]
772 impl<T: ?Sized> PinBox<T> {
773 /// Get a pinned reference to the data in this PinBox.
774 pub fn as_pin_mut<'a>(&'a mut self) -> PinMut<'a, T> {
775 unsafe { PinMut::new_unchecked(&mut *self.inner) }
778 /// Get a mutable reference to the data inside this PinBox.
780 /// This function is unsafe. Users must guarantee that the data is never
781 /// moved out of this reference.
782 pub unsafe fn get_mut<'a>(this: &'a mut PinBox<T>) -> &'a mut T {
786 /// Convert this PinBox into an unpinned Box.
788 /// This function is unsafe. Users must guarantee that the data is never
789 /// moved out of the box.
790 pub unsafe fn unpin(this: PinBox<T>) -> Box<T> {
795 #[unstable(feature = "pin", issue = "49150")]
796 impl<T: ?Sized> From<Box<T>> for PinBox<T> {
797 fn from(boxed: Box<T>) -> PinBox<T> {
798 PinBox { inner: boxed }
802 #[unstable(feature = "pin", issue = "49150")]
803 impl<T: Unpin + ?Sized> From<PinBox<T>> for Box<T> {
804 fn from(pinned: PinBox<T>) -> Box<T> {
809 #[unstable(feature = "pin", issue = "49150")]
810 impl<T: ?Sized> Deref for PinBox<T> {
813 fn deref(&self) -> &T {
818 #[unstable(feature = "pin", issue = "49150")]
819 impl<T: Unpin + ?Sized> DerefMut for PinBox<T> {
820 fn deref_mut(&mut self) -> &mut T {
825 #[unstable(feature = "pin", issue = "49150")]
826 impl<T: fmt::Display + ?Sized> fmt::Display for PinBox<T> {
827 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
828 fmt::Display::fmt(&*self.inner, f)
832 #[unstable(feature = "pin", issue = "49150")]
833 impl<T: fmt::Debug + ?Sized> fmt::Debug for PinBox<T> {
834 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
835 fmt::Debug::fmt(&*self.inner, f)
839 #[unstable(feature = "pin", issue = "49150")]
840 impl<T: ?Sized> fmt::Pointer for PinBox<T> {
841 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
842 // It's not possible to extract the inner Uniq directly from the Box,
843 // instead we cast it to a *const which aliases the Unique
844 let ptr: *const T = &*self.inner;
845 fmt::Pointer::fmt(&ptr, f)
849 #[unstable(feature = "pin", issue = "49150")]
850 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinBox<U>> for PinBox<T> {}
852 #[unstable(feature = "pin", issue = "49150")]
853 unsafe impl<T: ?Sized> Unpin for PinBox<T> {}