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 #[cfg(not(no_global_oom_handling))]
143 use core::iter::FromIterator;
144 use core::iter::{FusedIterator, Iterator};
145 use core::marker::{Unpin, Unsize};
148 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
151 use core::ptr::{self, Unique};
152 use core::stream::Stream;
153 use core::task::{Context, Poll};
155 #[cfg(not(no_global_oom_handling))]
156 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
157 use crate::alloc::{AllocError, Allocator, Global, Layout};
158 #[cfg(not(no_global_oom_handling))]
159 use crate::borrow::Cow;
160 use crate::raw_vec::RawVec;
161 #[cfg(not(no_global_oom_handling))]
162 use crate::str::from_boxed_utf8_unchecked;
163 #[cfg(not(no_global_oom_handling))]
166 /// A pointer type for heap allocation.
168 /// See the [module-level documentation](../../std/boxed/index.html) for more.
169 #[lang = "owned_box"]
171 #[stable(feature = "rust1", since = "1.0.0")]
172 // The declaration of the `Box` struct must be kept in sync with the
173 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
174 // on `box_free` for more details.
177 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
181 /// Allocates memory on the heap and then places `x` into it.
183 /// This doesn't actually allocate if `T` is zero-sized.
188 /// let five = Box::new(5);
190 #[cfg(not(no_global_oom_handling))]
192 #[stable(feature = "rust1", since = "1.0.0")]
194 pub fn new(x: T) -> Self {
198 /// Constructs a new box with uninitialized contents.
203 /// #![feature(new_uninit)]
205 /// let mut five = Box::<u32>::new_uninit();
207 /// let five = unsafe {
208 /// // Deferred initialization:
209 /// five.as_mut_ptr().write(5);
211 /// five.assume_init()
214 /// assert_eq!(*five, 5)
216 #[cfg(not(no_global_oom_handling))]
217 #[unstable(feature = "new_uninit", issue = "63291")]
220 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
221 Self::new_uninit_in(Global)
224 /// Constructs a new `Box` with uninitialized contents, with the memory
225 /// being filled with `0` bytes.
227 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
233 /// #![feature(new_uninit)]
235 /// let zero = Box::<u32>::new_zeroed();
236 /// let zero = unsafe { zero.assume_init() };
238 /// assert_eq!(*zero, 0)
241 /// [zeroed]: mem::MaybeUninit::zeroed
242 #[cfg(not(no_global_oom_handling))]
244 #[unstable(feature = "new_uninit", issue = "63291")]
246 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
247 Self::new_zeroed_in(Global)
250 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
251 /// `x` will be pinned in memory and unable to be moved.
252 #[cfg(not(no_global_oom_handling))]
253 #[stable(feature = "pin", since = "1.33.0")]
256 pub fn pin(x: T) -> Pin<Box<T>> {
260 /// Allocates memory on the heap then places `x` into it,
261 /// returning an error if the allocation fails
263 /// This doesn't actually allocate if `T` is zero-sized.
268 /// #![feature(allocator_api)]
270 /// let five = Box::try_new(5)?;
271 /// # Ok::<(), std::alloc::AllocError>(())
273 #[unstable(feature = "allocator_api", issue = "32838")]
275 pub fn try_new(x: T) -> Result<Self, AllocError> {
276 Self::try_new_in(x, Global)
279 /// Constructs a new box with uninitialized contents on the heap,
280 /// returning an error if the allocation fails
285 /// #![feature(allocator_api, new_uninit)]
287 /// let mut five = Box::<u32>::try_new_uninit()?;
289 /// let five = unsafe {
290 /// // Deferred initialization:
291 /// five.as_mut_ptr().write(5);
293 /// five.assume_init()
296 /// assert_eq!(*five, 5);
297 /// # Ok::<(), std::alloc::AllocError>(())
299 #[unstable(feature = "allocator_api", issue = "32838")]
300 // #[unstable(feature = "new_uninit", issue = "63291")]
302 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
303 Box::try_new_uninit_in(Global)
306 /// Constructs a new `Box` with uninitialized contents, with the memory
307 /// being filled with `0` bytes on the heap
309 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
315 /// #![feature(allocator_api, new_uninit)]
317 /// let zero = Box::<u32>::try_new_zeroed()?;
318 /// let zero = unsafe { zero.assume_init() };
320 /// assert_eq!(*zero, 0);
321 /// # Ok::<(), std::alloc::AllocError>(())
324 /// [zeroed]: mem::MaybeUninit::zeroed
325 #[unstable(feature = "allocator_api", issue = "32838")]
326 // #[unstable(feature = "new_uninit", issue = "63291")]
328 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
329 Box::try_new_zeroed_in(Global)
333 impl<T, A: Allocator> Box<T, A> {
334 /// Allocates memory in the given allocator then places `x` into it.
336 /// This doesn't actually allocate if `T` is zero-sized.
341 /// #![feature(allocator_api)]
343 /// use std::alloc::System;
345 /// let five = Box::new_in(5, System);
347 #[cfg(not(no_global_oom_handling))]
348 #[unstable(feature = "allocator_api", issue = "32838")]
351 pub fn new_in(x: T, alloc: A) -> Self {
352 let mut boxed = Self::new_uninit_in(alloc);
354 boxed.as_mut_ptr().write(x);
359 /// Allocates memory in the given allocator then places `x` into it,
360 /// returning an error if the allocation fails
362 /// This doesn't actually allocate if `T` is zero-sized.
367 /// #![feature(allocator_api)]
369 /// use std::alloc::System;
371 /// let five = Box::try_new_in(5, System)?;
372 /// # Ok::<(), std::alloc::AllocError>(())
374 #[unstable(feature = "allocator_api", issue = "32838")]
376 pub fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError> {
377 let mut boxed = Self::try_new_uninit_in(alloc)?;
379 boxed.as_mut_ptr().write(x);
380 Ok(boxed.assume_init())
384 /// Constructs a new box with uninitialized contents in the provided allocator.
389 /// #![feature(allocator_api, new_uninit)]
391 /// use std::alloc::System;
393 /// let mut five = Box::<u32, _>::new_uninit_in(System);
395 /// let five = unsafe {
396 /// // Deferred initialization:
397 /// five.as_mut_ptr().write(5);
399 /// five.assume_init()
402 /// assert_eq!(*five, 5)
404 #[unstable(feature = "allocator_api", issue = "32838")]
405 #[cfg(not(no_global_oom_handling))]
407 // #[unstable(feature = "new_uninit", issue = "63291")]
408 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
409 let layout = Layout::new::<mem::MaybeUninit<T>>();
410 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
411 // That would make code size bigger.
412 match Box::try_new_uninit_in(alloc) {
414 Err(_) => handle_alloc_error(layout),
418 /// Constructs a new box with uninitialized contents in the provided allocator,
419 /// returning an error if the allocation fails
424 /// #![feature(allocator_api, new_uninit)]
426 /// use std::alloc::System;
428 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
430 /// let five = unsafe {
431 /// // Deferred initialization:
432 /// five.as_mut_ptr().write(5);
434 /// five.assume_init()
437 /// assert_eq!(*five, 5);
438 /// # Ok::<(), std::alloc::AllocError>(())
440 #[unstable(feature = "allocator_api", issue = "32838")]
441 // #[unstable(feature = "new_uninit", issue = "63291")]
442 pub fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> {
443 let layout = Layout::new::<mem::MaybeUninit<T>>();
444 let ptr = alloc.allocate(layout)?.cast();
445 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
448 /// Constructs a new `Box` with uninitialized contents, with the memory
449 /// being filled with `0` bytes in the provided allocator.
451 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
457 /// #![feature(allocator_api, new_uninit)]
459 /// use std::alloc::System;
461 /// let zero = Box::<u32, _>::new_zeroed_in(System);
462 /// let zero = unsafe { zero.assume_init() };
464 /// assert_eq!(*zero, 0)
467 /// [zeroed]: mem::MaybeUninit::zeroed
468 #[unstable(feature = "allocator_api", issue = "32838")]
469 #[cfg(not(no_global_oom_handling))]
470 // #[unstable(feature = "new_uninit", issue = "63291")]
472 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
473 let layout = Layout::new::<mem::MaybeUninit<T>>();
474 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
475 // That would make code size bigger.
476 match Box::try_new_zeroed_in(alloc) {
478 Err(_) => handle_alloc_error(layout),
482 /// Constructs a new `Box` with uninitialized contents, with the memory
483 /// being filled with `0` bytes in the provided allocator,
484 /// returning an error if the allocation fails,
486 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
492 /// #![feature(allocator_api, new_uninit)]
494 /// use std::alloc::System;
496 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
497 /// let zero = unsafe { zero.assume_init() };
499 /// assert_eq!(*zero, 0);
500 /// # Ok::<(), std::alloc::AllocError>(())
503 /// [zeroed]: mem::MaybeUninit::zeroed
504 #[unstable(feature = "allocator_api", issue = "32838")]
505 // #[unstable(feature = "new_uninit", issue = "63291")]
506 pub fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> {
507 let layout = Layout::new::<mem::MaybeUninit<T>>();
508 let ptr = alloc.allocate_zeroed(layout)?.cast();
509 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
512 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
513 /// `x` will be pinned in memory and unable to be moved.
514 #[cfg(not(no_global_oom_handling))]
515 #[unstable(feature = "allocator_api", issue = "32838")]
518 pub fn pin_in(x: T, alloc: A) -> Pin<Self>
522 Self::new_in(x, alloc).into()
525 /// Converts a `Box<T>` into a `Box<[T]>`
527 /// This conversion does not allocate on the heap and happens in place.
528 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
529 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
530 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
531 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
534 /// Consumes the `Box`, returning the wrapped value.
539 /// #![feature(box_into_inner)]
541 /// let c = Box::new(5);
543 /// assert_eq!(Box::into_inner(c), 5);
545 #[unstable(feature = "box_into_inner", issue = "80437")]
547 pub fn into_inner(boxed: Self) -> T {
553 /// Constructs a new boxed slice with uninitialized contents.
558 /// #![feature(new_uninit)]
560 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
562 /// let values = unsafe {
563 /// // Deferred initialization:
564 /// values[0].as_mut_ptr().write(1);
565 /// values[1].as_mut_ptr().write(2);
566 /// values[2].as_mut_ptr().write(3);
568 /// values.assume_init()
571 /// assert_eq!(*values, [1, 2, 3])
573 #[cfg(not(no_global_oom_handling))]
574 #[unstable(feature = "new_uninit", issue = "63291")]
576 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
577 unsafe { RawVec::with_capacity(len).into_box(len) }
580 /// Constructs a new boxed slice with uninitialized contents, with the memory
581 /// being filled with `0` bytes.
583 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
589 /// #![feature(new_uninit)]
591 /// let values = Box::<[u32]>::new_zeroed_slice(3);
592 /// let values = unsafe { values.assume_init() };
594 /// assert_eq!(*values, [0, 0, 0])
597 /// [zeroed]: mem::MaybeUninit::zeroed
598 #[cfg(not(no_global_oom_handling))]
599 #[unstable(feature = "new_uninit", issue = "63291")]
601 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
602 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
605 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
606 /// the allocation fails
611 /// #![feature(allocator_api, new_uninit)]
613 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
614 /// let values = unsafe {
615 /// // Deferred initialization:
616 /// values[0].as_mut_ptr().write(1);
617 /// values[1].as_mut_ptr().write(2);
618 /// values[2].as_mut_ptr().write(3);
619 /// values.assume_init()
622 /// assert_eq!(*values, [1, 2, 3]);
623 /// # Ok::<(), std::alloc::AllocError>(())
625 #[unstable(feature = "allocator_api", issue = "32838")]
627 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
629 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
631 Err(_) => return Err(AllocError),
633 let ptr = Global.allocate(layout)?;
634 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
638 /// Constructs a new boxed slice with uninitialized contents, with the memory
639 /// being filled with `0` bytes. Returns an error if the allocation fails
641 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
647 /// #![feature(allocator_api, new_uninit)]
649 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
650 /// let values = unsafe { values.assume_init() };
652 /// assert_eq!(*values, [0, 0, 0]);
653 /// # Ok::<(), std::alloc::AllocError>(())
656 /// [zeroed]: mem::MaybeUninit::zeroed
657 #[unstable(feature = "allocator_api", issue = "32838")]
659 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
661 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
663 Err(_) => return Err(AllocError),
665 let ptr = Global.allocate_zeroed(layout)?;
666 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
671 impl<T, A: Allocator> Box<[T], A> {
672 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
677 /// #![feature(allocator_api, new_uninit)]
679 /// use std::alloc::System;
681 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
683 /// let values = unsafe {
684 /// // Deferred initialization:
685 /// values[0].as_mut_ptr().write(1);
686 /// values[1].as_mut_ptr().write(2);
687 /// values[2].as_mut_ptr().write(3);
689 /// values.assume_init()
692 /// assert_eq!(*values, [1, 2, 3])
694 #[cfg(not(no_global_oom_handling))]
695 #[unstable(feature = "allocator_api", issue = "32838")]
696 // #[unstable(feature = "new_uninit", issue = "63291")]
698 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
699 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
702 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
703 /// with the memory being filled with `0` bytes.
705 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
711 /// #![feature(allocator_api, new_uninit)]
713 /// use std::alloc::System;
715 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
716 /// let values = unsafe { values.assume_init() };
718 /// assert_eq!(*values, [0, 0, 0])
721 /// [zeroed]: mem::MaybeUninit::zeroed
722 #[cfg(not(no_global_oom_handling))]
723 #[unstable(feature = "allocator_api", issue = "32838")]
724 // #[unstable(feature = "new_uninit", issue = "63291")]
726 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
727 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
731 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
732 /// Converts to `Box<T, A>`.
736 /// As with [`MaybeUninit::assume_init`],
737 /// it is up to the caller to guarantee that the value
738 /// really is in an initialized state.
739 /// Calling this when the content is not yet fully initialized
740 /// causes immediate undefined behavior.
742 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
747 /// #![feature(new_uninit)]
749 /// let mut five = Box::<u32>::new_uninit();
751 /// let five: Box<u32> = unsafe {
752 /// // Deferred initialization:
753 /// five.as_mut_ptr().write(5);
755 /// five.assume_init()
758 /// assert_eq!(*five, 5)
760 #[unstable(feature = "new_uninit", issue = "63291")]
762 pub unsafe fn assume_init(self) -> Box<T, A> {
763 let (raw, alloc) = Box::into_raw_with_allocator(self);
764 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
767 /// Writes the value and converts to `Box<T, A>`.
769 /// This method converts the box similarly to [`Box::assume_init`] but
770 /// writes `value` into it before conversion thus guaranteeing safety.
771 /// In some scenarios use of this method may improve performance because
772 /// the compiler may be able to optimize copying from stack.
777 /// #![feature(new_uninit)]
779 /// let big_box = Box::<[usize; 1024]>::new_uninit();
781 /// let mut array = [0; 1024];
782 /// for (i, place) in array.iter_mut().enumerate() {
786 /// // The optimizer may be able to elide this copy, so previous code writes
787 /// // to heap directly.
788 /// let big_box = Box::write(big_box, array);
790 /// for (i, x) in big_box.iter().enumerate() {
791 /// assert_eq!(*x, i);
794 #[unstable(feature = "new_uninit", issue = "63291")]
796 pub fn write(mut boxed: Self, value: T) -> Box<T, A> {
798 (*boxed).write(value);
804 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
805 /// Converts to `Box<[T], A>`.
809 /// As with [`MaybeUninit::assume_init`],
810 /// it is up to the caller to guarantee that the values
811 /// really are in an initialized state.
812 /// Calling this when the content is not yet fully initialized
813 /// causes immediate undefined behavior.
815 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
820 /// #![feature(new_uninit)]
822 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
824 /// let values = unsafe {
825 /// // Deferred initialization:
826 /// values[0].as_mut_ptr().write(1);
827 /// values[1].as_mut_ptr().write(2);
828 /// values[2].as_mut_ptr().write(3);
830 /// values.assume_init()
833 /// assert_eq!(*values, [1, 2, 3])
835 #[unstable(feature = "new_uninit", issue = "63291")]
837 pub unsafe fn assume_init(self) -> Box<[T], A> {
838 let (raw, alloc) = Box::into_raw_with_allocator(self);
839 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
843 impl<T: ?Sized> Box<T> {
844 /// Constructs a box from a raw pointer.
846 /// After calling this function, the raw pointer is owned by the
847 /// resulting `Box`. Specifically, the `Box` destructor will call
848 /// the destructor of `T` and free the allocated memory. For this
849 /// to be safe, the memory must have been allocated in accordance
850 /// with the [memory layout] used by `Box` .
854 /// This function is unsafe because improper use may lead to
855 /// memory problems. For example, a double-free may occur if the
856 /// function is called twice on the same raw pointer.
858 /// The safety conditions are described in the [memory layout] section.
862 /// Recreate a `Box` which was previously converted to a raw pointer
863 /// using [`Box::into_raw`]:
865 /// let x = Box::new(5);
866 /// let ptr = Box::into_raw(x);
867 /// let x = unsafe { Box::from_raw(ptr) };
869 /// Manually create a `Box` from scratch by using the global allocator:
871 /// use std::alloc::{alloc, Layout};
874 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
875 /// // In general .write is required to avoid attempting to destruct
876 /// // the (uninitialized) previous contents of `ptr`, though for this
877 /// // simple example `*ptr = 5` would have worked as well.
879 /// let x = Box::from_raw(ptr);
883 /// [memory layout]: self#memory-layout
884 /// [`Layout`]: crate::Layout
885 #[stable(feature = "box_raw", since = "1.4.0")]
887 pub unsafe fn from_raw(raw: *mut T) -> Self {
888 unsafe { Self::from_raw_in(raw, Global) }
892 impl<T: ?Sized, A: Allocator> Box<T, A> {
893 /// Constructs a box from a raw pointer in the given allocator.
895 /// After calling this function, the raw pointer is owned by the
896 /// resulting `Box`. Specifically, the `Box` destructor will call
897 /// the destructor of `T` and free the allocated memory. For this
898 /// to be safe, the memory must have been allocated in accordance
899 /// with the [memory layout] used by `Box` .
903 /// This function is unsafe because improper use may lead to
904 /// memory problems. For example, a double-free may occur if the
905 /// function is called twice on the same raw pointer.
910 /// Recreate a `Box` which was previously converted to a raw pointer
911 /// using [`Box::into_raw_with_allocator`]:
913 /// #![feature(allocator_api)]
915 /// use std::alloc::System;
917 /// let x = Box::new_in(5, System);
918 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
919 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
921 /// Manually create a `Box` from scratch by using the system allocator:
923 /// #![feature(allocator_api, slice_ptr_get)]
925 /// use std::alloc::{Allocator, Layout, System};
928 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
929 /// // In general .write is required to avoid attempting to destruct
930 /// // the (uninitialized) previous contents of `ptr`, though for this
931 /// // simple example `*ptr = 5` would have worked as well.
933 /// let x = Box::from_raw_in(ptr, System);
935 /// # Ok::<(), std::alloc::AllocError>(())
938 /// [memory layout]: self#memory-layout
939 /// [`Layout`]: crate::Layout
940 #[unstable(feature = "allocator_api", issue = "32838")]
942 pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
943 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
946 /// Consumes the `Box`, returning a wrapped raw pointer.
948 /// The pointer will be properly aligned and non-null.
950 /// After calling this function, the caller is responsible for the
951 /// memory previously managed by the `Box`. In particular, the
952 /// caller should properly destroy `T` and release the memory, taking
953 /// into account the [memory layout] used by `Box`. The easiest way to
954 /// do this is to convert the raw pointer back into a `Box` with the
955 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
958 /// Note: this is an associated function, which means that you have
959 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
960 /// is so that there is no conflict with a method on the inner type.
963 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
964 /// for automatic cleanup:
966 /// let x = Box::new(String::from("Hello"));
967 /// let ptr = Box::into_raw(x);
968 /// let x = unsafe { Box::from_raw(ptr) };
970 /// Manual cleanup by explicitly running the destructor and deallocating
973 /// use std::alloc::{dealloc, Layout};
976 /// let x = Box::new(String::from("Hello"));
977 /// let p = Box::into_raw(x);
979 /// ptr::drop_in_place(p);
980 /// dealloc(p as *mut u8, Layout::new::<String>());
984 /// [memory layout]: self#memory-layout
985 #[stable(feature = "box_raw", since = "1.4.0")]
987 pub fn into_raw(b: Self) -> *mut T {
988 Self::into_raw_with_allocator(b).0
991 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
993 /// The pointer will be properly aligned and non-null.
995 /// After calling this function, the caller is responsible for the
996 /// memory previously managed by the `Box`. In particular, the
997 /// caller should properly destroy `T` and release the memory, taking
998 /// into account the [memory layout] used by `Box`. The easiest way to
999 /// do this is to convert the raw pointer back into a `Box` with the
1000 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1003 /// Note: this is an associated function, which means that you have
1004 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1005 /// is so that there is no conflict with a method on the inner type.
1008 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1009 /// for automatic cleanup:
1011 /// #![feature(allocator_api)]
1013 /// use std::alloc::System;
1015 /// let x = Box::new_in(String::from("Hello"), System);
1016 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1017 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1019 /// Manual cleanup by explicitly running the destructor and deallocating
1022 /// #![feature(allocator_api)]
1024 /// use std::alloc::{Allocator, Layout, System};
1025 /// use std::ptr::{self, NonNull};
1027 /// let x = Box::new_in(String::from("Hello"), System);
1028 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1030 /// ptr::drop_in_place(ptr);
1031 /// let non_null = NonNull::new_unchecked(ptr);
1032 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1036 /// [memory layout]: self#memory-layout
1037 #[unstable(feature = "allocator_api", issue = "32838")]
1039 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1040 let (leaked, alloc) = Box::into_unique(b);
1041 (leaked.as_ptr(), alloc)
1045 feature = "ptr_internals",
1047 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1051 pub fn into_unique(b: Self) -> (Unique<T>, A) {
1052 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1053 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1054 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1055 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1056 // behaves correctly.
1057 let alloc = unsafe { ptr::read(&b.1) };
1058 (Unique::from(Box::leak(b)), alloc)
1061 /// Returns a reference to the underlying allocator.
1063 /// Note: this is an associated function, which means that you have
1064 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1065 /// is so that there is no conflict with a method on the inner type.
1066 #[unstable(feature = "allocator_api", issue = "32838")]
1068 pub fn allocator(b: &Self) -> &A {
1072 /// Consumes and leaks the `Box`, returning a mutable reference,
1073 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1074 /// `'a`. If the type has only static references, or none at all, then this
1075 /// may be chosen to be `'static`.
1077 /// This function is mainly useful for data that lives for the remainder of
1078 /// the program's life. Dropping the returned reference will cause a memory
1079 /// leak. If this is not acceptable, the reference should first be wrapped
1080 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1081 /// then be dropped which will properly destroy `T` and release the
1082 /// allocated memory.
1084 /// Note: this is an associated function, which means that you have
1085 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1086 /// is so that there is no conflict with a method on the inner type.
1093 /// let x = Box::new(41);
1094 /// let static_ref: &'static mut usize = Box::leak(x);
1095 /// *static_ref += 1;
1096 /// assert_eq!(*static_ref, 42);
1102 /// let x = vec![1, 2, 3].into_boxed_slice();
1103 /// let static_ref = Box::leak(x);
1104 /// static_ref[0] = 4;
1105 /// assert_eq!(*static_ref, [4, 2, 3]);
1107 #[stable(feature = "box_leak", since = "1.26.0")]
1109 pub fn leak<'a>(b: Self) -> &'a mut T
1113 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1116 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1118 /// This conversion does not allocate on the heap and happens in place.
1120 /// This is also available via [`From`].
1121 #[unstable(feature = "box_into_pin", issue = "62370")]
1122 pub fn into_pin(boxed: Self) -> Pin<Self>
1126 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1127 // when `T: !Unpin`, so it's safe to pin it directly without any
1128 // additional requirements.
1129 unsafe { Pin::new_unchecked(boxed) }
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1135 fn drop(&mut self) {
1136 // FIXME: Do nothing, drop is currently performed by compiler.
1140 #[cfg(not(no_global_oom_handling))]
1141 #[stable(feature = "rust1", since = "1.0.0")]
1142 impl<T: Default> Default for Box<T> {
1143 /// Creates a `Box<T>`, with the `Default` value for T.
1144 fn default() -> Self {
1149 #[cfg(not(no_global_oom_handling))]
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 impl<T> Default for Box<[T]> {
1152 fn default() -> Self {
1153 Box::<[T; 0]>::new([])
1157 #[cfg(not(no_global_oom_handling))]
1158 #[stable(feature = "default_box_extra", since = "1.17.0")]
1159 impl Default for Box<str> {
1160 fn default() -> Self {
1161 unsafe { from_boxed_utf8_unchecked(Default::default()) }
1165 #[cfg(not(no_global_oom_handling))]
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1168 /// Returns a new box with a `clone()` of this box's contents.
1173 /// let x = Box::new(5);
1174 /// let y = x.clone();
1176 /// // The value is the same
1177 /// assert_eq!(x, y);
1179 /// // But they are unique objects
1180 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1183 fn clone(&self) -> Self {
1184 // Pre-allocate memory to allow writing the cloned value directly.
1185 let mut boxed = Self::new_uninit_in(self.1.clone());
1187 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1192 /// Copies `source`'s contents into `self` without creating a new allocation.
1197 /// let x = Box::new(5);
1198 /// let mut y = Box::new(10);
1199 /// let yp: *const i32 = &*y;
1201 /// y.clone_from(&x);
1203 /// // The value is the same
1204 /// assert_eq!(x, y);
1206 /// // And no allocation occurred
1207 /// assert_eq!(yp, &*y);
1210 fn clone_from(&mut self, source: &Self) {
1211 (**self).clone_from(&(**source));
1215 #[cfg(not(no_global_oom_handling))]
1216 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1217 impl Clone for Box<str> {
1218 fn clone(&self) -> Self {
1219 // this makes a copy of the data
1220 let buf: Box<[u8]> = self.as_bytes().into();
1221 unsafe { from_boxed_utf8_unchecked(buf) }
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1228 fn eq(&self, other: &Self) -> bool {
1229 PartialEq::eq(&**self, &**other)
1232 fn ne(&self, other: &Self) -> bool {
1233 PartialEq::ne(&**self, &**other)
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1239 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1240 PartialOrd::partial_cmp(&**self, &**other)
1243 fn lt(&self, other: &Self) -> bool {
1244 PartialOrd::lt(&**self, &**other)
1247 fn le(&self, other: &Self) -> bool {
1248 PartialOrd::le(&**self, &**other)
1251 fn ge(&self, other: &Self) -> bool {
1252 PartialOrd::ge(&**self, &**other)
1255 fn gt(&self, other: &Self) -> bool {
1256 PartialOrd::gt(&**self, &**other)
1259 #[stable(feature = "rust1", since = "1.0.0")]
1260 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1262 fn cmp(&self, other: &Self) -> Ordering {
1263 Ord::cmp(&**self, &**other)
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1271 fn hash<H: Hasher>(&self, state: &mut H) {
1272 (**self).hash(state);
1276 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1277 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1278 fn finish(&self) -> u64 {
1281 fn write(&mut self, bytes: &[u8]) {
1282 (**self).write(bytes)
1284 fn write_u8(&mut self, i: u8) {
1285 (**self).write_u8(i)
1287 fn write_u16(&mut self, i: u16) {
1288 (**self).write_u16(i)
1290 fn write_u32(&mut self, i: u32) {
1291 (**self).write_u32(i)
1293 fn write_u64(&mut self, i: u64) {
1294 (**self).write_u64(i)
1296 fn write_u128(&mut self, i: u128) {
1297 (**self).write_u128(i)
1299 fn write_usize(&mut self, i: usize) {
1300 (**self).write_usize(i)
1302 fn write_i8(&mut self, i: i8) {
1303 (**self).write_i8(i)
1305 fn write_i16(&mut self, i: i16) {
1306 (**self).write_i16(i)
1308 fn write_i32(&mut self, i: i32) {
1309 (**self).write_i32(i)
1311 fn write_i64(&mut self, i: i64) {
1312 (**self).write_i64(i)
1314 fn write_i128(&mut self, i: i128) {
1315 (**self).write_i128(i)
1317 fn write_isize(&mut self, i: isize) {
1318 (**self).write_isize(i)
1322 #[cfg(not(no_global_oom_handling))]
1323 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1324 impl<T> From<T> for Box<T> {
1325 /// Converts a `T` into a `Box<T>`
1327 /// The conversion allocates on the heap and moves `t`
1328 /// from the stack into it.
1334 /// let boxed = Box::new(5);
1336 /// assert_eq!(Box::from(x), boxed);
1338 fn from(t: T) -> Self {
1343 #[stable(feature = "pin", since = "1.33.0")]
1344 impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
1348 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1350 /// This conversion does not allocate on the heap and happens in place.
1351 fn from(boxed: Box<T, A>) -> Self {
1352 Box::into_pin(boxed)
1356 #[cfg(not(no_global_oom_handling))]
1357 #[stable(feature = "box_from_slice", since = "1.17.0")]
1358 impl<T: Copy> From<&[T]> for Box<[T]> {
1359 /// Converts a `&[T]` into a `Box<[T]>`
1361 /// This conversion allocates on the heap
1362 /// and performs a copy of `slice`.
1366 /// // create a &[u8] which will be used to create a Box<[u8]>
1367 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1368 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1370 /// println!("{:?}", boxed_slice);
1372 fn from(slice: &[T]) -> Box<[T]> {
1373 let len = slice.len();
1374 let buf = RawVec::with_capacity(len);
1376 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1377 buf.into_box(slice.len()).assume_init()
1382 #[cfg(not(no_global_oom_handling))]
1383 #[stable(feature = "box_from_cow", since = "1.45.0")]
1384 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1385 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1387 /// When `cow` is the `Cow::Borrowed` variant, this
1388 /// conversion allocates on the heap and copies the
1389 /// underlying slice. Otherwise, it will try to reuse the owned
1390 /// `Vec`'s allocation.
1392 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1394 Cow::Borrowed(slice) => Box::from(slice),
1395 Cow::Owned(slice) => Box::from(slice),
1400 #[cfg(not(no_global_oom_handling))]
1401 #[stable(feature = "box_from_slice", since = "1.17.0")]
1402 impl From<&str> for Box<str> {
1403 /// Converts a `&str` into a `Box<str>`
1405 /// This conversion allocates on the heap
1406 /// and performs a copy of `s`.
1411 /// let boxed: Box<str> = Box::from("hello");
1412 /// println!("{}", boxed);
1415 fn from(s: &str) -> Box<str> {
1416 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1420 #[cfg(not(no_global_oom_handling))]
1421 #[stable(feature = "box_from_cow", since = "1.45.0")]
1422 impl From<Cow<'_, str>> for Box<str> {
1423 /// Converts a `Cow<'_, str>` into a `Box<str>`
1425 /// When `cow` is the `Cow::Borrowed` variant, this
1426 /// conversion allocates on the heap and copies the
1427 /// underlying `str`. Otherwise, it will try to reuse the owned
1428 /// `String`'s allocation.
1433 /// use std::borrow::Cow;
1435 /// let unboxed = Cow::Borrowed("hello");
1436 /// let boxed: Box<str> = Box::from(unboxed);
1437 /// println!("{}", boxed);
1441 /// # use std::borrow::Cow;
1442 /// let unboxed = Cow::Owned("hello".to_string());
1443 /// let boxed: Box<str> = Box::from(unboxed);
1444 /// println!("{}", boxed);
1447 fn from(cow: Cow<'_, str>) -> Box<str> {
1449 Cow::Borrowed(s) => Box::from(s),
1450 Cow::Owned(s) => Box::from(s),
1455 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1456 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1457 /// Converts a `Box<str>` into a `Box<[u8]>`
1459 /// This conversion does not allocate on the heap and happens in place.
1463 /// // create a Box<str> which will be used to create a Box<[u8]>
1464 /// let boxed: Box<str> = Box::from("hello");
1465 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1467 /// // create a &[u8] which will be used to create a Box<[u8]>
1468 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1469 /// let boxed_slice = Box::from(slice);
1471 /// assert_eq!(boxed_slice, boxed_str);
1474 fn from(s: Box<str, A>) -> Self {
1475 let (raw, alloc) = Box::into_raw_with_allocator(s);
1476 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1480 #[cfg(not(no_global_oom_handling))]
1481 #[stable(feature = "box_from_array", since = "1.45.0")]
1482 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1483 /// Converts a `[T; N]` into a `Box<[T]>`
1485 /// This conversion moves the array to newly heap-allocated memory.
1490 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1491 /// println!("{:?}", boxed);
1493 fn from(array: [T; N]) -> Box<[T]> {
1498 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1499 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1500 type Error = Box<[T]>;
1502 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1504 /// The conversion occurs in-place and does not require a
1505 /// new memory allocation.
1509 /// Returns the old `Box<[T]>` in the `Err` variant if
1510 /// `boxed_slice.len()` does not equal `N`.
1511 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1512 if boxed_slice.len() == N {
1513 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1520 impl<A: Allocator> Box<dyn Any, A> {
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 /// Attempt to downcast the box to a concrete type.
1528 /// use std::any::Any;
1530 /// fn print_if_string(value: Box<dyn Any>) {
1531 /// if let Ok(string) = value.downcast::<String>() {
1532 /// println!("String ({}): {}", string.len(), string);
1536 /// let my_string = "Hello World".to_string();
1537 /// print_if_string(Box::new(my_string));
1538 /// print_if_string(Box::new(0i8));
1540 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1543 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1544 Ok(Box::from_raw_in(raw as *mut T, alloc))
1552 impl<A: Allocator> Box<dyn Any + Send, A> {
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 /// Attempt to downcast the box to a concrete type.
1560 /// use std::any::Any;
1562 /// fn print_if_string(value: Box<dyn Any + Send>) {
1563 /// if let Ok(string) = value.downcast::<String>() {
1564 /// println!("String ({}): {}", string.len(), string);
1568 /// let my_string = "Hello World".to_string();
1569 /// print_if_string(Box::new(my_string));
1570 /// print_if_string(Box::new(0i8));
1572 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1575 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1576 Ok(Box::from_raw_in(raw as *mut T, alloc))
1584 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1586 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1587 /// Attempt to downcast the box to a concrete type.
1592 /// use std::any::Any;
1594 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1595 /// if let Ok(string) = value.downcast::<String>() {
1596 /// println!("String ({}): {}", string.len(), string);
1600 /// let my_string = "Hello World".to_string();
1601 /// print_if_string(Box::new(my_string));
1602 /// print_if_string(Box::new(0i8));
1604 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1607 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1608 Box::into_raw_with_allocator(self);
1609 Ok(Box::from_raw_in(raw as *mut T, alloc))
1617 #[stable(feature = "rust1", since = "1.0.0")]
1618 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1620 fmt::Display::fmt(&**self, f)
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1626 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1627 fmt::Debug::fmt(&**self, f)
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1633 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1634 // It's not possible to extract the inner Uniq directly from the Box,
1635 // instead we cast it to a *const which aliases the Unique
1636 let ptr: *const T = &**self;
1637 fmt::Pointer::fmt(&ptr, f)
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
1645 fn deref(&self) -> &T {
1650 #[stable(feature = "rust1", since = "1.0.0")]
1651 impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
1652 fn deref_mut(&mut self) -> &mut T {
1657 #[unstable(feature = "receiver_trait", issue = "none")]
1658 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1662 type Item = I::Item;
1663 fn next(&mut self) -> Option<I::Item> {
1666 fn size_hint(&self) -> (usize, Option<usize>) {
1667 (**self).size_hint()
1669 fn nth(&mut self, n: usize) -> Option<I::Item> {
1672 fn last(self) -> Option<I::Item> {
1679 fn last(self) -> Option<Self::Item>;
1682 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1683 type Item = I::Item;
1684 default fn last(self) -> Option<I::Item> {
1686 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1690 self.fold(None, some)
1694 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1695 /// instead of the default.
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1698 fn last(self) -> Option<I::Item> {
1703 #[stable(feature = "rust1", since = "1.0.0")]
1704 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1705 fn next_back(&mut self) -> Option<I::Item> {
1706 (**self).next_back()
1708 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1709 (**self).nth_back(n)
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1714 fn len(&self) -> usize {
1717 fn is_empty(&self) -> bool {
1722 #[stable(feature = "fused", since = "1.26.0")]
1723 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1725 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1726 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1727 type Output = <F as FnOnce<Args>>::Output;
1729 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1730 <F as FnOnce<Args>>::call_once(*self, args)
1734 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1735 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1736 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1737 <F as FnMut<Args>>::call_mut(self, args)
1741 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1742 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1743 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1744 <F as Fn<Args>>::call(self, args)
1748 #[unstable(feature = "coerce_unsized", issue = "27732")]
1749 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1751 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1752 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1754 #[cfg(not(no_global_oom_handling))]
1755 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1756 impl<I> FromIterator<I> for Box<[I]> {
1757 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1758 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1762 #[cfg(not(no_global_oom_handling))]
1763 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1764 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1765 fn clone(&self) -> Self {
1766 let alloc = Box::allocator(self).clone();
1767 self.to_vec_in(alloc).into_boxed_slice()
1770 fn clone_from(&mut self, other: &Self) {
1771 if self.len() == other.len() {
1772 self.clone_from_slice(&other);
1774 *self = other.clone();
1779 #[stable(feature = "box_borrow", since = "1.1.0")]
1780 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1781 fn borrow(&self) -> &T {
1786 #[stable(feature = "box_borrow", since = "1.1.0")]
1787 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1788 fn borrow_mut(&mut self) -> &mut T {
1793 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1794 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1795 fn as_ref(&self) -> &T {
1800 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1801 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1802 fn as_mut(&mut self) -> &mut T {
1809 * We could have chosen not to add this impl, and instead have written a
1810 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1811 * because Box<T> implements Unpin even when T does not, as a result of
1814 * We chose this API instead of the alternative for a few reasons:
1815 * - Logically, it is helpful to understand pinning in regard to the
1816 * memory region being pointed to. For this reason none of the
1817 * standard library pointer types support projecting through a pin
1818 * (Box<T> is the only pointer type in std for which this would be
1820 * - It is in practice very useful to have Box<T> be unconditionally
1821 * Unpin because of trait objects, for which the structural auto
1822 * trait functionality does not apply (e.g., Box<dyn Foo> would
1823 * otherwise not be Unpin).
1825 * Another type with the same semantics as Box but only a conditional
1826 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1827 * could have a method to project a Pin<T> from it.
1829 #[stable(feature = "pin", since = "1.33.0")]
1830 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
1832 #[unstable(feature = "generator_trait", issue = "43122")]
1833 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1837 type Yield = G::Yield;
1838 type Return = G::Return;
1840 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1841 G::resume(Pin::new(&mut *self), arg)
1845 #[unstable(feature = "generator_trait", issue = "43122")]
1846 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1850 type Yield = G::Yield;
1851 type Return = G::Return;
1853 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1854 G::resume((*self).as_mut(), arg)
1858 #[stable(feature = "futures_api", since = "1.36.0")]
1859 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
1863 type Output = F::Output;
1865 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1866 F::poll(Pin::new(&mut *self), cx)
1870 #[unstable(feature = "async_stream", issue = "79024")]
1871 impl<S: ?Sized + Stream + Unpin> Stream for Box<S> {
1872 type Item = S::Item;
1874 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1875 Pin::new(&mut **self).poll_next(cx)
1878 fn size_hint(&self) -> (usize, Option<usize>) {
1879 (**self).size_hint()