1 //! A pointer type for heap allocation.
3 //! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
4 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
5 //! drop their contents when they go out of scope. Boxes also ensure that they
6 //! never allocate more than `isize::MAX` bytes.
10 //! Move a value from the stack to the heap by creating a [`Box`]:
14 //! let boxed: Box<u8> = Box::new(val);
17 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
20 //! let boxed: Box<u8> = Box::new(5);
21 //! let val: u8 = *boxed;
24 //! Creating a recursive data structure:
29 //! Cons(T, Box<List<T>>),
33 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //! println!("{:?}", list);
37 //! This will print `Cons(1, Cons(2, Nil))`.
39 //! Recursive structures must be boxed, because if the definition of `Cons`
42 //! ```compile_fail,E0072
48 //! It wouldn't work. This is because the size of a `List` depends on how many
49 //! elements are in the list, and so we don't know how much memory to allocate
50 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
51 //! big `Cons` needs to be.
55 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
56 //! its allocation. It is valid to convert both ways between a [`Box`] and a
57 //! raw pointer allocated with the [`Global`] allocator, given that the
58 //! [`Layout`] used with the allocator is correct for the type. More precisely,
59 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
60 //! with `Layout::for_value(&*value)` may be converted into a box using
61 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
62 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
63 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
65 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
66 //! as a single pointer and is also ABI-compatible with C pointers
67 //! (i.e. the C type `T*`). This means that if you have extern "C"
68 //! Rust functions that will be called from C, you can define those
69 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
70 //! type on the C side. As an example, consider this C header which
71 //! declares functions that create and destroy some kind of `Foo`
77 //! /* Returns ownership to the caller */
78 //! struct Foo* foo_new(void);
80 //! /* Takes ownership from the caller; no-op when invoked with NULL */
81 //! void foo_delete(struct Foo*);
84 //! These two functions might be implemented in Rust as follows. Here, the
85 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
86 //! the ownership constraints. Note also that the nullable argument to
87 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
95 //! #[allow(improper_ctypes_definitions)]
96 //! pub extern "C" fn foo_new() -> Box<Foo> {
101 //! #[allow(improper_ctypes_definitions)]
102 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
105 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
106 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
107 //! and expect things to work. `Box<T>` values will always be fully aligned,
108 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
109 //! free the value with the global allocator. In general, the best practice
110 //! is to only use `Box<T>` for pointers that originated from the global
113 //! **Important.** At least at present, you should avoid using
114 //! `Box<T>` types for functions that are defined in C but invoked
115 //! from Rust. In those cases, you should directly mirror the C types
116 //! as closely as possible. Using types like `Box<T>` where the C
117 //! definition is just using `T*` can lead to undefined behavior, as
118 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
120 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
121 //! [dereferencing]: ../../std/ops/trait.Deref.html
122 //! [`Box`]: struct.Box.html
123 //! [`Box<T>`]: struct.Box.html
124 //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
125 //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
126 //! [`Global`]: ../alloc/struct.Global.html
127 //! [`Layout`]: ../alloc/struct.Layout.html
128 //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value
130 #![stable(feature = "rust1", since = "1.0.0")]
133 use core::array::LengthAtMost32;
135 use core::cmp::Ordering;
136 use core::convert::{From, TryFrom};
138 use core::future::Future;
139 use core::hash::{Hash, Hasher};
140 use core::iter::{FromIterator, FusedIterator, Iterator};
141 use core::marker::{Unpin, Unsize};
144 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
147 use core::ptr::{self, NonNull, Unique};
148 use core::task::{Context, Poll};
150 use crate::alloc::{self, AllocInit, AllocRef, Global};
151 use crate::borrow::Cow;
152 use crate::raw_vec::RawVec;
153 use crate::str::from_boxed_utf8_unchecked;
156 /// A pointer type for heap allocation.
158 /// See the [module-level documentation](../../std/boxed/index.html) for more.
159 #[lang = "owned_box"]
161 #[stable(feature = "rust1", since = "1.0.0")]
162 pub struct Box<T: ?Sized>(Unique<T>);
165 /// Allocates memory on the heap and then places `x` into it.
167 /// This doesn't actually allocate if `T` is zero-sized.
172 /// let five = Box::new(5);
174 #[stable(feature = "rust1", since = "1.0.0")]
176 pub fn new(x: T) -> Box<T> {
180 /// Constructs a new box with uninitialized contents.
185 /// #![feature(new_uninit)]
187 /// let mut five = Box::<u32>::new_uninit();
189 /// let five = unsafe {
190 /// // Deferred initialization:
191 /// five.as_mut_ptr().write(5);
193 /// five.assume_init()
196 /// assert_eq!(*five, 5)
198 #[unstable(feature = "new_uninit", issue = "63291")]
199 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
200 let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
202 .alloc(layout, AllocInit::Uninitialized)
203 .unwrap_or_else(|_| alloc::handle_alloc_error(layout))
206 unsafe { Box::from_raw(ptr.as_ptr()) }
209 /// Constructs a new `Box` with uninitialized contents, with the memory
210 /// being filled with `0` bytes.
212 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
218 /// #![feature(new_uninit)]
220 /// let zero = Box::<u32>::new_zeroed();
221 /// let zero = unsafe { zero.assume_init() };
223 /// assert_eq!(*zero, 0)
226 /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
227 #[unstable(feature = "new_uninit", issue = "63291")]
228 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
229 let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
231 .alloc(layout, AllocInit::Zeroed)
232 .unwrap_or_else(|_| alloc::handle_alloc_error(layout))
235 unsafe { Box::from_raw(ptr.as_ptr()) }
238 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
239 /// `x` will be pinned in memory and unable to be moved.
240 #[stable(feature = "pin", since = "1.33.0")]
242 pub fn pin(x: T) -> Pin<Box<T>> {
246 /// Converts a `Box<T>` into a `Box<[T]>`
248 /// This conversion does not allocate on the heap and happens in place.
250 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
251 pub fn into_boxed_slice(boxed: Box<T>) -> Box<[T]> {
252 // *mut T and *mut [T; 1] have the same size and alignment
253 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut [T; 1]) }
258 /// Constructs a new boxed slice with uninitialized contents.
263 /// #![feature(new_uninit)]
265 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
267 /// let values = unsafe {
268 /// // Deferred initialization:
269 /// values[0].as_mut_ptr().write(1);
270 /// values[1].as_mut_ptr().write(2);
271 /// values[2].as_mut_ptr().write(3);
273 /// values.assume_init()
276 /// assert_eq!(*values, [1, 2, 3])
278 #[unstable(feature = "new_uninit", issue = "63291")]
279 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
280 unsafe { RawVec::with_capacity(len).into_box(len) }
284 impl<T> Box<mem::MaybeUninit<T>> {
285 /// Converts to `Box<T>`.
289 /// As with [`MaybeUninit::assume_init`],
290 /// it is up to the caller to guarantee that the value
291 /// really is in an initialized state.
292 /// Calling this when the content is not yet fully initialized
293 /// causes immediate undefined behavior.
295 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
300 /// #![feature(new_uninit)]
302 /// let mut five = Box::<u32>::new_uninit();
304 /// let five: Box<u32> = unsafe {
305 /// // Deferred initialization:
306 /// five.as_mut_ptr().write(5);
308 /// five.assume_init()
311 /// assert_eq!(*five, 5)
313 #[unstable(feature = "new_uninit", issue = "63291")]
315 pub unsafe fn assume_init(self) -> Box<T> {
316 unsafe { Box::from_raw(Box::into_raw(self) as *mut T) }
320 impl<T> Box<[mem::MaybeUninit<T>]> {
321 /// Converts to `Box<[T]>`.
325 /// As with [`MaybeUninit::assume_init`],
326 /// it is up to the caller to guarantee that the values
327 /// really are in an initialized state.
328 /// Calling this when the content is not yet fully initialized
329 /// causes immediate undefined behavior.
331 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
336 /// #![feature(new_uninit)]
338 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
340 /// let values = unsafe {
341 /// // Deferred initialization:
342 /// values[0].as_mut_ptr().write(1);
343 /// values[1].as_mut_ptr().write(2);
344 /// values[2].as_mut_ptr().write(3);
346 /// values.assume_init()
349 /// assert_eq!(*values, [1, 2, 3])
351 #[unstable(feature = "new_uninit", issue = "63291")]
353 pub unsafe fn assume_init(self) -> Box<[T]> {
354 unsafe { Box::from_raw(Box::into_raw(self) as *mut [T]) }
358 impl<T: ?Sized> Box<T> {
359 /// Constructs a box from a raw pointer.
361 /// After calling this function, the raw pointer is owned by the
362 /// resulting `Box`. Specifically, the `Box` destructor will call
363 /// the destructor of `T` and free the allocated memory. For this
364 /// to be safe, the memory must have been allocated in accordance
365 /// with the [memory layout] used by `Box` .
369 /// This function is unsafe because improper use may lead to
370 /// memory problems. For example, a double-free may occur if the
371 /// function is called twice on the same raw pointer.
374 /// Recreate a `Box` which was previously converted to a raw pointer
375 /// using [`Box::into_raw`]:
377 /// let x = Box::new(5);
378 /// let ptr = Box::into_raw(x);
379 /// let x = unsafe { Box::from_raw(ptr) };
381 /// Manually create a `Box` from scratch by using the global allocator:
383 /// use std::alloc::{alloc, Layout};
386 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
387 /// // In general .write is required to avoid attempting to destruct
388 /// // the (uninitialized) previous contents of `ptr`, though for this
389 /// // simple example `*ptr = 5` would have worked as well.
391 /// let x = Box::from_raw(ptr);
395 /// [memory layout]: index.html#memory-layout
396 /// [`Layout`]: ../alloc/struct.Layout.html
397 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
398 #[stable(feature = "box_raw", since = "1.4.0")]
400 pub unsafe fn from_raw(raw: *mut T) -> Self {
401 Box(unsafe { Unique::new_unchecked(raw) })
404 /// Consumes the `Box`, returning a wrapped raw pointer.
406 /// The pointer will be properly aligned and non-null.
408 /// After calling this function, the caller is responsible for the
409 /// memory previously managed by the `Box`. In particular, the
410 /// caller should properly destroy `T` and release the memory, taking
411 /// into account the [memory layout] used by `Box`. The easiest way to
412 /// do this is to convert the raw pointer back into a `Box` with the
413 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
416 /// Note: this is an associated function, which means that you have
417 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
418 /// is so that there is no conflict with a method on the inner type.
421 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
422 /// for automatic cleanup:
424 /// let x = Box::new(String::from("Hello"));
425 /// let ptr = Box::into_raw(x);
426 /// let x = unsafe { Box::from_raw(ptr) };
428 /// Manual cleanup by explicitly running the destructor and deallocating
431 /// use std::alloc::{dealloc, Layout};
434 /// let x = Box::new(String::from("Hello"));
435 /// let p = Box::into_raw(x);
437 /// ptr::drop_in_place(p);
438 /// dealloc(p as *mut u8, Layout::new::<String>());
442 /// [memory layout]: index.html#memory-layout
443 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
444 #[stable(feature = "box_raw", since = "1.4.0")]
446 pub fn into_raw(b: Box<T>) -> *mut T {
447 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
448 // raw pointer for the type system. Turning it directly into a raw pointer would not be
449 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
450 // so all raw pointer methods go through `leak` which creates a (unique)
451 // mutable reference. Turning *that* to a raw pointer behaves correctly.
452 Box::leak(b) as *mut T
455 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
457 /// After calling this function, the caller is responsible for the
458 /// memory previously managed by the `Box`. In particular, the
459 /// caller should properly destroy `T` and release the memory. The
460 /// easiest way to do so is to convert the `NonNull<T>` pointer
461 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
464 /// Note: this is an associated function, which means that you have
465 /// to call it as `Box::into_raw_non_null(b)`
466 /// instead of `b.into_raw_non_null()`. This
467 /// is so that there is no conflict with a method on the inner type.
469 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
474 /// #![feature(box_into_raw_non_null)]
475 /// #![allow(deprecated)]
477 /// let x = Box::new(5);
478 /// let ptr = Box::into_raw_non_null(x);
480 /// // Clean up the memory by converting the NonNull pointer back
481 /// // into a Box and letting the Box be dropped.
482 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
484 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
487 reason = "use `Box::leak(b).into()` or `NonNull::from(Box::leak(b))` instead"
490 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
491 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
492 // raw pointer for the type system. Turning it directly into a raw pointer would not be
493 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
494 // so all raw pointer methods go through `leak` which creates a (unique)
495 // mutable reference. Turning *that* to a raw pointer behaves correctly.
500 feature = "ptr_internals",
502 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
506 pub fn into_unique(b: Box<T>) -> Unique<T> {
507 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
508 // raw pointer for the type system. Turning it directly into a raw pointer would not be
509 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
510 // so all raw pointer methods go through `leak` which creates a (unique)
511 // mutable reference. Turning *that* to a raw pointer behaves correctly.
515 /// Consumes and leaks the `Box`, returning a mutable reference,
516 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
517 /// `'a`. If the type has only static references, or none at all, then this
518 /// may be chosen to be `'static`.
520 /// This function is mainly useful for data that lives for the remainder of
521 /// the program's life. Dropping the returned reference will cause a memory
522 /// leak. If this is not acceptable, the reference should first be wrapped
523 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
524 /// then be dropped which will properly destroy `T` and release the
525 /// allocated memory.
527 /// Note: this is an associated function, which means that you have
528 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
529 /// is so that there is no conflict with a method on the inner type.
531 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
538 /// let x = Box::new(41);
539 /// let static_ref: &'static mut usize = Box::leak(x);
540 /// *static_ref += 1;
541 /// assert_eq!(*static_ref, 42);
547 /// let x = vec![1, 2, 3].into_boxed_slice();
548 /// let static_ref = Box::leak(x);
549 /// static_ref[0] = 4;
550 /// assert_eq!(*static_ref, [4, 2, 3]);
552 #[stable(feature = "box_leak", since = "1.26.0")]
554 pub fn leak<'a>(b: Box<T>) -> &'a mut T
556 T: 'a, // Technically not needed, but kept to be explicit.
558 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
561 /// Converts a `Box<T>` into a `Pin<Box<T>>`
563 /// This conversion does not allocate on the heap and happens in place.
565 /// This is also available via [`From`].
566 #[unstable(feature = "box_into_pin", issue = "62370")]
567 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
568 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
569 // when `T: !Unpin`, so it's safe to pin it directly without any
570 // additional requirements.
571 unsafe { Pin::new_unchecked(boxed) }
575 #[stable(feature = "rust1", since = "1.0.0")]
576 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
578 // FIXME: Do nothing, drop is currently performed by compiler.
582 #[stable(feature = "rust1", since = "1.0.0")]
583 impl<T: Default> Default for Box<T> {
584 /// Creates a `Box<T>`, with the `Default` value for T.
585 fn default() -> Box<T> {
586 box Default::default()
590 #[stable(feature = "rust1", since = "1.0.0")]
591 impl<T> Default for Box<[T]> {
592 fn default() -> Box<[T]> {
593 Box::<[T; 0]>::new([])
597 #[stable(feature = "default_box_extra", since = "1.17.0")]
598 impl Default for Box<str> {
599 fn default() -> Box<str> {
600 unsafe { from_boxed_utf8_unchecked(Default::default()) }
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl<T: Clone> Clone for Box<T> {
606 /// Returns a new box with a `clone()` of this box's contents.
611 /// let x = Box::new(5);
612 /// let y = x.clone();
614 /// // The value is the same
615 /// assert_eq!(x, y);
617 /// // But they are unique objects
618 /// assert_ne!(&*x as *const i32, &*y as *const i32);
622 fn clone(&self) -> Box<T> {
623 box { (**self).clone() }
626 /// Copies `source`'s contents into `self` without creating a new allocation.
631 /// let x = Box::new(5);
632 /// let mut y = Box::new(10);
633 /// let yp: *const i32 = &*y;
635 /// y.clone_from(&x);
637 /// // The value is the same
638 /// assert_eq!(x, y);
640 /// // And no allocation occurred
641 /// assert_eq!(yp, &*y);
644 fn clone_from(&mut self, source: &Box<T>) {
645 (**self).clone_from(&(**source));
649 #[stable(feature = "box_slice_clone", since = "1.3.0")]
650 impl Clone for Box<str> {
651 fn clone(&self) -> Self {
652 // this makes a copy of the data
653 let buf: Box<[u8]> = self.as_bytes().into();
654 unsafe { from_boxed_utf8_unchecked(buf) }
658 #[stable(feature = "rust1", since = "1.0.0")]
659 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
661 fn eq(&self, other: &Box<T>) -> bool {
662 PartialEq::eq(&**self, &**other)
665 fn ne(&self, other: &Box<T>) -> bool {
666 PartialEq::ne(&**self, &**other)
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
672 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
673 PartialOrd::partial_cmp(&**self, &**other)
676 fn lt(&self, other: &Box<T>) -> bool {
677 PartialOrd::lt(&**self, &**other)
680 fn le(&self, other: &Box<T>) -> bool {
681 PartialOrd::le(&**self, &**other)
684 fn ge(&self, other: &Box<T>) -> bool {
685 PartialOrd::ge(&**self, &**other)
688 fn gt(&self, other: &Box<T>) -> bool {
689 PartialOrd::gt(&**self, &**other)
692 #[stable(feature = "rust1", since = "1.0.0")]
693 impl<T: ?Sized + Ord> Ord for Box<T> {
695 fn cmp(&self, other: &Box<T>) -> Ordering {
696 Ord::cmp(&**self, &**other)
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl<T: ?Sized + Eq> Eq for Box<T> {}
702 #[stable(feature = "rust1", since = "1.0.0")]
703 impl<T: ?Sized + Hash> Hash for Box<T> {
704 fn hash<H: Hasher>(&self, state: &mut H) {
705 (**self).hash(state);
709 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
710 impl<T: ?Sized + Hasher> Hasher for Box<T> {
711 fn finish(&self) -> u64 {
714 fn write(&mut self, bytes: &[u8]) {
715 (**self).write(bytes)
717 fn write_u8(&mut self, i: u8) {
720 fn write_u16(&mut self, i: u16) {
721 (**self).write_u16(i)
723 fn write_u32(&mut self, i: u32) {
724 (**self).write_u32(i)
726 fn write_u64(&mut self, i: u64) {
727 (**self).write_u64(i)
729 fn write_u128(&mut self, i: u128) {
730 (**self).write_u128(i)
732 fn write_usize(&mut self, i: usize) {
733 (**self).write_usize(i)
735 fn write_i8(&mut self, i: i8) {
738 fn write_i16(&mut self, i: i16) {
739 (**self).write_i16(i)
741 fn write_i32(&mut self, i: i32) {
742 (**self).write_i32(i)
744 fn write_i64(&mut self, i: i64) {
745 (**self).write_i64(i)
747 fn write_i128(&mut self, i: i128) {
748 (**self).write_i128(i)
750 fn write_isize(&mut self, i: isize) {
751 (**self).write_isize(i)
755 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
756 impl<T> From<T> for Box<T> {
757 /// Converts a generic type `T` into a `Box<T>`
759 /// The conversion allocates on the heap and moves `t`
760 /// from the stack into it.
765 /// let boxed = Box::new(5);
767 /// assert_eq!(Box::from(x), boxed);
769 fn from(t: T) -> Self {
774 #[stable(feature = "pin", since = "1.33.0")]
775 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
776 /// Converts a `Box<T>` into a `Pin<Box<T>>`
778 /// This conversion does not allocate on the heap and happens in place.
779 fn from(boxed: Box<T>) -> Self {
784 #[stable(feature = "box_from_slice", since = "1.17.0")]
785 impl<T: Copy> From<&[T]> for Box<[T]> {
786 /// Converts a `&[T]` into a `Box<[T]>`
788 /// This conversion allocates on the heap
789 /// and performs a copy of `slice`.
793 /// // create a &[u8] which will be used to create a Box<[u8]>
794 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
795 /// let boxed_slice: Box<[u8]> = Box::from(slice);
797 /// println!("{:?}", boxed_slice);
799 fn from(slice: &[T]) -> Box<[T]> {
800 let len = slice.len();
801 let buf = RawVec::with_capacity(len);
803 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
804 buf.into_box(slice.len()).assume_init()
809 #[stable(feature = "box_from_cow", since = "1.45.0")]
810 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
812 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
814 Cow::Borrowed(slice) => Box::from(slice),
815 Cow::Owned(slice) => Box::from(slice),
820 #[stable(feature = "box_from_slice", since = "1.17.0")]
821 impl From<&str> for Box<str> {
822 /// Converts a `&str` into a `Box<str>`
824 /// This conversion allocates on the heap
825 /// and performs a copy of `s`.
829 /// let boxed: Box<str> = Box::from("hello");
830 /// println!("{}", boxed);
833 fn from(s: &str) -> Box<str> {
834 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
838 #[stable(feature = "box_from_cow", since = "1.45.0")]
839 impl From<Cow<'_, str>> for Box<str> {
841 fn from(cow: Cow<'_, str>) -> Box<str> {
843 Cow::Borrowed(s) => Box::from(s),
844 Cow::Owned(s) => Box::from(s),
849 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
850 impl From<Box<str>> for Box<[u8]> {
851 /// Converts a `Box<str>>` into a `Box<[u8]>`
853 /// This conversion does not allocate on the heap and happens in place.
857 /// // create a Box<str> which will be used to create a Box<[u8]>
858 /// let boxed: Box<str> = Box::from("hello");
859 /// let boxed_str: Box<[u8]> = Box::from(boxed);
861 /// // create a &[u8] which will be used to create a Box<[u8]>
862 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
863 /// let boxed_slice = Box::from(slice);
865 /// assert_eq!(boxed_slice, boxed_str);
868 fn from(s: Box<str>) -> Self {
869 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
873 #[stable(feature = "box_from_array", since = "1.45.0")]
874 impl<T, const N: usize> From<[T; N]> for Box<[T]>
876 [T; N]: LengthAtMost32,
878 /// Converts a `[T; N]` into a `Box<[T]>`
880 /// This conversion moves the array to newly heap-allocated memory.
884 /// let boxed: Box<[u8]> = Box::from([4, 2]);
885 /// println!("{:?}", boxed);
887 fn from(array: [T; N]) -> Box<[T]> {
892 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
893 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]>
895 [T; N]: LengthAtMost32,
897 type Error = Box<[T]>;
899 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
900 if boxed_slice.len() == N {
901 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
910 #[stable(feature = "rust1", since = "1.0.0")]
911 /// Attempt to downcast the box to a concrete type.
916 /// use std::any::Any;
918 /// fn print_if_string(value: Box<dyn Any>) {
919 /// if let Ok(string) = value.downcast::<String>() {
920 /// println!("String ({}): {}", string.len(), string);
924 /// let my_string = "Hello World".to_string();
925 /// print_if_string(Box::new(my_string));
926 /// print_if_string(Box::new(0i8));
928 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
931 let raw: *mut dyn Any = Box::into_raw(self);
932 Ok(Box::from_raw(raw as *mut T))
940 impl Box<dyn Any + Send> {
942 #[stable(feature = "rust1", since = "1.0.0")]
943 /// Attempt to downcast the box to a concrete type.
948 /// use std::any::Any;
950 /// fn print_if_string(value: Box<dyn Any + Send>) {
951 /// if let Ok(string) = value.downcast::<String>() {
952 /// println!("String ({}): {}", string.len(), string);
956 /// let my_string = "Hello World".to_string();
957 /// print_if_string(Box::new(my_string));
958 /// print_if_string(Box::new(0i8));
960 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
961 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
962 // reapply the Send marker
963 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
968 #[stable(feature = "rust1", since = "1.0.0")]
969 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
970 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
971 fmt::Display::fmt(&**self, f)
975 #[stable(feature = "rust1", since = "1.0.0")]
976 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
977 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
978 fmt::Debug::fmt(&**self, f)
982 #[stable(feature = "rust1", since = "1.0.0")]
983 impl<T: ?Sized> fmt::Pointer for Box<T> {
984 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
985 // It's not possible to extract the inner Uniq directly from the Box,
986 // instead we cast it to a *const which aliases the Unique
987 let ptr: *const T = &**self;
988 fmt::Pointer::fmt(&ptr, f)
992 #[stable(feature = "rust1", since = "1.0.0")]
993 impl<T: ?Sized> Deref for Box<T> {
996 fn deref(&self) -> &T {
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 impl<T: ?Sized> DerefMut for Box<T> {
1003 fn deref_mut(&mut self) -> &mut T {
1008 #[unstable(feature = "receiver_trait", issue = "none")]
1009 impl<T: ?Sized> Receiver for Box<T> {}
1011 #[stable(feature = "rust1", since = "1.0.0")]
1012 impl<I: Iterator + ?Sized> Iterator for Box<I> {
1013 type Item = I::Item;
1014 fn next(&mut self) -> Option<I::Item> {
1017 fn size_hint(&self) -> (usize, Option<usize>) {
1018 (**self).size_hint()
1020 fn nth(&mut self, n: usize) -> Option<I::Item> {
1023 fn last(self) -> Option<I::Item> {
1030 fn last(self) -> Option<Self::Item>;
1033 impl<I: Iterator + ?Sized> BoxIter for Box<I> {
1034 type Item = I::Item;
1035 default fn last(self) -> Option<I::Item> {
1037 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1041 self.fold(None, some)
1045 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1046 /// instead of the default.
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 impl<I: Iterator> BoxIter for Box<I> {
1049 fn last(self) -> Option<I::Item> {
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
1056 fn next_back(&mut self) -> Option<I::Item> {
1057 (**self).next_back()
1059 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1060 (**self).nth_back(n)
1063 #[stable(feature = "rust1", since = "1.0.0")]
1064 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
1065 fn len(&self) -> usize {
1068 fn is_empty(&self) -> bool {
1073 #[stable(feature = "fused", since = "1.26.0")]
1074 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
1076 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1077 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
1078 type Output = <F as FnOnce<A>>::Output;
1080 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
1081 <F as FnOnce<A>>::call_once(*self, args)
1085 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1086 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
1087 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
1088 <F as FnMut<A>>::call_mut(self, args)
1092 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1093 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
1094 extern "rust-call" fn call(&self, args: A) -> Self::Output {
1095 <F as Fn<A>>::call(self, args)
1099 #[unstable(feature = "coerce_unsized", issue = "27732")]
1100 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
1102 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1103 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
1105 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1106 impl<A> FromIterator<A> for Box<[A]> {
1107 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
1108 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1112 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1113 impl<T: Clone> Clone for Box<[T]> {
1114 fn clone(&self) -> Self {
1115 self.to_vec().into_boxed_slice()
1118 fn clone_from(&mut self, other: &Self) {
1119 if self.len() == other.len() {
1120 self.clone_from_slice(&other);
1122 *self = other.clone();
1127 #[stable(feature = "box_borrow", since = "1.1.0")]
1128 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
1129 fn borrow(&self) -> &T {
1134 #[stable(feature = "box_borrow", since = "1.1.0")]
1135 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
1136 fn borrow_mut(&mut self) -> &mut T {
1141 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1142 impl<T: ?Sized> AsRef<T> for Box<T> {
1143 fn as_ref(&self) -> &T {
1148 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1149 impl<T: ?Sized> AsMut<T> for Box<T> {
1150 fn as_mut(&mut self) -> &mut T {
1157 * We could have chosen not to add this impl, and instead have written a
1158 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1159 * because Box<T> implements Unpin even when T does not, as a result of
1162 * We chose this API instead of the alternative for a few reasons:
1163 * - Logically, it is helpful to understand pinning in regard to the
1164 * memory region being pointed to. For this reason none of the
1165 * standard library pointer types support projecting through a pin
1166 * (Box<T> is the only pointer type in std for which this would be
1168 * - It is in practice very useful to have Box<T> be unconditionally
1169 * Unpin because of trait objects, for which the structural auto
1170 * trait functionality does not apply (e.g., Box<dyn Foo> would
1171 * otherwise not be Unpin).
1173 * Another type with the same semantics as Box but only a conditional
1174 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1175 * could have a method to project a Pin<T> from it.
1177 #[stable(feature = "pin", since = "1.33.0")]
1178 impl<T: ?Sized> Unpin for Box<T> {}
1180 #[unstable(feature = "generator_trait", issue = "43122")]
1181 impl<G: ?Sized + Generator<R> + Unpin, R> Generator<R> for Box<G> {
1182 type Yield = G::Yield;
1183 type Return = G::Return;
1185 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1186 G::resume(Pin::new(&mut *self), arg)
1190 #[unstable(feature = "generator_trait", issue = "43122")]
1191 impl<G: ?Sized + Generator<R>, R> Generator<R> for Pin<Box<G>> {
1192 type Yield = G::Yield;
1193 type Return = G::Return;
1195 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1196 G::resume((*self).as_mut(), arg)
1200 #[stable(feature = "futures_api", since = "1.36.0")]
1201 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
1202 type Output = F::Output;
1204 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1205 F::poll(Pin::new(&mut *self), cx)