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.
19 //! Move a value from the stack to the heap by creating a [`Box`]:
23 //! let boxed: Box<u8> = Box::new(val);
26 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
29 //! let boxed: Box<u8> = Box::new(5);
30 //! let val: u8 = *boxed;
33 //! Creating a recursive data structure:
38 //! Cons(T, Box<List<T>>),
43 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
44 //! println!("{:?}", list);
48 //! This will print `Cons(1, Cons(2, Nil))`.
50 //! Recursive structures must be boxed, because if the definition of `Cons`
53 //! ```compile_fail,E0072
59 //! It wouldn't work. This is because the size of a `List` depends on how many
60 //! elements are in the list, and so we don't know how much memory to allocate
61 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
62 //! big `Cons` needs to be.
64 //! [dereferencing]: ../../std/ops/trait.Deref.html
65 //! [`Box`]: struct.Box.html
67 #![stable(feature = "rust1", since = "1.0.0")]
71 use core::cmp::Ordering;
72 use core::convert::From;
74 use core::future::Future;
75 use core::hash::{Hash, Hasher};
76 use core::iter::{Iterator, FromIterator, FusedIterator};
77 use core::marker::{Unpin, Unsize};
81 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
83 use core::ptr::{self, NonNull, Unique};
84 use core::task::{LocalWaker, Poll};
88 use str::from_boxed_utf8_unchecked;
90 /// A pointer type for heap allocation.
92 /// See the [module-level documentation](../../std/boxed/index.html) for more.
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Box<T: ?Sized>(Unique<T>);
99 /// Allocates memory on the heap and then places `x` into it.
101 /// This doesn't actually allocate if `T` is zero-sized.
106 /// let five = Box::new(5);
108 #[stable(feature = "rust1", since = "1.0.0")]
110 pub fn new(x: T) -> Box<T> {
114 #[unstable(feature = "pin", issue = "49150")]
116 pub fn pinned(x: T) -> Pin<Box<T>> {
121 impl<T: ?Sized> Box<T> {
122 /// Constructs a box from a raw pointer.
124 /// After calling this function, the raw pointer is owned by the
125 /// resulting `Box`. Specifically, the `Box` destructor will call
126 /// the destructor of `T` and free the allocated memory. Since the
127 /// way `Box` allocates and releases memory is unspecified, the
128 /// only valid pointer to pass to this function is the one taken
129 /// from another `Box` via the [`Box::into_raw`] function.
131 /// This function is unsafe because improper use may lead to
132 /// memory problems. For example, a double-free may occur if the
133 /// function is called twice on the same raw pointer.
135 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
140 /// let x = Box::new(5);
141 /// let ptr = Box::into_raw(x);
142 /// let x = unsafe { Box::from_raw(ptr) };
144 #[stable(feature = "box_raw", since = "1.4.0")]
146 pub unsafe fn from_raw(raw: *mut T) -> Self {
147 Box(Unique::new_unchecked(raw))
150 /// Consumes the `Box`, returning a wrapped raw pointer.
152 /// The pointer will be properly aligned and non-null.
154 /// After calling this function, the caller is responsible for the
155 /// memory previously managed by the `Box`. In particular, the
156 /// caller should properly destroy `T` and release the memory. The
157 /// proper way to do so is to convert the raw pointer back into a
158 /// `Box` with the [`Box::from_raw`] function.
160 /// Note: this is an associated function, which means that you have
161 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
162 /// is so that there is no conflict with a method on the inner type.
164 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
169 /// let x = Box::new(5);
170 /// let ptr = Box::into_raw(x);
172 #[stable(feature = "box_raw", since = "1.4.0")]
174 pub fn into_raw(b: Box<T>) -> *mut T {
175 Box::into_raw_non_null(b).as_ptr()
178 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
180 /// After calling this function, the caller is responsible for the
181 /// memory previously managed by the `Box`. In particular, the
182 /// caller should properly destroy `T` and release the memory. The
183 /// proper way to do so is to convert the `NonNull<T>` pointer
184 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
187 /// Note: this is an associated function, which means that you have
188 /// to call it as `Box::into_raw_non_null(b)`
189 /// instead of `b.into_raw_non_null()`. This
190 /// is so that there is no conflict with a method on the inner type.
192 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
197 /// #![feature(box_into_raw_non_null)]
200 /// let x = Box::new(5);
201 /// let ptr = Box::into_raw_non_null(x);
204 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
206 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
207 Box::into_unique(b).into()
210 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
213 pub fn into_unique(b: Box<T>) -> Unique<T> {
219 /// Consumes and leaks the `Box`, returning a mutable reference,
220 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
221 /// `'a`. If the type has only static references, or none at all, then this
222 /// may be chosen to be `'static`.
224 /// This function is mainly useful for data that lives for the remainder of
225 /// the program's life. Dropping the returned reference will cause a memory
226 /// leak. If this is not acceptable, the reference should first be wrapped
227 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
228 /// then be dropped which will properly destroy `T` and release the
229 /// allocated memory.
231 /// Note: this is an associated function, which means that you have
232 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
233 /// is so that there is no conflict with a method on the inner type.
235 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
243 /// let x = Box::new(41);
244 /// let static_ref: &'static mut usize = Box::leak(x);
245 /// *static_ref += 1;
246 /// assert_eq!(*static_ref, 42);
254 /// let x = vec![1, 2, 3].into_boxed_slice();
255 /// let static_ref = Box::leak(x);
256 /// static_ref[0] = 4;
257 /// assert_eq!(*static_ref, [4, 2, 3]);
260 #[stable(feature = "box_leak", since = "1.26.0")]
262 pub fn leak<'a>(b: Box<T>) -> &'a mut T
264 T: 'a // Technically not needed, but kept to be explicit.
266 unsafe { &mut *Box::into_raw(b) }
270 #[stable(feature = "rust1", since = "1.0.0")]
271 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
273 // FIXME: Do nothing, drop is currently performed by compiler.
277 #[stable(feature = "rust1", since = "1.0.0")]
278 impl<T: Default> Default for Box<T> {
279 /// Creates a `Box<T>`, with the `Default` value for T.
280 fn default() -> Box<T> {
281 box Default::default()
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T> Default for Box<[T]> {
287 fn default() -> Box<[T]> {
288 Box::<[T; 0]>::new([])
292 #[stable(feature = "default_box_extra", since = "1.17.0")]
293 impl Default for Box<str> {
294 fn default() -> Box<str> {
295 unsafe { from_boxed_utf8_unchecked(Default::default()) }
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<T: Clone> Clone for Box<T> {
301 /// Returns a new box with a `clone()` of this box's contents.
306 /// let x = Box::new(5);
307 /// let y = x.clone();
311 fn clone(&self) -> Box<T> {
312 box { (**self).clone() }
314 /// Copies `source`'s contents into `self` without creating a new allocation.
319 /// let x = Box::new(5);
320 /// let mut y = Box::new(10);
322 /// y.clone_from(&x);
324 /// assert_eq!(*y, 5);
327 fn clone_from(&mut self, source: &Box<T>) {
328 (**self).clone_from(&(**source));
333 #[stable(feature = "box_slice_clone", since = "1.3.0")]
334 impl Clone for Box<str> {
335 fn clone(&self) -> Self {
336 let len = self.len();
337 let buf = RawVec::with_capacity(len);
339 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
340 from_boxed_utf8_unchecked(buf.into_box())
345 #[stable(feature = "rust1", since = "1.0.0")]
346 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
348 fn eq(&self, other: &Box<T>) -> bool {
349 PartialEq::eq(&**self, &**other)
352 fn ne(&self, other: &Box<T>) -> bool {
353 PartialEq::ne(&**self, &**other)
356 #[stable(feature = "rust1", since = "1.0.0")]
357 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
359 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
360 PartialOrd::partial_cmp(&**self, &**other)
363 fn lt(&self, other: &Box<T>) -> bool {
364 PartialOrd::lt(&**self, &**other)
367 fn le(&self, other: &Box<T>) -> bool {
368 PartialOrd::le(&**self, &**other)
371 fn ge(&self, other: &Box<T>) -> bool {
372 PartialOrd::ge(&**self, &**other)
375 fn gt(&self, other: &Box<T>) -> bool {
376 PartialOrd::gt(&**self, &**other)
379 #[stable(feature = "rust1", since = "1.0.0")]
380 impl<T: ?Sized + Ord> Ord for Box<T> {
382 fn cmp(&self, other: &Box<T>) -> Ordering {
383 Ord::cmp(&**self, &**other)
386 #[stable(feature = "rust1", since = "1.0.0")]
387 impl<T: ?Sized + Eq> Eq for Box<T> {}
389 #[stable(feature = "rust1", since = "1.0.0")]
390 impl<T: ?Sized + Hash> Hash for Box<T> {
391 fn hash<H: Hasher>(&self, state: &mut H) {
392 (**self).hash(state);
396 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
397 impl<T: ?Sized + Hasher> Hasher for Box<T> {
398 fn finish(&self) -> u64 {
401 fn write(&mut self, bytes: &[u8]) {
402 (**self).write(bytes)
404 fn write_u8(&mut self, i: u8) {
407 fn write_u16(&mut self, i: u16) {
408 (**self).write_u16(i)
410 fn write_u32(&mut self, i: u32) {
411 (**self).write_u32(i)
413 fn write_u64(&mut self, i: u64) {
414 (**self).write_u64(i)
416 fn write_u128(&mut self, i: u128) {
417 (**self).write_u128(i)
419 fn write_usize(&mut self, i: usize) {
420 (**self).write_usize(i)
422 fn write_i8(&mut self, i: i8) {
425 fn write_i16(&mut self, i: i16) {
426 (**self).write_i16(i)
428 fn write_i32(&mut self, i: i32) {
429 (**self).write_i32(i)
431 fn write_i64(&mut self, i: i64) {
432 (**self).write_i64(i)
434 fn write_i128(&mut self, i: i128) {
435 (**self).write_i128(i)
437 fn write_isize(&mut self, i: isize) {
438 (**self).write_isize(i)
442 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
443 impl<T> From<T> for Box<T> {
444 fn from(t: T) -> Self {
449 #[unstable(feature = "pin", issue = "49150")]
450 impl<T> From<Box<T>> for Pin<Box<T>> {
451 fn from(boxed: Box<T>) -> Self {
452 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
453 // when `T: !Unpin`, so it's safe to pin it directly without any
454 // additional requirements.
455 unsafe { Pin::new_unchecked(boxed) }
459 #[stable(feature = "box_from_slice", since = "1.17.0")]
460 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
461 fn from(slice: &'a [T]) -> Box<[T]> {
462 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
463 boxed.copy_from_slice(slice);
468 #[stable(feature = "box_from_slice", since = "1.17.0")]
469 impl<'a> From<&'a str> for Box<str> {
471 fn from(s: &'a str) -> Box<str> {
472 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
476 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
477 impl From<Box<str>> for Box<[u8]> {
479 fn from(s: Box<str>) -> Self {
480 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
486 #[stable(feature = "rust1", since = "1.0.0")]
487 /// Attempt to downcast the box to a concrete type.
492 /// use std::any::Any;
494 /// fn print_if_string(value: Box<dyn Any>) {
495 /// if let Ok(string) = value.downcast::<String>() {
496 /// println!("String ({}): {}", string.len(), string);
501 /// let my_string = "Hello World".to_string();
502 /// print_if_string(Box::new(my_string));
503 /// print_if_string(Box::new(0i8));
506 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
509 let raw: *mut dyn Any = Box::into_raw(self);
510 Ok(Box::from_raw(raw as *mut T))
518 impl Box<dyn Any + Send> {
520 #[stable(feature = "rust1", since = "1.0.0")]
521 /// Attempt to downcast the box to a concrete type.
526 /// use std::any::Any;
528 /// fn print_if_string(value: Box<dyn Any + Send>) {
529 /// if let Ok(string) = value.downcast::<String>() {
530 /// println!("String ({}): {}", string.len(), string);
535 /// let my_string = "Hello World".to_string();
536 /// print_if_string(Box::new(my_string));
537 /// print_if_string(Box::new(0i8));
540 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
541 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
542 // reapply the Send marker
543 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
551 fmt::Display::fmt(&**self, f)
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
557 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
558 fmt::Debug::fmt(&**self, f)
562 #[stable(feature = "rust1", since = "1.0.0")]
563 impl<T: ?Sized> fmt::Pointer for Box<T> {
564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
565 // It's not possible to extract the inner Uniq directly from the Box,
566 // instead we cast it to a *const which aliases the Unique
567 let ptr: *const T = &**self;
568 fmt::Pointer::fmt(&ptr, f)
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<T: ?Sized> Deref for Box<T> {
576 fn deref(&self) -> &T {
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T: ?Sized> DerefMut for Box<T> {
583 fn deref_mut(&mut self) -> &mut T {
588 #[unstable(feature = "receiver_trait", issue = "0")]
589 impl<T: ?Sized> Receiver for Box<T> {}
591 #[stable(feature = "rust1", since = "1.0.0")]
592 impl<I: Iterator + ?Sized> Iterator for Box<I> {
594 fn next(&mut self) -> Option<I::Item> {
597 fn size_hint(&self) -> (usize, Option<usize>) {
600 fn nth(&mut self, n: usize) -> Option<I::Item> {
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
606 fn next_back(&mut self) -> Option<I::Item> {
610 #[stable(feature = "rust1", since = "1.0.0")]
611 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
612 fn len(&self) -> usize {
615 fn is_empty(&self) -> bool {
620 #[stable(feature = "fused", since = "1.26.0")]
621 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
624 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
625 /// closure objects. The idea is that where one would normally store a
626 /// `Box<dyn FnOnce()>` in a data structure, you should use
627 /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except
628 /// that a `FnBox` closure can only be called if it is boxed. (Note
629 /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>`
630 /// closures become directly usable.)
634 /// Here is a snippet of code which creates a hashmap full of boxed
635 /// once closures and then removes them one by one, calling each
636 /// closure as it is removed. Note that the type of the closures
637 /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce()
641 /// #![feature(fnbox)]
643 /// use std::boxed::FnBox;
644 /// use std::collections::HashMap;
646 /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> {
647 /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new();
648 /// map.insert(1, Box::new(|| 22));
649 /// map.insert(2, Box::new(|| 44));
654 /// let mut map = make_map();
655 /// for i in &[1, 2] {
656 /// let f = map.remove(&i).unwrap();
657 /// assert_eq!(f(), i * 22);
662 #[unstable(feature = "fnbox",
663 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
667 fn call_box(self: Box<Self>, args: A) -> Self::Output;
670 #[unstable(feature = "fnbox",
671 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
672 impl<A, F> FnBox<A> for F
675 type Output = F::Output;
677 fn call_box(self: Box<F>, args: A) -> F::Output {
682 #[unstable(feature = "fnbox",
683 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
684 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> {
687 extern "rust-call" fn call_once(self, args: A) -> R {
692 #[unstable(feature = "fnbox",
693 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
694 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> {
697 extern "rust-call" fn call_once(self, args: A) -> R {
702 #[unstable(feature = "coerce_unsized", issue = "27732")]
703 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
705 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
706 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
708 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
709 impl<A> FromIterator<A> for Box<[A]> {
710 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
711 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
715 #[stable(feature = "box_slice_clone", since = "1.3.0")]
716 impl<T: Clone> Clone for Box<[T]> {
717 fn clone(&self) -> Self {
718 let mut new = BoxBuilder {
719 data: RawVec::with_capacity(self.len()),
723 let mut target = new.data.ptr();
725 for item in self.iter() {
727 ptr::write(target, item.clone());
728 target = target.offset(1);
734 return unsafe { new.into_box() };
736 // Helper type for responding to panics correctly.
737 struct BoxBuilder<T> {
742 impl<T> BoxBuilder<T> {
743 unsafe fn into_box(self) -> Box<[T]> {
744 let raw = ptr::read(&self.data);
750 impl<T> Drop for BoxBuilder<T> {
752 let mut data = self.data.ptr();
753 let max = unsafe { data.add(self.len) };
758 data = data.offset(1);
766 #[stable(feature = "box_borrow", since = "1.1.0")]
767 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
768 fn borrow(&self) -> &T {
773 #[stable(feature = "box_borrow", since = "1.1.0")]
774 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
775 fn borrow_mut(&mut self) -> &mut T {
780 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
781 impl<T: ?Sized> AsRef<T> for Box<T> {
782 fn as_ref(&self) -> &T {
787 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
788 impl<T: ?Sized> AsMut<T> for Box<T> {
789 fn as_mut(&mut self) -> &mut T {
796 * We could have chosen not to add this impl, and instead have written a
797 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
798 * because Box<T> implements Unpin even when T does not, as a result of
801 * We chose this API instead of the alternative for a few reasons:
802 * - Logically, it is helpful to understand pinning in regard to the
803 * memory region being pointed to. For this reason none of the
804 * standard library pointer types support projecting through a pin
805 * (Box<T> is the only pointer type in std for which this would be
807 * - It is in practice very useful to have Box<T> be unconditionally
808 * Unpin because of trait objects, for which the structural auto
809 * trait functionality does not apply (e.g., Box<dyn Foo> would
810 * otherwise not be Unpin).
812 * Another type with the same semantics as Box but only a conditional
813 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
814 * could have a method to project a Pin<T> from it.
816 #[unstable(feature = "pin", issue = "49150")]
817 impl<T: ?Sized> Unpin for Box<T> { }
819 #[unstable(feature = "generator_trait", issue = "43122")]
820 impl<T> Generator for Box<T>
821 where T: Generator + ?Sized
823 type Yield = T::Yield;
824 type Return = T::Return;
825 unsafe fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> {
830 #[unstable(feature = "futures_api", issue = "50547")]
831 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
832 type Output = F::Output;
834 fn poll(mut self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
835 F::poll(Pin::new(&mut *self), lw)