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 //! For zero-sized values, the `Box` pointer still has to be [valid] for reads
66 //! and writes and sufficiently aligned. In particular, casting any aligned
67 //! non-zero integer literal to a raw pointer produces a valid pointer, but a
68 //! pointer pointing into previously allocated memory that since got freed is
69 //! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
70 //! be used is to use [`ptr::NonNull::dangling`].
72 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
73 //! as a single pointer and is also ABI-compatible with C pointers
74 //! (i.e. the C type `T*`). This means that if you have extern "C"
75 //! Rust functions that will be called from C, you can define those
76 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
77 //! type on the C side. As an example, consider this C header which
78 //! declares functions that create and destroy some kind of `Foo`
84 //! /* Returns ownership to the caller */
85 //! struct Foo* foo_new(void);
87 //! /* Takes ownership from the caller; no-op when invoked with NULL */
88 //! void foo_delete(struct Foo*);
91 //! These two functions might be implemented in Rust as follows. Here, the
92 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
93 //! the ownership constraints. Note also that the nullable argument to
94 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
102 //! pub extern "C" fn foo_new() -> Box<Foo> {
107 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
110 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
111 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
112 //! and expect things to work. `Box<T>` values will always be fully aligned,
113 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
114 //! free the value with the global allocator. In general, the best practice
115 //! is to only use `Box<T>` for pointers that originated from the global
118 //! **Important.** At least at present, you should avoid using
119 //! `Box<T>` types for functions that are defined in C but invoked
120 //! from Rust. In those cases, you should directly mirror the C types
121 //! as closely as possible. Using types like `Box<T>` where the C
122 //! definition is just using `T*` can lead to undefined behavior, as
123 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
125 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
126 //! [dereferencing]: core::ops::Deref
127 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
128 //! [`Global`]: crate::alloc::Global
129 //! [`Layout`]: crate::alloc::Layout
130 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
131 //! [valid]: ptr#safety
133 #![stable(feature = "rust1", since = "1.0.0")]
137 use core::cmp::Ordering;
138 use core::convert::{From, TryFrom};
140 use core::future::Future;
141 use core::hash::{Hash, Hasher};
142 use core::iter::{FromIterator, FusedIterator, Iterator};
143 use core::marker::{Unpin, Unsize};
146 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
149 use core::ptr::{self, Unique};
150 use core::stream::Stream;
151 use core::task::{Context, Poll};
153 use crate::alloc::{handle_alloc_error, AllocError, Allocator, Global, Layout, WriteCloneIntoRaw};
154 use crate::borrow::Cow;
155 use crate::raw_vec::RawVec;
156 use crate::str::from_boxed_utf8_unchecked;
159 /// A pointer type for heap allocation.
161 /// See the [module-level documentation](../../std/boxed/index.html) for more.
162 #[lang = "owned_box"]
164 #[stable(feature = "rust1", since = "1.0.0")]
167 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
171 /// Allocates memory on the heap and then places `x` into it.
173 /// This doesn't actually allocate if `T` is zero-sized.
178 /// let five = Box::new(5);
181 #[doc(alias = "alloc")]
182 #[doc(alias = "malloc")]
183 #[stable(feature = "rust1", since = "1.0.0")]
184 pub fn new(x: T) -> Self {
188 /// Constructs a new box with uninitialized contents.
193 /// #![feature(new_uninit)]
195 /// let mut five = Box::<u32>::new_uninit();
197 /// let five = unsafe {
198 /// // Deferred initialization:
199 /// five.as_mut_ptr().write(5);
201 /// five.assume_init()
204 /// assert_eq!(*five, 5)
206 #[unstable(feature = "new_uninit", issue = "63291")]
208 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
209 Self::new_uninit_in(Global)
212 /// Constructs a new `Box` with uninitialized contents, with the memory
213 /// being filled with `0` bytes.
215 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
221 /// #![feature(new_uninit)]
223 /// let zero = Box::<u32>::new_zeroed();
224 /// let zero = unsafe { zero.assume_init() };
226 /// assert_eq!(*zero, 0)
229 /// [zeroed]: mem::MaybeUninit::zeroed
231 #[doc(alias = "calloc")]
232 #[unstable(feature = "new_uninit", issue = "63291")]
233 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
234 Self::new_zeroed_in(Global)
237 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
238 /// `x` will be pinned in memory and unable to be moved.
239 #[stable(feature = "pin", since = "1.33.0")]
241 pub fn pin(x: T) -> Pin<Box<T>> {
245 /// Allocates memory on the heap then places `x` into it,
246 /// returning an error if the allocation fails
248 /// This doesn't actually allocate if `T` is zero-sized.
253 /// #![feature(allocator_api)]
255 /// let five = Box::try_new(5)?;
256 /// # Ok::<(), std::alloc::AllocError>(())
258 #[unstable(feature = "allocator_api", issue = "32838")]
260 pub fn try_new(x: T) -> Result<Self, AllocError> {
261 Self::try_new_in(x, Global)
264 /// Constructs a new box with uninitialized contents on the heap,
265 /// returning an error if the allocation fails
270 /// #![feature(allocator_api, new_uninit)]
272 /// let mut five = Box::<u32>::try_new_uninit()?;
274 /// let five = unsafe {
275 /// // Deferred initialization:
276 /// five.as_mut_ptr().write(5);
278 /// five.assume_init()
281 /// assert_eq!(*five, 5);
282 /// # Ok::<(), std::alloc::AllocError>(())
284 #[unstable(feature = "allocator_api", issue = "32838")]
285 // #[unstable(feature = "new_uninit", issue = "63291")]
287 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
288 Box::try_new_uninit_in(Global)
291 /// Constructs a new `Box` with uninitialized contents, with the memory
292 /// being filled with `0` bytes on the heap
294 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
300 /// #![feature(allocator_api, new_uninit)]
302 /// let zero = Box::<u32>::try_new_zeroed()?;
303 /// let zero = unsafe { zero.assume_init() };
305 /// assert_eq!(*zero, 0);
306 /// # Ok::<(), std::alloc::AllocError>(())
309 /// [zeroed]: mem::MaybeUninit::zeroed
310 #[unstable(feature = "allocator_api", issue = "32838")]
311 // #[unstable(feature = "new_uninit", issue = "63291")]
313 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
314 Box::try_new_zeroed_in(Global)
318 impl<T, A: Allocator> Box<T, A> {
319 /// Allocates memory in the given allocator then places `x` into it.
321 /// This doesn't actually allocate if `T` is zero-sized.
326 /// #![feature(allocator_api)]
328 /// use std::alloc::System;
330 /// let five = Box::new_in(5, System);
332 #[unstable(feature = "allocator_api", issue = "32838")]
334 pub fn new_in(x: T, alloc: A) -> Self {
335 let mut boxed = Self::new_uninit_in(alloc);
337 boxed.as_mut_ptr().write(x);
342 /// Allocates memory in the given allocator then places `x` into it,
343 /// returning an error if the allocation fails
345 /// This doesn't actually allocate if `T` is zero-sized.
350 /// #![feature(allocator_api)]
352 /// use std::alloc::System;
354 /// let five = Box::try_new_in(5, System)?;
355 /// # Ok::<(), std::alloc::AllocError>(())
357 #[unstable(feature = "allocator_api", issue = "32838")]
359 pub fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError> {
360 let mut boxed = Self::try_new_uninit_in(alloc)?;
362 boxed.as_mut_ptr().write(x);
363 Ok(boxed.assume_init())
367 /// Constructs a new box with uninitialized contents in the provided allocator.
372 /// #![feature(allocator_api, new_uninit)]
374 /// use std::alloc::System;
376 /// let mut five = Box::<u32, _>::new_uninit_in(System);
378 /// let five = unsafe {
379 /// // Deferred initialization:
380 /// five.as_mut_ptr().write(5);
382 /// five.assume_init()
385 /// assert_eq!(*five, 5)
387 #[unstable(feature = "allocator_api", issue = "32838")]
388 // #[unstable(feature = "new_uninit", issue = "63291")]
389 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
390 let layout = Layout::new::<mem::MaybeUninit<T>>();
391 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
392 // That would make code size bigger.
393 match Box::try_new_uninit_in(alloc) {
395 Err(_) => handle_alloc_error(layout),
399 /// Constructs a new box with uninitialized contents in the provided allocator,
400 /// returning an error if the allocation fails
405 /// #![feature(allocator_api, new_uninit)]
407 /// use std::alloc::System;
409 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
411 /// let five = unsafe {
412 /// // Deferred initialization:
413 /// five.as_mut_ptr().write(5);
415 /// five.assume_init()
418 /// assert_eq!(*five, 5);
419 /// # Ok::<(), std::alloc::AllocError>(())
421 #[unstable(feature = "allocator_api", issue = "32838")]
422 // #[unstable(feature = "new_uninit", issue = "63291")]
423 pub fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> {
424 let layout = Layout::new::<mem::MaybeUninit<T>>();
425 let ptr = alloc.allocate(layout)?.cast();
426 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
429 /// Constructs a new `Box` with uninitialized contents, with the memory
430 /// being filled with `0` bytes in the provided allocator.
432 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
438 /// #![feature(allocator_api, new_uninit)]
440 /// use std::alloc::System;
442 /// let zero = Box::<u32, _>::new_zeroed_in(System);
443 /// let zero = unsafe { zero.assume_init() };
445 /// assert_eq!(*zero, 0)
448 /// [zeroed]: mem::MaybeUninit::zeroed
449 #[unstable(feature = "allocator_api", issue = "32838")]
450 // #[unstable(feature = "new_uninit", issue = "63291")]
451 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
452 let layout = Layout::new::<mem::MaybeUninit<T>>();
453 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
454 // That would make code size bigger.
455 match Box::try_new_zeroed_in(alloc) {
457 Err(_) => handle_alloc_error(layout),
461 /// Constructs a new `Box` with uninitialized contents, with the memory
462 /// being filled with `0` bytes in the provided allocator,
463 /// returning an error if the allocation fails,
465 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
471 /// #![feature(allocator_api, new_uninit)]
473 /// use std::alloc::System;
475 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
476 /// let zero = unsafe { zero.assume_init() };
478 /// assert_eq!(*zero, 0);
479 /// # Ok::<(), std::alloc::AllocError>(())
482 /// [zeroed]: mem::MaybeUninit::zeroed
483 #[unstable(feature = "allocator_api", issue = "32838")]
484 // #[unstable(feature = "new_uninit", issue = "63291")]
485 pub fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> {
486 let layout = Layout::new::<mem::MaybeUninit<T>>();
487 let ptr = alloc.allocate_zeroed(layout)?.cast();
488 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
491 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
492 /// `x` will be pinned in memory and unable to be moved.
493 #[unstable(feature = "allocator_api", issue = "32838")]
495 pub fn pin_in(x: T, alloc: A) -> Pin<Self>
499 Self::new_in(x, alloc).into()
502 /// Converts a `Box<T>` into a `Box<[T]>`
504 /// This conversion does not allocate on the heap and happens in place.
505 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
506 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
507 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
508 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
511 /// Consumes the `Box`, returning the wrapped value.
516 /// #![feature(box_into_inner)]
518 /// let c = Box::new(5);
520 /// assert_eq!(Box::into_inner(c), 5);
522 #[unstable(feature = "box_into_inner", issue = "80437")]
524 pub fn into_inner(boxed: Self) -> T {
530 /// Constructs a new boxed slice with uninitialized contents.
535 /// #![feature(new_uninit)]
537 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
539 /// let values = unsafe {
540 /// // Deferred initialization:
541 /// values[0].as_mut_ptr().write(1);
542 /// values[1].as_mut_ptr().write(2);
543 /// values[2].as_mut_ptr().write(3);
545 /// values.assume_init()
548 /// assert_eq!(*values, [1, 2, 3])
550 #[unstable(feature = "new_uninit", issue = "63291")]
551 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
552 unsafe { RawVec::with_capacity(len).into_box(len) }
555 /// Constructs a new boxed slice with uninitialized contents, with the memory
556 /// being filled with `0` bytes.
558 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
564 /// #![feature(new_uninit)]
566 /// let values = Box::<[u32]>::new_zeroed_slice(3);
567 /// let values = unsafe { values.assume_init() };
569 /// assert_eq!(*values, [0, 0, 0])
572 /// [zeroed]: mem::MaybeUninit::zeroed
573 #[unstable(feature = "new_uninit", issue = "63291")]
574 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
575 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
579 impl<T, A: Allocator> Box<[T], A> {
580 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
585 /// #![feature(allocator_api, new_uninit)]
587 /// use std::alloc::System;
589 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
591 /// let values = unsafe {
592 /// // Deferred initialization:
593 /// values[0].as_mut_ptr().write(1);
594 /// values[1].as_mut_ptr().write(2);
595 /// values[2].as_mut_ptr().write(3);
597 /// values.assume_init()
600 /// assert_eq!(*values, [1, 2, 3])
602 #[unstable(feature = "allocator_api", issue = "32838")]
603 // #[unstable(feature = "new_uninit", issue = "63291")]
604 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
605 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
608 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
609 /// with the memory being filled with `0` bytes.
611 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
617 /// #![feature(allocator_api, new_uninit)]
619 /// use std::alloc::System;
621 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
622 /// let values = unsafe { values.assume_init() };
624 /// assert_eq!(*values, [0, 0, 0])
627 /// [zeroed]: mem::MaybeUninit::zeroed
628 #[unstable(feature = "allocator_api", issue = "32838")]
629 // #[unstable(feature = "new_uninit", issue = "63291")]
630 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
631 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
635 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
636 /// Converts to `Box<T, A>`.
640 /// As with [`MaybeUninit::assume_init`],
641 /// it is up to the caller to guarantee that the value
642 /// really is in an initialized state.
643 /// Calling this when the content is not yet fully initialized
644 /// causes immediate undefined behavior.
646 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
651 /// #![feature(new_uninit)]
653 /// let mut five = Box::<u32>::new_uninit();
655 /// let five: Box<u32> = unsafe {
656 /// // Deferred initialization:
657 /// five.as_mut_ptr().write(5);
659 /// five.assume_init()
662 /// assert_eq!(*five, 5)
664 #[unstable(feature = "new_uninit", issue = "63291")]
666 pub unsafe fn assume_init(self) -> Box<T, A> {
667 let (raw, alloc) = Box::into_raw_with_allocator(self);
668 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
672 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
673 /// Converts to `Box<[T], A>`.
677 /// As with [`MaybeUninit::assume_init`],
678 /// it is up to the caller to guarantee that the values
679 /// really are in an initialized state.
680 /// Calling this when the content is not yet fully initialized
681 /// causes immediate undefined behavior.
683 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
688 /// #![feature(new_uninit)]
690 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
692 /// let values = unsafe {
693 /// // Deferred initialization:
694 /// values[0].as_mut_ptr().write(1);
695 /// values[1].as_mut_ptr().write(2);
696 /// values[2].as_mut_ptr().write(3);
698 /// values.assume_init()
701 /// assert_eq!(*values, [1, 2, 3])
703 #[unstable(feature = "new_uninit", issue = "63291")]
705 pub unsafe fn assume_init(self) -> Box<[T], A> {
706 let (raw, alloc) = Box::into_raw_with_allocator(self);
707 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
711 impl<T: ?Sized> Box<T> {
712 /// Constructs a box from a raw pointer.
714 /// After calling this function, the raw pointer is owned by the
715 /// resulting `Box`. Specifically, the `Box` destructor will call
716 /// the destructor of `T` and free the allocated memory. For this
717 /// to be safe, the memory must have been allocated in accordance
718 /// with the [memory layout] used by `Box` .
722 /// This function is unsafe because improper use may lead to
723 /// memory problems. For example, a double-free may occur if the
724 /// function is called twice on the same raw pointer.
726 /// The safety conditions are described in the [memory layout] section.
730 /// Recreate a `Box` which was previously converted to a raw pointer
731 /// using [`Box::into_raw`]:
733 /// let x = Box::new(5);
734 /// let ptr = Box::into_raw(x);
735 /// let x = unsafe { Box::from_raw(ptr) };
737 /// Manually create a `Box` from scratch by using the global allocator:
739 /// use std::alloc::{alloc, Layout};
742 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
743 /// // In general .write is required to avoid attempting to destruct
744 /// // the (uninitialized) previous contents of `ptr`, though for this
745 /// // simple example `*ptr = 5` would have worked as well.
747 /// let x = Box::from_raw(ptr);
751 /// [memory layout]: self#memory-layout
752 /// [`Layout`]: crate::Layout
753 #[stable(feature = "box_raw", since = "1.4.0")]
755 pub unsafe fn from_raw(raw: *mut T) -> Self {
756 unsafe { Self::from_raw_in(raw, Global) }
760 impl<T: ?Sized, A: Allocator> Box<T, A> {
761 /// Constructs a box from a raw pointer in the given allocator.
763 /// After calling this function, the raw pointer is owned by the
764 /// resulting `Box`. Specifically, the `Box` destructor will call
765 /// the destructor of `T` and free the allocated memory. For this
766 /// to be safe, the memory must have been allocated in accordance
767 /// with the [memory layout] used by `Box` .
771 /// This function is unsafe because improper use may lead to
772 /// memory problems. For example, a double-free may occur if the
773 /// function is called twice on the same raw pointer.
778 /// Recreate a `Box` which was previously converted to a raw pointer
779 /// using [`Box::into_raw_with_allocator`]:
781 /// #![feature(allocator_api)]
783 /// use std::alloc::System;
785 /// let x = Box::new_in(5, System);
786 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
787 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
789 /// Manually create a `Box` from scratch by using the system allocator:
791 /// #![feature(allocator_api, slice_ptr_get)]
793 /// use std::alloc::{Allocator, Layout, System};
796 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr();
797 /// // In general .write is required to avoid attempting to destruct
798 /// // the (uninitialized) previous contents of `ptr`, though for this
799 /// // simple example `*ptr = 5` would have worked as well.
801 /// let x = Box::from_raw_in(ptr, System);
803 /// # Ok::<(), std::alloc::AllocError>(())
806 /// [memory layout]: self#memory-layout
807 /// [`Layout`]: crate::Layout
808 #[unstable(feature = "allocator_api", issue = "32838")]
810 pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
811 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
814 /// Consumes the `Box`, returning a wrapped raw pointer.
816 /// The pointer will be properly aligned and non-null.
818 /// After calling this function, the caller is responsible for the
819 /// memory previously managed by the `Box`. In particular, the
820 /// caller should properly destroy `T` and release the memory, taking
821 /// into account the [memory layout] used by `Box`. The easiest way to
822 /// do this is to convert the raw pointer back into a `Box` with the
823 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
826 /// Note: this is an associated function, which means that you have
827 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
828 /// is so that there is no conflict with a method on the inner type.
831 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
832 /// for automatic cleanup:
834 /// let x = Box::new(String::from("Hello"));
835 /// let ptr = Box::into_raw(x);
836 /// let x = unsafe { Box::from_raw(ptr) };
838 /// Manual cleanup by explicitly running the destructor and deallocating
841 /// use std::alloc::{dealloc, Layout};
844 /// let x = Box::new(String::from("Hello"));
845 /// let p = Box::into_raw(x);
847 /// ptr::drop_in_place(p);
848 /// dealloc(p as *mut u8, Layout::new::<String>());
852 /// [memory layout]: self#memory-layout
853 #[stable(feature = "box_raw", since = "1.4.0")]
855 pub fn into_raw(b: Self) -> *mut T {
856 Self::into_raw_with_allocator(b).0
859 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
861 /// The pointer will be properly aligned and non-null.
863 /// After calling this function, the caller is responsible for the
864 /// memory previously managed by the `Box`. In particular, the
865 /// caller should properly destroy `T` and release the memory, taking
866 /// into account the [memory layout] used by `Box`. The easiest way to
867 /// do this is to convert the raw pointer back into a `Box` with the
868 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
871 /// Note: this is an associated function, which means that you have
872 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
873 /// is so that there is no conflict with a method on the inner type.
876 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
877 /// for automatic cleanup:
879 /// #![feature(allocator_api)]
881 /// use std::alloc::System;
883 /// let x = Box::new_in(String::from("Hello"), System);
884 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
885 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
887 /// Manual cleanup by explicitly running the destructor and deallocating
890 /// #![feature(allocator_api)]
892 /// use std::alloc::{Allocator, Layout, System};
893 /// use std::ptr::{self, NonNull};
895 /// let x = Box::new_in(String::from("Hello"), System);
896 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
898 /// ptr::drop_in_place(ptr);
899 /// let non_null = NonNull::new_unchecked(ptr);
900 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
904 /// [memory layout]: self#memory-layout
905 #[unstable(feature = "allocator_api", issue = "32838")]
907 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
908 let (leaked, alloc) = Box::into_unique(b);
909 (leaked.as_ptr(), alloc)
913 feature = "ptr_internals",
915 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
919 pub fn into_unique(b: Self) -> (Unique<T>, A) {
920 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
921 // raw pointer for the type system. Turning it directly into a raw pointer would not be
922 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
923 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
924 // behaves correctly.
925 let alloc = unsafe { ptr::read(&b.1) };
926 (Unique::from(Box::leak(b)), alloc)
929 /// Returns a reference to the underlying allocator.
931 /// Note: this is an associated function, which means that you have
932 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
933 /// is so that there is no conflict with a method on the inner type.
934 #[unstable(feature = "allocator_api", issue = "32838")]
936 pub fn allocator(b: &Self) -> &A {
940 /// Consumes and leaks the `Box`, returning a mutable reference,
941 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
942 /// `'a`. If the type has only static references, or none at all, then this
943 /// may be chosen to be `'static`.
945 /// This function is mainly useful for data that lives for the remainder of
946 /// the program's life. Dropping the returned reference will cause a memory
947 /// leak. If this is not acceptable, the reference should first be wrapped
948 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
949 /// then be dropped which will properly destroy `T` and release the
950 /// allocated memory.
952 /// Note: this is an associated function, which means that you have
953 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
954 /// is so that there is no conflict with a method on the inner type.
961 /// let x = Box::new(41);
962 /// let static_ref: &'static mut usize = Box::leak(x);
963 /// *static_ref += 1;
964 /// assert_eq!(*static_ref, 42);
970 /// let x = vec![1, 2, 3].into_boxed_slice();
971 /// let static_ref = Box::leak(x);
972 /// static_ref[0] = 4;
973 /// assert_eq!(*static_ref, [4, 2, 3]);
975 #[stable(feature = "box_leak", since = "1.26.0")]
977 pub fn leak<'a>(b: Self) -> &'a mut T
981 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
984 /// Converts a `Box<T>` into a `Pin<Box<T>>`
986 /// This conversion does not allocate on the heap and happens in place.
988 /// This is also available via [`From`].
989 #[unstable(feature = "box_into_pin", issue = "62370")]
990 pub fn into_pin(boxed: Self) -> Pin<Self>
994 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
995 // when `T: !Unpin`, so it's safe to pin it directly without any
996 // additional requirements.
997 unsafe { Pin::new_unchecked(boxed) }
1001 #[stable(feature = "rust1", since = "1.0.0")]
1002 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1003 fn drop(&mut self) {
1004 // FIXME: Do nothing, drop is currently performed by compiler.
1008 #[stable(feature = "rust1", since = "1.0.0")]
1009 impl<T: Default> Default for Box<T> {
1010 /// Creates a `Box<T>`, with the `Default` value for T.
1011 fn default() -> Self {
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 impl<T> Default for Box<[T]> {
1018 fn default() -> Self {
1019 Box::<[T; 0]>::new([])
1023 #[stable(feature = "default_box_extra", since = "1.17.0")]
1024 impl Default for Box<str> {
1025 fn default() -> Self {
1026 unsafe { from_boxed_utf8_unchecked(Default::default()) }
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1032 /// Returns a new box with a `clone()` of this box's contents.
1037 /// let x = Box::new(5);
1038 /// let y = x.clone();
1040 /// // The value is the same
1041 /// assert_eq!(x, y);
1043 /// // But they are unique objects
1044 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1047 fn clone(&self) -> Self {
1048 // Pre-allocate memory to allow writing the cloned value directly.
1049 let mut boxed = Self::new_uninit_in(self.1.clone());
1051 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1056 /// Copies `source`'s contents into `self` without creating a new allocation.
1061 /// let x = Box::new(5);
1062 /// let mut y = Box::new(10);
1063 /// let yp: *const i32 = &*y;
1065 /// y.clone_from(&x);
1067 /// // The value is the same
1068 /// assert_eq!(x, y);
1070 /// // And no allocation occurred
1071 /// assert_eq!(yp, &*y);
1074 fn clone_from(&mut self, source: &Self) {
1075 (**self).clone_from(&(**source));
1079 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1080 impl Clone for Box<str> {
1081 fn clone(&self) -> Self {
1082 // this makes a copy of the data
1083 let buf: Box<[u8]> = self.as_bytes().into();
1084 unsafe { from_boxed_utf8_unchecked(buf) }
1088 #[stable(feature = "rust1", since = "1.0.0")]
1089 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1091 fn eq(&self, other: &Self) -> bool {
1092 PartialEq::eq(&**self, &**other)
1095 fn ne(&self, other: &Self) -> bool {
1096 PartialEq::ne(&**self, &**other)
1099 #[stable(feature = "rust1", since = "1.0.0")]
1100 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1102 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1103 PartialOrd::partial_cmp(&**self, &**other)
1106 fn lt(&self, other: &Self) -> bool {
1107 PartialOrd::lt(&**self, &**other)
1110 fn le(&self, other: &Self) -> bool {
1111 PartialOrd::le(&**self, &**other)
1114 fn ge(&self, other: &Self) -> bool {
1115 PartialOrd::ge(&**self, &**other)
1118 fn gt(&self, other: &Self) -> bool {
1119 PartialOrd::gt(&**self, &**other)
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1125 fn cmp(&self, other: &Self) -> Ordering {
1126 Ord::cmp(&**self, &**other)
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1132 #[stable(feature = "rust1", since = "1.0.0")]
1133 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1134 fn hash<H: Hasher>(&self, state: &mut H) {
1135 (**self).hash(state);
1139 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1140 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1141 fn finish(&self) -> u64 {
1144 fn write(&mut self, bytes: &[u8]) {
1145 (**self).write(bytes)
1147 fn write_u8(&mut self, i: u8) {
1148 (**self).write_u8(i)
1150 fn write_u16(&mut self, i: u16) {
1151 (**self).write_u16(i)
1153 fn write_u32(&mut self, i: u32) {
1154 (**self).write_u32(i)
1156 fn write_u64(&mut self, i: u64) {
1157 (**self).write_u64(i)
1159 fn write_u128(&mut self, i: u128) {
1160 (**self).write_u128(i)
1162 fn write_usize(&mut self, i: usize) {
1163 (**self).write_usize(i)
1165 fn write_i8(&mut self, i: i8) {
1166 (**self).write_i8(i)
1168 fn write_i16(&mut self, i: i16) {
1169 (**self).write_i16(i)
1171 fn write_i32(&mut self, i: i32) {
1172 (**self).write_i32(i)
1174 fn write_i64(&mut self, i: i64) {
1175 (**self).write_i64(i)
1177 fn write_i128(&mut self, i: i128) {
1178 (**self).write_i128(i)
1180 fn write_isize(&mut self, i: isize) {
1181 (**self).write_isize(i)
1185 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1186 impl<T> From<T> for Box<T> {
1187 /// Converts a generic type `T` into a `Box<T>`
1189 /// The conversion allocates on the heap and moves `t`
1190 /// from the stack into it.
1195 /// let boxed = Box::new(5);
1197 /// assert_eq!(Box::from(x), boxed);
1199 fn from(t: T) -> Self {
1204 #[stable(feature = "pin", since = "1.33.0")]
1205 impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
1209 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1211 /// This conversion does not allocate on the heap and happens in place.
1212 fn from(boxed: Box<T, A>) -> Self {
1213 Box::into_pin(boxed)
1217 #[stable(feature = "box_from_slice", since = "1.17.0")]
1218 impl<T: Copy> From<&[T]> for Box<[T]> {
1219 /// Converts a `&[T]` into a `Box<[T]>`
1221 /// This conversion allocates on the heap
1222 /// and performs a copy of `slice`.
1226 /// // create a &[u8] which will be used to create a Box<[u8]>
1227 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1228 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1230 /// println!("{:?}", boxed_slice);
1232 fn from(slice: &[T]) -> Box<[T]> {
1233 let len = slice.len();
1234 let buf = RawVec::with_capacity(len);
1236 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1237 buf.into_box(slice.len()).assume_init()
1242 #[stable(feature = "box_from_cow", since = "1.45.0")]
1243 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1245 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1247 Cow::Borrowed(slice) => Box::from(slice),
1248 Cow::Owned(slice) => Box::from(slice),
1253 #[stable(feature = "box_from_slice", since = "1.17.0")]
1254 impl From<&str> for Box<str> {
1255 /// Converts a `&str` into a `Box<str>`
1257 /// This conversion allocates on the heap
1258 /// and performs a copy of `s`.
1262 /// let boxed: Box<str> = Box::from("hello");
1263 /// println!("{}", boxed);
1266 fn from(s: &str) -> Box<str> {
1267 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1271 #[stable(feature = "box_from_cow", since = "1.45.0")]
1272 impl From<Cow<'_, str>> for Box<str> {
1274 fn from(cow: Cow<'_, str>) -> Box<str> {
1276 Cow::Borrowed(s) => Box::from(s),
1277 Cow::Owned(s) => Box::from(s),
1282 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1283 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1284 /// Converts a `Box<str>` into a `Box<[u8]>`
1286 /// This conversion does not allocate on the heap and happens in place.
1290 /// // create a Box<str> which will be used to create a Box<[u8]>
1291 /// let boxed: Box<str> = Box::from("hello");
1292 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1294 /// // create a &[u8] which will be used to create a Box<[u8]>
1295 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1296 /// let boxed_slice = Box::from(slice);
1298 /// assert_eq!(boxed_slice, boxed_str);
1301 fn from(s: Box<str, A>) -> Self {
1302 let (raw, alloc) = Box::into_raw_with_allocator(s);
1303 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1307 #[stable(feature = "box_from_array", since = "1.45.0")]
1308 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1309 /// Converts a `[T; N]` into a `Box<[T]>`
1311 /// This conversion moves the array to newly heap-allocated memory.
1315 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1316 /// println!("{:?}", boxed);
1318 fn from(array: [T; N]) -> Box<[T]> {
1323 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1324 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1325 type Error = Box<[T]>;
1327 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1328 if boxed_slice.len() == N {
1329 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1336 impl<A: Allocator> Box<dyn Any, A> {
1338 #[stable(feature = "rust1", since = "1.0.0")]
1339 /// Attempt to downcast the box to a concrete type.
1344 /// use std::any::Any;
1346 /// fn print_if_string(value: Box<dyn Any>) {
1347 /// if let Ok(string) = value.downcast::<String>() {
1348 /// println!("String ({}): {}", string.len(), string);
1352 /// let my_string = "Hello World".to_string();
1353 /// print_if_string(Box::new(my_string));
1354 /// print_if_string(Box::new(0i8));
1356 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1359 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1360 Ok(Box::from_raw_in(raw as *mut T, alloc))
1368 impl<A: Allocator> Box<dyn Any + Send, A> {
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 /// Attempt to downcast the box to a concrete type.
1376 /// use std::any::Any;
1378 /// fn print_if_string(value: Box<dyn Any + Send>) {
1379 /// if let Ok(string) = value.downcast::<String>() {
1380 /// println!("String ({}): {}", string.len(), string);
1384 /// let my_string = "Hello World".to_string();
1385 /// print_if_string(Box::new(my_string));
1386 /// print_if_string(Box::new(0i8));
1388 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1391 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1392 Ok(Box::from_raw_in(raw as *mut T, alloc))
1400 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1402 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1403 /// Attempt to downcast the box to a concrete type.
1408 /// use std::any::Any;
1410 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1411 /// if let Ok(string) = value.downcast::<String>() {
1412 /// println!("String ({}): {}", string.len(), string);
1416 /// let my_string = "Hello World".to_string();
1417 /// print_if_string(Box::new(my_string));
1418 /// print_if_string(Box::new(0i8));
1420 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1423 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1424 Box::into_raw_with_allocator(self);
1425 Ok(Box::from_raw_in(raw as *mut T, alloc))
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1435 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1436 fmt::Display::fmt(&**self, f)
1440 #[stable(feature = "rust1", since = "1.0.0")]
1441 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1442 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1443 fmt::Debug::fmt(&**self, f)
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1449 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1450 // It's not possible to extract the inner Uniq directly from the Box,
1451 // instead we cast it to a *const which aliases the Unique
1452 let ptr: *const T = &**self;
1453 fmt::Pointer::fmt(&ptr, f)
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
1461 fn deref(&self) -> &T {
1466 #[stable(feature = "rust1", since = "1.0.0")]
1467 impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
1468 fn deref_mut(&mut self) -> &mut T {
1473 #[unstable(feature = "receiver_trait", issue = "none")]
1474 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1478 type Item = I::Item;
1479 fn next(&mut self) -> Option<I::Item> {
1482 fn size_hint(&self) -> (usize, Option<usize>) {
1483 (**self).size_hint()
1485 fn nth(&mut self, n: usize) -> Option<I::Item> {
1488 fn last(self) -> Option<I::Item> {
1495 fn last(self) -> Option<Self::Item>;
1498 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1499 type Item = I::Item;
1500 default fn last(self) -> Option<I::Item> {
1502 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1506 self.fold(None, some)
1510 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1511 /// instead of the default.
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1514 fn last(self) -> Option<I::Item> {
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1521 fn next_back(&mut self) -> Option<I::Item> {
1522 (**self).next_back()
1524 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1525 (**self).nth_back(n)
1528 #[stable(feature = "rust1", since = "1.0.0")]
1529 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1530 fn len(&self) -> usize {
1533 fn is_empty(&self) -> bool {
1538 #[stable(feature = "fused", since = "1.26.0")]
1539 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1541 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1542 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1543 type Output = <F as FnOnce<Args>>::Output;
1545 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1546 <F as FnOnce<Args>>::call_once(*self, args)
1550 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1551 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1552 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1553 <F as FnMut<Args>>::call_mut(self, args)
1557 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1558 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1559 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1560 <F as Fn<Args>>::call(self, args)
1564 #[unstable(feature = "coerce_unsized", issue = "27732")]
1565 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1567 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1568 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1570 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1571 impl<I> FromIterator<I> for Box<[I]> {
1572 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1573 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1577 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1578 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1579 fn clone(&self) -> Self {
1580 let alloc = Box::allocator(self).clone();
1581 self.to_vec_in(alloc).into_boxed_slice()
1584 fn clone_from(&mut self, other: &Self) {
1585 if self.len() == other.len() {
1586 self.clone_from_slice(&other);
1588 *self = other.clone();
1593 #[stable(feature = "box_borrow", since = "1.1.0")]
1594 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1595 fn borrow(&self) -> &T {
1600 #[stable(feature = "box_borrow", since = "1.1.0")]
1601 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1602 fn borrow_mut(&mut self) -> &mut T {
1607 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1608 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1609 fn as_ref(&self) -> &T {
1614 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1615 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1616 fn as_mut(&mut self) -> &mut T {
1623 * We could have chosen not to add this impl, and instead have written a
1624 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1625 * because Box<T> implements Unpin even when T does not, as a result of
1628 * We chose this API instead of the alternative for a few reasons:
1629 * - Logically, it is helpful to understand pinning in regard to the
1630 * memory region being pointed to. For this reason none of the
1631 * standard library pointer types support projecting through a pin
1632 * (Box<T> is the only pointer type in std for which this would be
1634 * - It is in practice very useful to have Box<T> be unconditionally
1635 * Unpin because of trait objects, for which the structural auto
1636 * trait functionality does not apply (e.g., Box<dyn Foo> would
1637 * otherwise not be Unpin).
1639 * Another type with the same semantics as Box but only a conditional
1640 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1641 * could have a method to project a Pin<T> from it.
1643 #[stable(feature = "pin", since = "1.33.0")]
1644 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
1646 #[unstable(feature = "generator_trait", issue = "43122")]
1647 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1651 type Yield = G::Yield;
1652 type Return = G::Return;
1654 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1655 G::resume(Pin::new(&mut *self), arg)
1659 #[unstable(feature = "generator_trait", issue = "43122")]
1660 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1664 type Yield = G::Yield;
1665 type Return = G::Return;
1667 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1668 G::resume((*self).as_mut(), arg)
1672 #[stable(feature = "futures_api", since = "1.36.0")]
1673 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
1677 type Output = F::Output;
1679 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1680 F::poll(Pin::new(&mut *self), cx)
1684 #[unstable(feature = "async_stream", issue = "79024")]
1685 impl<S: ?Sized + Stream + Unpin> Stream for Box<S> {
1686 type Item = S::Item;
1688 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1689 Pin::new(&mut **self).poll_next(cx)
1692 fn size_hint(&self) -> (usize, Option<usize>) {
1693 (**self).size_hint()