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.
9 //! Move a value from the stack to the heap by creating a [`Box`]:
13 //! let boxed: Box<u8> = Box::new(val);
16 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
19 //! let boxed: Box<u8> = Box::new(5);
20 //! let val: u8 = *boxed;
23 //! Creating a recursive data structure:
28 //! Cons(T, Box<List<T>>),
32 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
33 //! println!("{:?}", list);
36 //! This will print `Cons(1, Cons(2, Nil))`.
38 //! Recursive structures must be boxed, because if the definition of `Cons`
41 //! ```compile_fail,E0072
47 //! It wouldn't work. This is because the size of a `List` depends on how many
48 //! elements are in the list, and so we don't know how much memory to allocate
49 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
50 //! big `Cons` needs to be.
54 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
55 //! its allocation. It is valid to convert both ways between a [`Box`] and a
56 //! raw pointer allocated with the [`Global`] allocator, given that the
57 //! [`Layout`] used with the allocator is correct for the type. More precisely,
58 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
59 //! with `Layout::for_value(&*value)` may be converted into a box using
60 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
61 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
62 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
64 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
65 //! as a single pointer and is also ABI-compatible with C pointers
66 //! (i.e. the C type `T*`). This means that if you have extern "C"
67 //! Rust functions that will be called from C, you can define those
68 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
69 //! type on the C side. As an example, consider this C header which
70 //! declares functions that create and destroy some kind of `Foo`
76 //! /* Returns ownership to the caller */
77 //! struct Foo* foo_new(void);
79 //! /* Takes ownership from the caller; no-op when invoked with NULL */
80 //! void foo_delete(struct Foo*);
83 //! These two functions might be implemented in Rust as follows. Here, the
84 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
85 //! the ownership constraints. Note also that the nullable argument to
86 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
94 //! pub extern "C" fn foo_new() -> Box<Foo> {
99 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
102 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
103 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
104 //! and expect things to work. `Box<T>` values will always be fully aligned,
105 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
106 //! free the value with the global allocator. In general, the best practice
107 //! is to only use `Box<T>` for pointers that originated from the global
110 //! **Important.** At least at present, you should avoid using
111 //! `Box<T>` types for functions that are defined in C but invoked
112 //! from Rust. In those cases, you should directly mirror the C types
113 //! as closely as possible. Using types like `Box<T>` where the C
114 //! definition is just using `T*` can lead to undefined behavior, as
115 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
117 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
118 //! [dereferencing]: ../../std/ops/trait.Deref.html
119 //! [`Box`]: struct.Box.html
120 //! [`Box<T>`]: struct.Box.html
121 //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
122 //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
123 //! [`Global`]: ../alloc/struct.Global.html
124 //! [`Layout`]: ../alloc/struct.Layout.html
125 //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value
127 #![stable(feature = "rust1", since = "1.0.0")]
130 use core::array::LengthAtMost32;
132 use core::cmp::Ordering;
133 use core::convert::{From, TryFrom};
135 use core::future::Future;
136 use core::hash::{Hash, Hasher};
137 use core::iter::{FromIterator, FusedIterator, Iterator};
138 use core::marker::{Unpin, Unsize};
141 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
144 use core::ptr::{self, NonNull, Unique};
146 use core::task::{Context, Poll};
148 use crate::alloc::{self, Alloc, Global};
149 use crate::raw_vec::RawVec;
150 use crate::str::from_boxed_utf8_unchecked;
153 /// A pointer type for heap allocation.
155 /// See the [module-level documentation](../../std/boxed/index.html) for more.
156 #[lang = "owned_box"]
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub struct Box<T: ?Sized>(Unique<T>);
162 /// Allocates memory on the heap and then places `x` into it.
164 /// This doesn't actually allocate if `T` is zero-sized.
169 /// let five = Box::new(5);
171 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn new(x: T) -> Box<T> {
177 /// Constructs a new box with uninitialized contents.
182 /// #![feature(new_uninit)]
184 /// let mut five = Box::<u32>::new_uninit();
186 /// let five = unsafe {
187 /// // Deferred initialization:
188 /// five.as_mut_ptr().write(5);
190 /// five.assume_init()
193 /// assert_eq!(*five, 5)
195 #[unstable(feature = "new_uninit", issue = "63291")]
196 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
197 let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
198 if layout.size() == 0 {
199 return Box(NonNull::dangling().into());
202 unsafe { Global.alloc(layout).unwrap_or_else(|_| alloc::handle_alloc_error(layout)) };
203 Box(ptr.cast().into())
206 /// Constructs a new `Box` with uninitialized contents, with the memory
207 /// being filled with `0` bytes.
209 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
215 /// #![feature(new_uninit)]
217 /// let zero = Box::<u32>::new_zeroed();
218 /// let zero = unsafe { zero.assume_init() };
220 /// assert_eq!(*zero, 0)
223 /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
224 #[unstable(feature = "new_uninit", issue = "63291")]
225 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
227 let mut uninit = Self::new_uninit();
228 ptr::write_bytes::<T>(uninit.as_mut_ptr(), 0, 1);
233 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
234 /// `x` will be pinned in memory and unable to be moved.
235 #[stable(feature = "pin", since = "1.33.0")]
237 pub fn pin(x: T) -> Pin<Box<T>> {
243 /// Constructs a new boxed slice with uninitialized contents.
248 /// #![feature(new_uninit)]
250 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
252 /// let values = unsafe {
253 /// // Deferred initialization:
254 /// values[0].as_mut_ptr().write(1);
255 /// values[1].as_mut_ptr().write(2);
256 /// values[2].as_mut_ptr().write(3);
258 /// values.assume_init()
261 /// assert_eq!(*values, [1, 2, 3])
263 #[unstable(feature = "new_uninit", issue = "63291")]
264 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
265 let layout = alloc::Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
266 let ptr = if layout.size() == 0 {
270 Global.alloc(layout).unwrap_or_else(|_| alloc::handle_alloc_error(layout)).cast()
273 let slice = unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len) };
274 Box(Unique::from(slice))
278 impl<T> Box<mem::MaybeUninit<T>> {
279 /// Converts to `Box<T>`.
283 /// As with [`MaybeUninit::assume_init`],
284 /// it is up to the caller to guarantee that the value
285 /// really is in an initialized state.
286 /// Calling this when the content is not yet fully initialized
287 /// causes immediate undefined behavior.
289 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
294 /// #![feature(new_uninit)]
296 /// let mut five = Box::<u32>::new_uninit();
298 /// let five: Box<u32> = unsafe {
299 /// // Deferred initialization:
300 /// five.as_mut_ptr().write(5);
302 /// five.assume_init()
305 /// assert_eq!(*five, 5)
307 #[unstable(feature = "new_uninit", issue = "63291")]
309 pub unsafe fn assume_init(self) -> Box<T> {
310 Box(Box::into_unique(self).cast())
314 impl<T> Box<[mem::MaybeUninit<T>]> {
315 /// Converts to `Box<[T]>`.
319 /// As with [`MaybeUninit::assume_init`],
320 /// it is up to the caller to guarantee that the values
321 /// really are in an initialized state.
322 /// Calling this when the content is not yet fully initialized
323 /// causes immediate undefined behavior.
325 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
330 /// #![feature(new_uninit)]
332 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
334 /// let values = unsafe {
335 /// // Deferred initialization:
336 /// values[0].as_mut_ptr().write(1);
337 /// values[1].as_mut_ptr().write(2);
338 /// values[2].as_mut_ptr().write(3);
340 /// values.assume_init()
343 /// assert_eq!(*values, [1, 2, 3])
345 #[unstable(feature = "new_uninit", issue = "63291")]
347 pub unsafe fn assume_init(self) -> Box<[T]> {
348 Box(Unique::new_unchecked(Box::into_raw(self) as _))
352 impl<T: ?Sized> Box<T> {
353 /// Constructs a box from a raw pointer.
355 /// After calling this function, the raw pointer is owned by the
356 /// resulting `Box`. Specifically, the `Box` destructor will call
357 /// the destructor of `T` and free the allocated memory. For this
358 /// to be safe, the memory must have been allocated in accordance
359 /// with the [memory layout] used by `Box` .
363 /// This function is unsafe because improper use may lead to
364 /// memory problems. For example, a double-free may occur if the
365 /// function is called twice on the same raw pointer.
368 /// Recreate a `Box` which was previously converted to a raw pointer
369 /// using [`Box::into_raw`]:
371 /// let x = Box::new(5);
372 /// let ptr = Box::into_raw(x);
373 /// let x = unsafe { Box::from_raw(ptr) };
375 /// Manually create a `Box` from scratch by using the global allocator:
377 /// use std::alloc::{alloc, Layout};
380 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
382 /// let x = Box::from_raw(ptr);
386 /// [memory layout]: index.html#memory-layout
387 /// [`Layout`]: ../alloc/struct.Layout.html
388 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
389 #[stable(feature = "box_raw", since = "1.4.0")]
391 pub unsafe fn from_raw(raw: *mut T) -> Self {
392 Box(Unique::new_unchecked(raw))
395 /// Consumes the `Box`, returning a wrapped raw pointer.
397 /// The pointer will be properly aligned and non-null.
399 /// After calling this function, the caller is responsible for the
400 /// memory previously managed by the `Box`. In particular, the
401 /// caller should properly destroy `T` and release the memory, taking
402 /// into account the [memory layout] used by `Box`. The easiest way to
403 /// do this is to convert the raw pointer back into a `Box` with the
404 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
407 /// Note: this is an associated function, which means that you have
408 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
409 /// is so that there is no conflict with a method on the inner type.
412 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
413 /// for automatic cleanup:
415 /// let x = Box::new(String::from("Hello"));
416 /// let ptr = Box::into_raw(x);
417 /// let x = unsafe { Box::from_raw(ptr) };
419 /// Manual cleanup by explicitly running the destructor and deallocating
422 /// use std::alloc::{dealloc, Layout};
425 /// let x = Box::new(String::from("Hello"));
426 /// let p = Box::into_raw(x);
428 /// ptr::drop_in_place(p);
429 /// dealloc(p as *mut u8, Layout::new::<String>());
433 /// [memory layout]: index.html#memory-layout
434 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
435 #[stable(feature = "box_raw", since = "1.4.0")]
437 pub fn into_raw(b: Box<T>) -> *mut T {
438 Box::into_raw_non_null(b).as_ptr()
441 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
443 /// After calling this function, the caller is responsible for the
444 /// memory previously managed by the `Box`. In particular, the
445 /// caller should properly destroy `T` and release the memory. The
446 /// easiest way to do so is to convert the `NonNull<T>` pointer
447 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
450 /// Note: this is an associated function, which means that you have
451 /// to call it as `Box::into_raw_non_null(b)`
452 /// instead of `b.into_raw_non_null()`. This
453 /// is so that there is no conflict with a method on the inner type.
455 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
460 /// #![feature(box_into_raw_non_null)]
462 /// let x = Box::new(5);
463 /// let ptr = Box::into_raw_non_null(x);
465 /// // Clean up the memory by converting the NonNull pointer back
466 /// // into a Box and letting the Box be dropped.
467 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
469 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
471 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
472 Box::into_unique(b).into()
475 #[unstable(feature = "ptr_internals", issue = "none", reason = "use into_raw_non_null instead")]
478 pub fn into_unique(b: Box<T>) -> Unique<T> {
479 let mut unique = b.0;
481 // Box is kind-of a library type, but recognized as a "unique pointer" by
482 // Stacked Borrows. This function here corresponds to "reborrowing to
483 // a raw pointer", but there is no actual reborrow here -- so
484 // without some care, the pointer we are returning here still carries
485 // the tag of `b`, with `Unique` permission.
486 // We round-trip through a mutable reference to avoid that.
487 unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
490 /// Consumes and leaks the `Box`, returning a mutable reference,
491 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
492 /// `'a`. If the type has only static references, or none at all, then this
493 /// may be chosen to be `'static`.
495 /// This function is mainly useful for data that lives for the remainder of
496 /// the program's life. Dropping the returned reference will cause a memory
497 /// leak. If this is not acceptable, the reference should first be wrapped
498 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
499 /// then be dropped which will properly destroy `T` and release the
500 /// allocated memory.
502 /// Note: this is an associated function, which means that you have
503 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
504 /// is so that there is no conflict with a method on the inner type.
506 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
513 /// let x = Box::new(41);
514 /// let static_ref: &'static mut usize = Box::leak(x);
515 /// *static_ref += 1;
516 /// assert_eq!(*static_ref, 42);
522 /// let x = vec![1, 2, 3].into_boxed_slice();
523 /// let static_ref = Box::leak(x);
524 /// static_ref[0] = 4;
525 /// assert_eq!(*static_ref, [4, 2, 3]);
527 #[stable(feature = "box_leak", since = "1.26.0")]
529 pub fn leak<'a>(b: Box<T>) -> &'a mut T
531 T: 'a, // Technically not needed, but kept to be explicit.
533 unsafe { &mut *Box::into_raw(b) }
536 /// Converts a `Box<T>` into a `Pin<Box<T>>`
538 /// This conversion does not allocate on the heap and happens in place.
540 /// This is also available via [`From`].
541 #[unstable(feature = "box_into_pin", issue = "62370")]
542 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
543 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
544 // when `T: !Unpin`, so it's safe to pin it directly without any
545 // additional requirements.
546 unsafe { Pin::new_unchecked(boxed) }
550 #[stable(feature = "rust1", since = "1.0.0")]
551 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
553 // FIXME: Do nothing, drop is currently performed by compiler.
557 #[stable(feature = "rust1", since = "1.0.0")]
558 impl<T: Default> Default for Box<T> {
559 /// Creates a `Box<T>`, with the `Default` value for T.
560 fn default() -> Box<T> {
561 box Default::default()
565 #[stable(feature = "rust1", since = "1.0.0")]
566 impl<T> Default for Box<[T]> {
567 fn default() -> Box<[T]> {
568 Box::<[T; 0]>::new([])
572 #[stable(feature = "default_box_extra", since = "1.17.0")]
573 impl Default for Box<str> {
574 fn default() -> Box<str> {
575 unsafe { from_boxed_utf8_unchecked(Default::default()) }
579 #[stable(feature = "rust1", since = "1.0.0")]
580 impl<T: Clone> Clone for Box<T> {
581 /// Returns a new box with a `clone()` of this box's contents.
586 /// let x = Box::new(5);
587 /// let y = x.clone();
589 /// // The value is the same
590 /// assert_eq!(x, y);
592 /// // But they are unique objects
593 /// assert_ne!(&*x as *const i32, &*y as *const i32);
597 fn clone(&self) -> Box<T> {
598 box { (**self).clone() }
601 /// Copies `source`'s contents into `self` without creating a new allocation.
606 /// let x = Box::new(5);
607 /// let mut y = Box::new(10);
608 /// let yp: *const i32 = &*y;
610 /// y.clone_from(&x);
612 /// // The value is the same
613 /// assert_eq!(x, y);
615 /// // And no allocation occurred
616 /// assert_eq!(yp, &*y);
619 fn clone_from(&mut self, source: &Box<T>) {
620 (**self).clone_from(&(**source));
624 #[stable(feature = "box_slice_clone", since = "1.3.0")]
625 impl Clone for Box<str> {
626 fn clone(&self) -> Self {
627 // this makes a copy of the data
628 let buf: Box<[u8]> = self.as_bytes().into();
629 unsafe { from_boxed_utf8_unchecked(buf) }
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
636 fn eq(&self, other: &Box<T>) -> bool {
637 PartialEq::eq(&**self, &**other)
640 fn ne(&self, other: &Box<T>) -> bool {
641 PartialEq::ne(&**self, &**other)
644 #[stable(feature = "rust1", since = "1.0.0")]
645 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
647 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
648 PartialOrd::partial_cmp(&**self, &**other)
651 fn lt(&self, other: &Box<T>) -> bool {
652 PartialOrd::lt(&**self, &**other)
655 fn le(&self, other: &Box<T>) -> bool {
656 PartialOrd::le(&**self, &**other)
659 fn ge(&self, other: &Box<T>) -> bool {
660 PartialOrd::ge(&**self, &**other)
663 fn gt(&self, other: &Box<T>) -> bool {
664 PartialOrd::gt(&**self, &**other)
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl<T: ?Sized + Ord> Ord for Box<T> {
670 fn cmp(&self, other: &Box<T>) -> Ordering {
671 Ord::cmp(&**self, &**other)
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl<T: ?Sized + Eq> Eq for Box<T> {}
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<T: ?Sized + Hash> Hash for Box<T> {
679 fn hash<H: Hasher>(&self, state: &mut H) {
680 (**self).hash(state);
684 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
685 impl<T: ?Sized + Hasher> Hasher for Box<T> {
686 fn finish(&self) -> u64 {
689 fn write(&mut self, bytes: &[u8]) {
690 (**self).write(bytes)
692 fn write_u8(&mut self, i: u8) {
695 fn write_u16(&mut self, i: u16) {
696 (**self).write_u16(i)
698 fn write_u32(&mut self, i: u32) {
699 (**self).write_u32(i)
701 fn write_u64(&mut self, i: u64) {
702 (**self).write_u64(i)
704 fn write_u128(&mut self, i: u128) {
705 (**self).write_u128(i)
707 fn write_usize(&mut self, i: usize) {
708 (**self).write_usize(i)
710 fn write_i8(&mut self, i: i8) {
713 fn write_i16(&mut self, i: i16) {
714 (**self).write_i16(i)
716 fn write_i32(&mut self, i: i32) {
717 (**self).write_i32(i)
719 fn write_i64(&mut self, i: i64) {
720 (**self).write_i64(i)
722 fn write_i128(&mut self, i: i128) {
723 (**self).write_i128(i)
725 fn write_isize(&mut self, i: isize) {
726 (**self).write_isize(i)
730 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
731 impl<T> From<T> for Box<T> {
732 /// Converts a generic type `T` into a `Box<T>`
734 /// The conversion allocates on the heap and moves `t`
735 /// from the stack into it.
740 /// let boxed = Box::new(5);
742 /// assert_eq!(Box::from(x), boxed);
744 fn from(t: T) -> Self {
749 #[stable(feature = "pin", since = "1.33.0")]
750 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
751 /// Converts a `Box<T>` into a `Pin<Box<T>>`
753 /// This conversion does not allocate on the heap and happens in place.
754 fn from(boxed: Box<T>) -> Self {
759 #[stable(feature = "box_from_slice", since = "1.17.0")]
760 impl<T: Copy> From<&[T]> for Box<[T]> {
761 /// Converts a `&[T]` into a `Box<[T]>`
763 /// This conversion allocates on the heap
764 /// and performs a copy of `slice`.
768 /// // create a &[u8] which will be used to create a Box<[u8]>
769 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
770 /// let boxed_slice: Box<[u8]> = Box::from(slice);
772 /// println!("{:?}", boxed_slice);
774 fn from(slice: &[T]) -> Box<[T]> {
775 let len = slice.len();
776 let buf = RawVec::with_capacity(len);
778 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
784 #[stable(feature = "box_from_slice", since = "1.17.0")]
785 impl From<&str> for Box<str> {
786 /// Converts a `&str` into a `Box<str>`
788 /// This conversion allocates on the heap
789 /// and performs a copy of `s`.
793 /// let boxed: Box<str> = Box::from("hello");
794 /// println!("{}", boxed);
797 fn from(s: &str) -> Box<str> {
798 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
802 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
803 impl From<Box<str>> for Box<[u8]> {
804 /// Converts a `Box<str>>` into a `Box<[u8]>`
806 /// This conversion does not allocate on the heap and happens in place.
810 /// // create a Box<str> which will be used to create a Box<[u8]>
811 /// let boxed: Box<str> = Box::from("hello");
812 /// let boxed_str: Box<[u8]> = Box::from(boxed);
814 /// // create a &[u8] which will be used to create a Box<[u8]>
815 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
816 /// let boxed_slice = Box::from(slice);
818 /// assert_eq!(boxed_slice, boxed_str);
821 fn from(s: Box<str>) -> Self {
822 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
826 #[unstable(feature = "boxed_slice_try_from", issue = "none")]
827 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]>
829 [T; N]: LengthAtMost32,
831 type Error = Box<[T]>;
833 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
834 if boxed_slice.len() == N {
835 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
844 #[stable(feature = "rust1", since = "1.0.0")]
845 /// Attempt to downcast the box to a concrete type.
850 /// use std::any::Any;
852 /// fn print_if_string(value: Box<dyn Any>) {
853 /// if let Ok(string) = value.downcast::<String>() {
854 /// println!("String ({}): {}", string.len(), string);
858 /// let my_string = "Hello World".to_string();
859 /// print_if_string(Box::new(my_string));
860 /// print_if_string(Box::new(0i8));
862 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
865 let raw: *mut dyn Any = Box::into_raw(self);
866 Ok(Box::from_raw(raw as *mut T))
874 impl Box<dyn Any + Send> {
876 #[stable(feature = "rust1", since = "1.0.0")]
877 /// Attempt to downcast the box to a concrete type.
882 /// use std::any::Any;
884 /// fn print_if_string(value: Box<dyn Any + Send>) {
885 /// if let Ok(string) = value.downcast::<String>() {
886 /// println!("String ({}): {}", string.len(), string);
890 /// let my_string = "Hello World".to_string();
891 /// print_if_string(Box::new(my_string));
892 /// print_if_string(Box::new(0i8));
894 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
895 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
896 // reapply the Send marker
897 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
902 #[stable(feature = "rust1", since = "1.0.0")]
903 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
904 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
905 fmt::Display::fmt(&**self, f)
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
911 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
912 fmt::Debug::fmt(&**self, f)
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<T: ?Sized> fmt::Pointer for Box<T> {
918 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
919 // It's not possible to extract the inner Uniq directly from the Box,
920 // instead we cast it to a *const which aliases the Unique
921 let ptr: *const T = &**self;
922 fmt::Pointer::fmt(&ptr, f)
926 #[stable(feature = "rust1", since = "1.0.0")]
927 impl<T: ?Sized> Deref for Box<T> {
930 fn deref(&self) -> &T {
935 #[stable(feature = "rust1", since = "1.0.0")]
936 impl<T: ?Sized> DerefMut for Box<T> {
937 fn deref_mut(&mut self) -> &mut T {
942 #[unstable(feature = "receiver_trait", issue = "none")]
943 impl<T: ?Sized> Receiver for Box<T> {}
945 #[stable(feature = "rust1", since = "1.0.0")]
946 impl<I: Iterator + ?Sized> Iterator for Box<I> {
948 fn next(&mut self) -> Option<I::Item> {
951 fn size_hint(&self) -> (usize, Option<usize>) {
954 fn nth(&mut self, n: usize) -> Option<I::Item> {
957 fn last(self) -> Option<I::Item> {
964 fn last(self) -> Option<Self::Item>;
967 impl<I: Iterator + ?Sized> BoxIter for Box<I> {
969 default fn last(self) -> Option<I::Item> {
971 fn some<T>(_: Option<T>, x: T) -> Option<T> {
975 self.fold(None, some)
979 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
980 /// instead of the default.
981 #[stable(feature = "rust1", since = "1.0.0")]
982 impl<I: Iterator> BoxIter for Box<I> {
983 fn last(self) -> Option<I::Item> {
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
990 fn next_back(&mut self) -> Option<I::Item> {
993 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
997 #[stable(feature = "rust1", since = "1.0.0")]
998 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
999 fn len(&self) -> usize {
1002 fn is_empty(&self) -> bool {
1007 #[stable(feature = "fused", since = "1.26.0")]
1008 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
1010 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1011 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
1012 type Output = <F as FnOnce<A>>::Output;
1014 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
1015 <F as FnOnce<A>>::call_once(*self, args)
1019 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1020 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
1021 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
1022 <F as FnMut<A>>::call_mut(self, args)
1026 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1027 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
1028 extern "rust-call" fn call(&self, args: A) -> Self::Output {
1029 <F as Fn<A>>::call(self, args)
1033 #[unstable(feature = "coerce_unsized", issue = "27732")]
1034 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
1036 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1037 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
1039 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1040 impl<A> FromIterator<A> for Box<[A]> {
1041 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
1042 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1046 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1047 impl<T: Clone> Clone for Box<[T]> {
1048 fn clone(&self) -> Self {
1049 self.to_vec().into_boxed_slice()
1053 #[stable(feature = "box_borrow", since = "1.1.0")]
1054 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
1055 fn borrow(&self) -> &T {
1060 #[stable(feature = "box_borrow", since = "1.1.0")]
1061 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
1062 fn borrow_mut(&mut self) -> &mut T {
1067 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1068 impl<T: ?Sized> AsRef<T> for Box<T> {
1069 fn as_ref(&self) -> &T {
1074 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1075 impl<T: ?Sized> AsMut<T> for Box<T> {
1076 fn as_mut(&mut self) -> &mut T {
1083 * We could have chosen not to add this impl, and instead have written a
1084 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1085 * because Box<T> implements Unpin even when T does not, as a result of
1088 * We chose this API instead of the alternative for a few reasons:
1089 * - Logically, it is helpful to understand pinning in regard to the
1090 * memory region being pointed to. For this reason none of the
1091 * standard library pointer types support projecting through a pin
1092 * (Box<T> is the only pointer type in std for which this would be
1094 * - It is in practice very useful to have Box<T> be unconditionally
1095 * Unpin because of trait objects, for which the structural auto
1096 * trait functionality does not apply (e.g., Box<dyn Foo> would
1097 * otherwise not be Unpin).
1099 * Another type with the same semantics as Box but only a conditional
1100 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1101 * could have a method to project a Pin<T> from it.
1103 #[stable(feature = "pin", since = "1.33.0")]
1104 impl<T: ?Sized> Unpin for Box<T> {}
1106 #[unstable(feature = "generator_trait", issue = "43122")]
1107 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
1108 type Yield = G::Yield;
1109 type Return = G::Return;
1111 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
1112 G::resume(Pin::new(&mut *self))
1116 #[unstable(feature = "generator_trait", issue = "43122")]
1117 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
1118 type Yield = G::Yield;
1119 type Return = G::Return;
1121 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
1122 G::resume((*self).as_mut())
1126 #[stable(feature = "futures_api", since = "1.36.0")]
1127 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
1128 type Output = F::Output;
1130 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1131 F::poll(Pin::new(&mut *self), cx)