1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 //! A pointer type for heap allocation.
5 //! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
6 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
7 //! drop their contents when they go out of scope. Boxes also ensure that they
8 //! never allocate more than `isize::MAX` bytes.
12 //! Move a value from the stack to the heap by creating a [`Box`]:
16 //! let boxed: Box<u8> = Box::new(val);
19 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
22 //! let boxed: Box<u8> = Box::new(5);
23 //! let val: u8 = *boxed;
26 //! Creating a recursive data structure:
31 //! Cons(T, Box<List<T>>),
35 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
36 //! println!("{list:?}");
39 //! This will print `Cons(1, Cons(2, Nil))`.
41 //! Recursive structures must be boxed, because if the definition of `Cons`
44 //! ```compile_fail,E0072
50 //! It wouldn't work. This is because the size of a `List` depends on how many
51 //! elements are in the list, and so we don't know how much memory to allocate
52 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
53 //! big `Cons` needs to be.
57 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
58 //! its allocation. It is valid to convert both ways between a [`Box`] and a
59 //! raw pointer allocated with the [`Global`] allocator, given that the
60 //! [`Layout`] used with the allocator is correct for the type. More precisely,
61 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
62 //! with `Layout::for_value(&*value)` may be converted into a box using
63 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
64 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
65 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
67 //! For zero-sized values, the `Box` pointer still has to be [valid] for reads
68 //! and writes and sufficiently aligned. In particular, casting any aligned
69 //! non-zero integer literal to a raw pointer produces a valid pointer, but a
70 //! pointer pointing into previously allocated memory that since got freed is
71 //! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
72 //! be used is to use [`ptr::NonNull::dangling`].
74 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
75 //! as a single pointer and is also ABI-compatible with C pointers
76 //! (i.e. the C type `T*`). This means that if you have extern "C"
77 //! Rust functions that will be called from C, you can define those
78 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
79 //! type on the C side. As an example, consider this C header which
80 //! declares functions that create and destroy some kind of `Foo`
86 //! /* Returns ownership to the caller */
87 //! struct Foo* foo_new(void);
89 //! /* Takes ownership from the caller; no-op when invoked with null */
90 //! void foo_delete(struct Foo*);
93 //! These two functions might be implemented in Rust as follows. Here, the
94 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
95 //! the ownership constraints. Note also that the nullable argument to
96 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
104 //! pub extern "C" fn foo_new() -> Box<Foo> {
109 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
112 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
113 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
114 //! and expect things to work. `Box<T>` values will always be fully aligned,
115 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
116 //! free the value with the global allocator. In general, the best practice
117 //! is to only use `Box<T>` for pointers that originated from the global
120 //! **Important.** At least at present, you should avoid using
121 //! `Box<T>` types for functions that are defined in C but invoked
122 //! from Rust. In those cases, you should directly mirror the C types
123 //! as closely as possible. Using types like `Box<T>` where the C
124 //! definition is just using `T*` can lead to undefined behavior, as
125 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
127 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
128 //! [dereferencing]: core::ops::Deref
129 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
130 //! [`Global`]: crate::alloc::Global
131 //! [`Layout`]: crate::alloc::Layout
132 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
133 //! [valid]: ptr#safety
135 #![stable(feature = "rust1", since = "1.0.0")]
138 use core::async_iter::AsyncIterator;
140 use core::cmp::Ordering;
141 use core::convert::{From, TryFrom};
143 use core::future::Future;
144 use core::hash::{Hash, Hasher};
145 #[cfg(not(no_global_oom_handling))]
146 use core::iter::FromIterator;
147 use core::iter::{FusedIterator, Iterator};
148 use core::marker::{Destruct, Unpin, Unsize};
151 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
154 use core::ptr::{self, Unique};
155 use core::task::{Context, Poll};
157 #[cfg(not(no_global_oom_handling))]
158 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
159 use crate::alloc::{AllocError, Allocator, Global, Layout};
160 #[cfg(not(no_global_oom_handling))]
161 use crate::borrow::Cow;
162 use crate::raw_vec::RawVec;
163 #[cfg(not(no_global_oom_handling))]
164 use crate::str::from_boxed_utf8_unchecked;
165 #[cfg(not(no_global_oom_handling))]
169 #[unstable(feature = "thin_box", issue = "92791")]
170 pub use thin::ThinBox;
175 /// A pointer type for heap allocation.
177 /// See the [module-level documentation](../../std/boxed/index.html) for more.
178 #[lang = "owned_box"]
180 #[stable(feature = "rust1", since = "1.0.0")]
181 // The declaration of the `Box` struct must be kept in sync with the
182 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
183 // on `box_free` for more details.
186 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
190 /// Allocates memory on the heap and then places `x` into it.
192 /// This doesn't actually allocate if `T` is zero-sized.
197 /// let five = Box::new(5);
199 #[cfg(not(no_global_oom_handling))]
201 #[stable(feature = "rust1", since = "1.0.0")]
203 pub fn new(x: T) -> Self {
207 /// Constructs a new box with uninitialized contents.
212 /// #![feature(new_uninit)]
214 /// let mut five = Box::<u32>::new_uninit();
216 /// let five = unsafe {
217 /// // Deferred initialization:
218 /// five.as_mut_ptr().write(5);
220 /// five.assume_init()
223 /// assert_eq!(*five, 5)
225 #[cfg(not(no_global_oom_handling))]
226 #[unstable(feature = "new_uninit", issue = "63291")]
229 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
230 Self::new_uninit_in(Global)
233 /// Constructs a new `Box` with uninitialized contents, with the memory
234 /// being filled with `0` bytes.
236 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
242 /// #![feature(new_uninit)]
244 /// let zero = Box::<u32>::new_zeroed();
245 /// let zero = unsafe { zero.assume_init() };
247 /// assert_eq!(*zero, 0)
250 /// [zeroed]: mem::MaybeUninit::zeroed
251 #[cfg(not(no_global_oom_handling))]
253 #[unstable(feature = "new_uninit", issue = "63291")]
255 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
256 Self::new_zeroed_in(Global)
259 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
260 /// `x` will be pinned in memory and unable to be moved.
261 #[cfg(not(no_global_oom_handling))]
262 #[stable(feature = "pin", since = "1.33.0")]
265 pub fn pin(x: T) -> Pin<Box<T>> {
269 /// Allocates memory on the heap then places `x` into it,
270 /// returning an error if the allocation fails
272 /// This doesn't actually allocate if `T` is zero-sized.
277 /// #![feature(allocator_api)]
279 /// let five = Box::try_new(5)?;
280 /// # Ok::<(), std::alloc::AllocError>(())
282 #[unstable(feature = "allocator_api", issue = "32838")]
284 pub fn try_new(x: T) -> Result<Self, AllocError> {
285 Self::try_new_in(x, Global)
288 /// Constructs a new box with uninitialized contents on the heap,
289 /// returning an error if the allocation fails
294 /// #![feature(allocator_api, new_uninit)]
296 /// let mut five = Box::<u32>::try_new_uninit()?;
298 /// let five = unsafe {
299 /// // Deferred initialization:
300 /// five.as_mut_ptr().write(5);
302 /// five.assume_init()
305 /// assert_eq!(*five, 5);
306 /// # Ok::<(), std::alloc::AllocError>(())
308 #[unstable(feature = "allocator_api", issue = "32838")]
309 // #[unstable(feature = "new_uninit", issue = "63291")]
311 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
312 Box::try_new_uninit_in(Global)
315 /// Constructs a new `Box` with uninitialized contents, with the memory
316 /// being filled with `0` bytes on the heap
318 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
324 /// #![feature(allocator_api, new_uninit)]
326 /// let zero = Box::<u32>::try_new_zeroed()?;
327 /// let zero = unsafe { zero.assume_init() };
329 /// assert_eq!(*zero, 0);
330 /// # Ok::<(), std::alloc::AllocError>(())
333 /// [zeroed]: mem::MaybeUninit::zeroed
334 #[unstable(feature = "allocator_api", issue = "32838")]
335 // #[unstable(feature = "new_uninit", issue = "63291")]
337 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
338 Box::try_new_zeroed_in(Global)
342 impl<T, A: Allocator> Box<T, A> {
343 /// Allocates memory in the given allocator then places `x` into it.
345 /// This doesn't actually allocate if `T` is zero-sized.
350 /// #![feature(allocator_api)]
352 /// use std::alloc::System;
354 /// let five = Box::new_in(5, System);
356 #[cfg(not(no_global_oom_handling))]
357 #[unstable(feature = "allocator_api", issue = "32838")]
358 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
361 pub const fn new_in(x: T, alloc: A) -> Self
363 A: ~const Allocator + ~const Destruct,
365 let mut boxed = Self::new_uninit_in(alloc);
367 boxed.as_mut_ptr().write(x);
372 /// Allocates memory in the given allocator then places `x` into it,
373 /// returning an error if the allocation fails
375 /// This doesn't actually allocate if `T` is zero-sized.
380 /// #![feature(allocator_api)]
382 /// use std::alloc::System;
384 /// let five = Box::try_new_in(5, System)?;
385 /// # Ok::<(), std::alloc::AllocError>(())
387 #[unstable(feature = "allocator_api", issue = "32838")]
388 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
390 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
393 A: ~const Allocator + ~const Destruct,
395 let mut boxed = Self::try_new_uninit_in(alloc)?;
397 boxed.as_mut_ptr().write(x);
398 Ok(boxed.assume_init())
402 /// Constructs a new box with uninitialized contents in the provided allocator.
407 /// #![feature(allocator_api, new_uninit)]
409 /// use std::alloc::System;
411 /// let mut five = Box::<u32, _>::new_uninit_in(System);
413 /// let five = unsafe {
414 /// // Deferred initialization:
415 /// five.as_mut_ptr().write(5);
417 /// five.assume_init()
420 /// assert_eq!(*five, 5)
422 #[unstable(feature = "allocator_api", issue = "32838")]
423 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
424 #[cfg(not(no_global_oom_handling))]
426 // #[unstable(feature = "new_uninit", issue = "63291")]
427 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
429 A: ~const Allocator + ~const Destruct,
431 let layout = Layout::new::<mem::MaybeUninit<T>>();
432 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
433 // That would make code size bigger.
434 match Box::try_new_uninit_in(alloc) {
436 Err(_) => handle_alloc_error(layout),
440 /// Constructs a new box with uninitialized contents in the provided allocator,
441 /// returning an error if the allocation fails
446 /// #![feature(allocator_api, new_uninit)]
448 /// use std::alloc::System;
450 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
452 /// let five = unsafe {
453 /// // Deferred initialization:
454 /// five.as_mut_ptr().write(5);
456 /// five.assume_init()
459 /// assert_eq!(*five, 5);
460 /// # Ok::<(), std::alloc::AllocError>(())
462 #[unstable(feature = "allocator_api", issue = "32838")]
463 // #[unstable(feature = "new_uninit", issue = "63291")]
464 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
465 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
467 A: ~const Allocator + ~const Destruct,
469 let layout = Layout::new::<mem::MaybeUninit<T>>();
470 let ptr = alloc.allocate(layout)?.cast();
471 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
474 /// Constructs a new `Box` with uninitialized contents, with the memory
475 /// being filled with `0` bytes in the provided allocator.
477 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
483 /// #![feature(allocator_api, new_uninit)]
485 /// use std::alloc::System;
487 /// let zero = Box::<u32, _>::new_zeroed_in(System);
488 /// let zero = unsafe { zero.assume_init() };
490 /// assert_eq!(*zero, 0)
493 /// [zeroed]: mem::MaybeUninit::zeroed
494 #[unstable(feature = "allocator_api", issue = "32838")]
495 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
496 #[cfg(not(no_global_oom_handling))]
497 // #[unstable(feature = "new_uninit", issue = "63291")]
499 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
501 A: ~const Allocator + ~const Destruct,
503 let layout = Layout::new::<mem::MaybeUninit<T>>();
504 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
505 // That would make code size bigger.
506 match Box::try_new_zeroed_in(alloc) {
508 Err(_) => handle_alloc_error(layout),
512 /// Constructs a new `Box` with uninitialized contents, with the memory
513 /// being filled with `0` bytes in the provided allocator,
514 /// returning an error if the allocation fails,
516 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
522 /// #![feature(allocator_api, new_uninit)]
524 /// use std::alloc::System;
526 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
527 /// let zero = unsafe { zero.assume_init() };
529 /// assert_eq!(*zero, 0);
530 /// # Ok::<(), std::alloc::AllocError>(())
533 /// [zeroed]: mem::MaybeUninit::zeroed
534 #[unstable(feature = "allocator_api", issue = "32838")]
535 // #[unstable(feature = "new_uninit", issue = "63291")]
536 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
537 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
539 A: ~const Allocator + ~const Destruct,
541 let layout = Layout::new::<mem::MaybeUninit<T>>();
542 let ptr = alloc.allocate_zeroed(layout)?.cast();
543 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
546 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
547 /// `x` will be pinned in memory and unable to be moved.
548 #[cfg(not(no_global_oom_handling))]
549 #[unstable(feature = "allocator_api", issue = "32838")]
550 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
553 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
555 A: 'static + ~const Allocator + ~const Destruct,
557 Self::into_pin(Self::new_in(x, alloc))
560 /// Converts a `Box<T>` into a `Box<[T]>`
562 /// This conversion does not allocate on the heap and happens in place.
563 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
564 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
565 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
566 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
567 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
570 /// Consumes the `Box`, returning the wrapped value.
575 /// #![feature(box_into_inner)]
577 /// let c = Box::new(5);
579 /// assert_eq!(Box::into_inner(c), 5);
581 #[unstable(feature = "box_into_inner", issue = "80437")]
582 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
584 pub const fn into_inner(boxed: Self) -> T
586 Self: ~const Destruct,
593 /// Constructs a new boxed slice with uninitialized contents.
598 /// #![feature(new_uninit)]
600 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
602 /// let values = unsafe {
603 /// // Deferred initialization:
604 /// values[0].as_mut_ptr().write(1);
605 /// values[1].as_mut_ptr().write(2);
606 /// values[2].as_mut_ptr().write(3);
608 /// values.assume_init()
611 /// assert_eq!(*values, [1, 2, 3])
613 #[cfg(not(no_global_oom_handling))]
614 #[unstable(feature = "new_uninit", issue = "63291")]
616 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
617 unsafe { RawVec::with_capacity(len).into_box(len) }
620 /// Constructs a new boxed slice with uninitialized contents, with the memory
621 /// being filled with `0` bytes.
623 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
629 /// #![feature(new_uninit)]
631 /// let values = Box::<[u32]>::new_zeroed_slice(3);
632 /// let values = unsafe { values.assume_init() };
634 /// assert_eq!(*values, [0, 0, 0])
637 /// [zeroed]: mem::MaybeUninit::zeroed
638 #[cfg(not(no_global_oom_handling))]
639 #[unstable(feature = "new_uninit", issue = "63291")]
641 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
642 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
645 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
646 /// the allocation fails
651 /// #![feature(allocator_api, new_uninit)]
653 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
654 /// let values = unsafe {
655 /// // Deferred initialization:
656 /// values[0].as_mut_ptr().write(1);
657 /// values[1].as_mut_ptr().write(2);
658 /// values[2].as_mut_ptr().write(3);
659 /// values.assume_init()
662 /// assert_eq!(*values, [1, 2, 3]);
663 /// # Ok::<(), std::alloc::AllocError>(())
665 #[unstable(feature = "allocator_api", issue = "32838")]
667 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
669 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
671 Err(_) => return Err(AllocError),
673 let ptr = Global.allocate(layout)?;
674 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
678 /// Constructs a new boxed slice with uninitialized contents, with the memory
679 /// being filled with `0` bytes. Returns an error if the allocation fails
681 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
687 /// #![feature(allocator_api, new_uninit)]
689 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
690 /// let values = unsafe { values.assume_init() };
692 /// assert_eq!(*values, [0, 0, 0]);
693 /// # Ok::<(), std::alloc::AllocError>(())
696 /// [zeroed]: mem::MaybeUninit::zeroed
697 #[unstable(feature = "allocator_api", issue = "32838")]
699 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
701 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
703 Err(_) => return Err(AllocError),
705 let ptr = Global.allocate_zeroed(layout)?;
706 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
711 impl<T, A: Allocator> Box<[T], A> {
712 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
717 /// #![feature(allocator_api, new_uninit)]
719 /// use std::alloc::System;
721 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
723 /// let values = unsafe {
724 /// // Deferred initialization:
725 /// values[0].as_mut_ptr().write(1);
726 /// values[1].as_mut_ptr().write(2);
727 /// values[2].as_mut_ptr().write(3);
729 /// values.assume_init()
732 /// assert_eq!(*values, [1, 2, 3])
734 #[cfg(not(no_global_oom_handling))]
735 #[unstable(feature = "allocator_api", issue = "32838")]
736 // #[unstable(feature = "new_uninit", issue = "63291")]
738 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
739 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
742 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
743 /// with the memory being filled with `0` bytes.
745 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
751 /// #![feature(allocator_api, new_uninit)]
753 /// use std::alloc::System;
755 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
756 /// let values = unsafe { values.assume_init() };
758 /// assert_eq!(*values, [0, 0, 0])
761 /// [zeroed]: mem::MaybeUninit::zeroed
762 #[cfg(not(no_global_oom_handling))]
763 #[unstable(feature = "allocator_api", issue = "32838")]
764 // #[unstable(feature = "new_uninit", issue = "63291")]
766 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
767 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
771 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
772 /// Converts to `Box<T, A>`.
776 /// As with [`MaybeUninit::assume_init`],
777 /// it is up to the caller to guarantee that the value
778 /// really is in an initialized state.
779 /// Calling this when the content is not yet fully initialized
780 /// causes immediate undefined behavior.
782 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
787 /// #![feature(new_uninit)]
789 /// let mut five = Box::<u32>::new_uninit();
791 /// let five: Box<u32> = unsafe {
792 /// // Deferred initialization:
793 /// five.as_mut_ptr().write(5);
795 /// five.assume_init()
798 /// assert_eq!(*five, 5)
800 #[unstable(feature = "new_uninit", issue = "63291")]
801 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
803 pub const unsafe fn assume_init(self) -> Box<T, A> {
804 let (raw, alloc) = Box::into_raw_with_allocator(self);
805 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
808 /// Writes the value and converts to `Box<T, A>`.
810 /// This method converts the box similarly to [`Box::assume_init`] but
811 /// writes `value` into it before conversion thus guaranteeing safety.
812 /// In some scenarios use of this method may improve performance because
813 /// the compiler may be able to optimize copying from stack.
818 /// #![feature(new_uninit)]
820 /// let big_box = Box::<[usize; 1024]>::new_uninit();
822 /// let mut array = [0; 1024];
823 /// for (i, place) in array.iter_mut().enumerate() {
827 /// // The optimizer may be able to elide this copy, so previous code writes
828 /// // to heap directly.
829 /// let big_box = Box::write(big_box, array);
831 /// for (i, x) in big_box.iter().enumerate() {
832 /// assert_eq!(*x, i);
835 #[unstable(feature = "new_uninit", issue = "63291")]
836 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
838 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
840 (*boxed).write(value);
846 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
847 /// Converts to `Box<[T], A>`.
851 /// As with [`MaybeUninit::assume_init`],
852 /// it is up to the caller to guarantee that the values
853 /// really are in an initialized state.
854 /// Calling this when the content is not yet fully initialized
855 /// causes immediate undefined behavior.
857 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
862 /// #![feature(new_uninit)]
864 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
866 /// let values = unsafe {
867 /// // Deferred initialization:
868 /// values[0].as_mut_ptr().write(1);
869 /// values[1].as_mut_ptr().write(2);
870 /// values[2].as_mut_ptr().write(3);
872 /// values.assume_init()
875 /// assert_eq!(*values, [1, 2, 3])
877 #[unstable(feature = "new_uninit", issue = "63291")]
879 pub unsafe fn assume_init(self) -> Box<[T], A> {
880 let (raw, alloc) = Box::into_raw_with_allocator(self);
881 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
885 impl<T: ?Sized> Box<T> {
886 /// Constructs a box from a raw pointer.
888 /// After calling this function, the raw pointer is owned by the
889 /// resulting `Box`. Specifically, the `Box` destructor will call
890 /// the destructor of `T` and free the allocated memory. For this
891 /// to be safe, the memory must have been allocated in accordance
892 /// with the [memory layout] used by `Box` .
896 /// This function is unsafe because improper use may lead to
897 /// memory problems. For example, a double-free may occur if the
898 /// function is called twice on the same raw pointer.
900 /// The safety conditions are described in the [memory layout] section.
904 /// Recreate a `Box` which was previously converted to a raw pointer
905 /// using [`Box::into_raw`]:
907 /// let x = Box::new(5);
908 /// let ptr = Box::into_raw(x);
909 /// let x = unsafe { Box::from_raw(ptr) };
911 /// Manually create a `Box` from scratch by using the global allocator:
913 /// use std::alloc::{alloc, Layout};
916 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
917 /// // In general .write is required to avoid attempting to destruct
918 /// // the (uninitialized) previous contents of `ptr`, though for this
919 /// // simple example `*ptr = 5` would have worked as well.
921 /// let x = Box::from_raw(ptr);
925 /// [memory layout]: self#memory-layout
926 /// [`Layout`]: crate::Layout
927 #[stable(feature = "box_raw", since = "1.4.0")]
929 pub unsafe fn from_raw(raw: *mut T) -> Self {
930 unsafe { Self::from_raw_in(raw, Global) }
934 impl<T: ?Sized, A: Allocator> Box<T, A> {
935 /// Constructs a box from a raw pointer in the given allocator.
937 /// After calling this function, the raw pointer is owned by the
938 /// resulting `Box`. Specifically, the `Box` destructor will call
939 /// the destructor of `T` and free the allocated memory. For this
940 /// to be safe, the memory must have been allocated in accordance
941 /// with the [memory layout] used by `Box` .
945 /// This function is unsafe because improper use may lead to
946 /// memory problems. For example, a double-free may occur if the
947 /// function is called twice on the same raw pointer.
952 /// Recreate a `Box` which was previously converted to a raw pointer
953 /// using [`Box::into_raw_with_allocator`]:
955 /// #![feature(allocator_api)]
957 /// use std::alloc::System;
959 /// let x = Box::new_in(5, System);
960 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
961 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
963 /// Manually create a `Box` from scratch by using the system allocator:
965 /// #![feature(allocator_api, slice_ptr_get)]
967 /// use std::alloc::{Allocator, Layout, System};
970 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
971 /// // In general .write is required to avoid attempting to destruct
972 /// // the (uninitialized) previous contents of `ptr`, though for this
973 /// // simple example `*ptr = 5` would have worked as well.
975 /// let x = Box::from_raw_in(ptr, System);
977 /// # Ok::<(), std::alloc::AllocError>(())
980 /// [memory layout]: self#memory-layout
981 /// [`Layout`]: crate::Layout
982 #[unstable(feature = "allocator_api", issue = "32838")]
983 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
985 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
986 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
989 /// Consumes the `Box`, returning a wrapped raw pointer.
991 /// The pointer will be properly aligned and non-null.
993 /// After calling this function, the caller is responsible for the
994 /// memory previously managed by the `Box`. In particular, the
995 /// caller should properly destroy `T` and release the memory, taking
996 /// into account the [memory layout] used by `Box`. The easiest way to
997 /// do this is to convert the raw pointer back into a `Box` with the
998 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1001 /// Note: this is an associated function, which means that you have
1002 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1003 /// is so that there is no conflict with a method on the inner type.
1006 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1007 /// for automatic cleanup:
1009 /// let x = Box::new(String::from("Hello"));
1010 /// let ptr = Box::into_raw(x);
1011 /// let x = unsafe { Box::from_raw(ptr) };
1013 /// Manual cleanup by explicitly running the destructor and deallocating
1016 /// use std::alloc::{dealloc, Layout};
1019 /// let x = Box::new(String::from("Hello"));
1020 /// let p = Box::into_raw(x);
1022 /// ptr::drop_in_place(p);
1023 /// dealloc(p as *mut u8, Layout::new::<String>());
1027 /// [memory layout]: self#memory-layout
1028 #[stable(feature = "box_raw", since = "1.4.0")]
1030 pub fn into_raw(b: Self) -> *mut T {
1031 Self::into_raw_with_allocator(b).0
1034 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1036 /// The pointer will be properly aligned and non-null.
1038 /// After calling this function, the caller is responsible for the
1039 /// memory previously managed by the `Box`. In particular, the
1040 /// caller should properly destroy `T` and release the memory, taking
1041 /// into account the [memory layout] used by `Box`. The easiest way to
1042 /// do this is to convert the raw pointer back into a `Box` with the
1043 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1046 /// Note: this is an associated function, which means that you have
1047 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1048 /// is so that there is no conflict with a method on the inner type.
1051 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1052 /// for automatic cleanup:
1054 /// #![feature(allocator_api)]
1056 /// use std::alloc::System;
1058 /// let x = Box::new_in(String::from("Hello"), System);
1059 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1060 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1062 /// Manual cleanup by explicitly running the destructor and deallocating
1065 /// #![feature(allocator_api)]
1067 /// use std::alloc::{Allocator, Layout, System};
1068 /// use std::ptr::{self, NonNull};
1070 /// let x = Box::new_in(String::from("Hello"), System);
1071 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1073 /// ptr::drop_in_place(ptr);
1074 /// let non_null = NonNull::new_unchecked(ptr);
1075 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1079 /// [memory layout]: self#memory-layout
1080 #[unstable(feature = "allocator_api", issue = "32838")]
1081 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1083 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1084 let (leaked, alloc) = Box::into_unique(b);
1085 (leaked.as_ptr(), alloc)
1089 feature = "ptr_internals",
1091 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1093 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1096 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1097 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1098 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1099 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1100 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1101 // behaves correctly.
1102 let alloc = unsafe { ptr::read(&b.1) };
1103 (Unique::from(Box::leak(b)), alloc)
1106 /// Returns a reference to the underlying allocator.
1108 /// Note: this is an associated function, which means that you have
1109 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1110 /// is so that there is no conflict with a method on the inner type.
1111 #[unstable(feature = "allocator_api", issue = "32838")]
1112 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1114 pub const fn allocator(b: &Self) -> &A {
1118 /// Consumes and leaks the `Box`, returning a mutable reference,
1119 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1120 /// `'a`. If the type has only static references, or none at all, then this
1121 /// may be chosen to be `'static`.
1123 /// This function is mainly useful for data that lives for the remainder of
1124 /// the program's life. Dropping the returned reference will cause a memory
1125 /// leak. If this is not acceptable, the reference should first be wrapped
1126 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1127 /// then be dropped which will properly destroy `T` and release the
1128 /// allocated memory.
1130 /// Note: this is an associated function, which means that you have
1131 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1132 /// is so that there is no conflict with a method on the inner type.
1139 /// let x = Box::new(41);
1140 /// let static_ref: &'static mut usize = Box::leak(x);
1141 /// *static_ref += 1;
1142 /// assert_eq!(*static_ref, 42);
1148 /// let x = vec![1, 2, 3].into_boxed_slice();
1149 /// let static_ref = Box::leak(x);
1150 /// static_ref[0] = 4;
1151 /// assert_eq!(*static_ref, [4, 2, 3]);
1153 #[stable(feature = "box_leak", since = "1.26.0")]
1154 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1156 pub const fn leak<'a>(b: Self) -> &'a mut T
1160 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1163 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1165 /// This conversion does not allocate on the heap and happens in place.
1167 /// This is also available via [`From`].
1168 #[unstable(feature = "box_into_pin", issue = "62370")]
1169 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1170 pub const fn into_pin(boxed: Self) -> Pin<Self>
1174 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1175 // when `T: !Unpin`, so it's safe to pin it directly without any
1176 // additional requirements.
1177 unsafe { Pin::new_unchecked(boxed) }
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1183 fn drop(&mut self) {
1184 // FIXME: Do nothing, drop is currently performed by compiler.
1188 #[cfg(not(no_global_oom_handling))]
1189 #[stable(feature = "rust1", since = "1.0.0")]
1190 impl<T: Default> Default for Box<T> {
1191 /// Creates a `Box<T>`, with the `Default` value for T.
1192 fn default() -> Self {
1197 #[cfg(not(no_global_oom_handling))]
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1200 impl<T> const Default for Box<[T]> {
1201 fn default() -> Self {
1202 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1207 #[cfg(not(no_global_oom_handling))]
1208 #[stable(feature = "default_box_extra", since = "1.17.0")]
1209 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1210 impl const Default for Box<str> {
1211 fn default() -> Self {
1212 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1213 let ptr: Unique<str> = unsafe {
1214 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1215 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1221 #[cfg(not(no_global_oom_handling))]
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1224 /// Returns a new box with a `clone()` of this box's contents.
1229 /// let x = Box::new(5);
1230 /// let y = x.clone();
1232 /// // The value is the same
1233 /// assert_eq!(x, y);
1235 /// // But they are unique objects
1236 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1239 fn clone(&self) -> Self {
1240 // Pre-allocate memory to allow writing the cloned value directly.
1241 let mut boxed = Self::new_uninit_in(self.1.clone());
1243 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1248 /// Copies `source`'s contents into `self` without creating a new allocation.
1253 /// let x = Box::new(5);
1254 /// let mut y = Box::new(10);
1255 /// let yp: *const i32 = &*y;
1257 /// y.clone_from(&x);
1259 /// // The value is the same
1260 /// assert_eq!(x, y);
1262 /// // And no allocation occurred
1263 /// assert_eq!(yp, &*y);
1266 fn clone_from(&mut self, source: &Self) {
1267 (**self).clone_from(&(**source));
1271 #[cfg(not(no_global_oom_handling))]
1272 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1273 impl Clone for Box<str> {
1274 fn clone(&self) -> Self {
1275 // this makes a copy of the data
1276 let buf: Box<[u8]> = self.as_bytes().into();
1277 unsafe { from_boxed_utf8_unchecked(buf) }
1281 #[stable(feature = "rust1", since = "1.0.0")]
1282 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1284 fn eq(&self, other: &Self) -> bool {
1285 PartialEq::eq(&**self, &**other)
1288 fn ne(&self, other: &Self) -> bool {
1289 PartialEq::ne(&**self, &**other)
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1295 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1296 PartialOrd::partial_cmp(&**self, &**other)
1299 fn lt(&self, other: &Self) -> bool {
1300 PartialOrd::lt(&**self, &**other)
1303 fn le(&self, other: &Self) -> bool {
1304 PartialOrd::le(&**self, &**other)
1307 fn ge(&self, other: &Self) -> bool {
1308 PartialOrd::ge(&**self, &**other)
1311 fn gt(&self, other: &Self) -> bool {
1312 PartialOrd::gt(&**self, &**other)
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1318 fn cmp(&self, other: &Self) -> Ordering {
1319 Ord::cmp(&**self, &**other)
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1327 fn hash<H: Hasher>(&self, state: &mut H) {
1328 (**self).hash(state);
1332 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1333 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1334 fn finish(&self) -> u64 {
1337 fn write(&mut self, bytes: &[u8]) {
1338 (**self).write(bytes)
1340 fn write_u8(&mut self, i: u8) {
1341 (**self).write_u8(i)
1343 fn write_u16(&mut self, i: u16) {
1344 (**self).write_u16(i)
1346 fn write_u32(&mut self, i: u32) {
1347 (**self).write_u32(i)
1349 fn write_u64(&mut self, i: u64) {
1350 (**self).write_u64(i)
1352 fn write_u128(&mut self, i: u128) {
1353 (**self).write_u128(i)
1355 fn write_usize(&mut self, i: usize) {
1356 (**self).write_usize(i)
1358 fn write_i8(&mut self, i: i8) {
1359 (**self).write_i8(i)
1361 fn write_i16(&mut self, i: i16) {
1362 (**self).write_i16(i)
1364 fn write_i32(&mut self, i: i32) {
1365 (**self).write_i32(i)
1367 fn write_i64(&mut self, i: i64) {
1368 (**self).write_i64(i)
1370 fn write_i128(&mut self, i: i128) {
1371 (**self).write_i128(i)
1373 fn write_isize(&mut self, i: isize) {
1374 (**self).write_isize(i)
1376 fn write_length_prefix(&mut self, len: usize) {
1377 (**self).write_length_prefix(len)
1379 fn write_str(&mut self, s: &str) {
1380 (**self).write_str(s)
1384 #[cfg(not(no_global_oom_handling))]
1385 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1386 impl<T> From<T> for Box<T> {
1387 /// Converts a `T` into a `Box<T>`
1389 /// The conversion allocates on the heap and moves `t`
1390 /// from the stack into it.
1396 /// let boxed = Box::new(5);
1398 /// assert_eq!(Box::from(x), boxed);
1400 fn from(t: T) -> Self {
1405 #[stable(feature = "pin", since = "1.33.0")]
1406 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1407 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1411 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1413 /// This conversion does not allocate on the heap and happens in place.
1414 fn from(boxed: Box<T, A>) -> Self {
1415 Box::into_pin(boxed)
1419 #[cfg(not(no_global_oom_handling))]
1420 #[stable(feature = "box_from_slice", since = "1.17.0")]
1421 impl<T: Copy> From<&[T]> for Box<[T]> {
1422 /// Converts a `&[T]` into a `Box<[T]>`
1424 /// This conversion allocates on the heap
1425 /// and performs a copy of `slice`.
1429 /// // create a &[u8] which will be used to create a Box<[u8]>
1430 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1431 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1433 /// println!("{boxed_slice:?}");
1435 fn from(slice: &[T]) -> Box<[T]> {
1436 let len = slice.len();
1437 let buf = RawVec::with_capacity(len);
1439 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1440 buf.into_box(slice.len()).assume_init()
1445 #[cfg(not(no_global_oom_handling))]
1446 #[stable(feature = "box_from_cow", since = "1.45.0")]
1447 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1448 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1450 /// When `cow` is the `Cow::Borrowed` variant, this
1451 /// conversion allocates on the heap and copies the
1452 /// underlying slice. Otherwise, it will try to reuse the owned
1453 /// `Vec`'s allocation.
1455 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1457 Cow::Borrowed(slice) => Box::from(slice),
1458 Cow::Owned(slice) => Box::from(slice),
1463 #[cfg(not(no_global_oom_handling))]
1464 #[stable(feature = "box_from_slice", since = "1.17.0")]
1465 impl From<&str> for Box<str> {
1466 /// Converts a `&str` into a `Box<str>`
1468 /// This conversion allocates on the heap
1469 /// and performs a copy of `s`.
1474 /// let boxed: Box<str> = Box::from("hello");
1475 /// println!("{boxed}");
1478 fn from(s: &str) -> Box<str> {
1479 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1483 #[cfg(not(no_global_oom_handling))]
1484 #[stable(feature = "box_from_cow", since = "1.45.0")]
1485 impl From<Cow<'_, str>> for Box<str> {
1486 /// Converts a `Cow<'_, str>` into a `Box<str>`
1488 /// When `cow` is the `Cow::Borrowed` variant, this
1489 /// conversion allocates on the heap and copies the
1490 /// underlying `str`. Otherwise, it will try to reuse the owned
1491 /// `String`'s allocation.
1496 /// use std::borrow::Cow;
1498 /// let unboxed = Cow::Borrowed("hello");
1499 /// let boxed: Box<str> = Box::from(unboxed);
1500 /// println!("{boxed}");
1504 /// # use std::borrow::Cow;
1505 /// let unboxed = Cow::Owned("hello".to_string());
1506 /// let boxed: Box<str> = Box::from(unboxed);
1507 /// println!("{boxed}");
1510 fn from(cow: Cow<'_, str>) -> Box<str> {
1512 Cow::Borrowed(s) => Box::from(s),
1513 Cow::Owned(s) => Box::from(s),
1518 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1519 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1520 /// Converts a `Box<str>` into a `Box<[u8]>`
1522 /// This conversion does not allocate on the heap and happens in place.
1526 /// // create a Box<str> which will be used to create a Box<[u8]>
1527 /// let boxed: Box<str> = Box::from("hello");
1528 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1530 /// // create a &[u8] which will be used to create a Box<[u8]>
1531 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1532 /// let boxed_slice = Box::from(slice);
1534 /// assert_eq!(boxed_slice, boxed_str);
1537 fn from(s: Box<str, A>) -> Self {
1538 let (raw, alloc) = Box::into_raw_with_allocator(s);
1539 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1543 #[cfg(not(no_global_oom_handling))]
1544 #[stable(feature = "box_from_array", since = "1.45.0")]
1545 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1546 /// Converts a `[T; N]` into a `Box<[T]>`
1548 /// This conversion moves the array to newly heap-allocated memory.
1553 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1554 /// println!("{boxed:?}");
1556 fn from(array: [T; N]) -> Box<[T]> {
1561 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1562 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1563 type Error = Box<[T]>;
1565 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1567 /// The conversion occurs in-place and does not require a
1568 /// new memory allocation.
1572 /// Returns the old `Box<[T]>` in the `Err` variant if
1573 /// `boxed_slice.len()` does not equal `N`.
1574 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1575 if boxed_slice.len() == N {
1576 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1583 impl<A: Allocator> Box<dyn Any, A> {
1584 /// Attempt to downcast the box to a concrete type.
1589 /// use std::any::Any;
1591 /// fn print_if_string(value: Box<dyn Any>) {
1592 /// if let Ok(string) = value.downcast::<String>() {
1593 /// println!("String ({}): {}", string.len(), string);
1597 /// let my_string = "Hello World".to_string();
1598 /// print_if_string(Box::new(my_string));
1599 /// print_if_string(Box::new(0i8));
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1604 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1607 /// Downcasts the box to a concrete type.
1609 /// For a safe alternative see [`downcast`].
1614 /// #![feature(downcast_unchecked)]
1616 /// use std::any::Any;
1618 /// let x: Box<dyn Any> = Box::new(1_usize);
1621 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1627 /// The contained value must be of type `T`. Calling this method
1628 /// with the incorrect type is *undefined behavior*.
1630 /// [`downcast`]: Self::downcast
1632 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1633 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1634 debug_assert!(self.is::<T>());
1636 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1637 Box::from_raw_in(raw as *mut T, alloc)
1642 impl<A: Allocator> Box<dyn Any + Send, A> {
1643 /// Attempt to downcast the box to a concrete type.
1648 /// use std::any::Any;
1650 /// fn print_if_string(value: Box<dyn Any + Send>) {
1651 /// if let Ok(string) = value.downcast::<String>() {
1652 /// println!("String ({}): {}", string.len(), string);
1656 /// let my_string = "Hello World".to_string();
1657 /// print_if_string(Box::new(my_string));
1658 /// print_if_string(Box::new(0i8));
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1663 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1666 /// Downcasts the box to a concrete type.
1668 /// For a safe alternative see [`downcast`].
1673 /// #![feature(downcast_unchecked)]
1675 /// use std::any::Any;
1677 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1680 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1686 /// The contained value must be of type `T`. Calling this method
1687 /// with the incorrect type is *undefined behavior*.
1689 /// [`downcast`]: Self::downcast
1691 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1692 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1693 debug_assert!(self.is::<T>());
1695 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1696 Box::from_raw_in(raw as *mut T, alloc)
1701 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1702 /// Attempt to downcast the box to a concrete type.
1707 /// use std::any::Any;
1709 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1710 /// if let Ok(string) = value.downcast::<String>() {
1711 /// println!("String ({}): {}", string.len(), string);
1715 /// let my_string = "Hello World".to_string();
1716 /// print_if_string(Box::new(my_string));
1717 /// print_if_string(Box::new(0i8));
1720 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1721 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1722 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1725 /// Downcasts the box to a concrete type.
1727 /// For a safe alternative see [`downcast`].
1732 /// #![feature(downcast_unchecked)]
1734 /// use std::any::Any;
1736 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1739 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1745 /// The contained value must be of type `T`. Calling this method
1746 /// with the incorrect type is *undefined behavior*.
1748 /// [`downcast`]: Self::downcast
1750 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1751 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1752 debug_assert!(self.is::<T>());
1754 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1755 Box::into_raw_with_allocator(self);
1756 Box::from_raw_in(raw as *mut T, alloc)
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1763 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1764 fmt::Display::fmt(&**self, f)
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1771 fmt::Debug::fmt(&**self, f)
1775 #[stable(feature = "rust1", since = "1.0.0")]
1776 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1777 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1778 // It's not possible to extract the inner Uniq directly from the Box,
1779 // instead we cast it to a *const which aliases the Unique
1780 let ptr: *const T = &**self;
1781 fmt::Pointer::fmt(&ptr, f)
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1787 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1790 fn deref(&self) -> &T {
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1797 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1798 fn deref_mut(&mut self) -> &mut T {
1803 #[unstable(feature = "receiver_trait", issue = "none")]
1804 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1808 type Item = I::Item;
1809 fn next(&mut self) -> Option<I::Item> {
1812 fn size_hint(&self) -> (usize, Option<usize>) {
1813 (**self).size_hint()
1815 fn nth(&mut self, n: usize) -> Option<I::Item> {
1818 fn last(self) -> Option<I::Item> {
1825 fn last(self) -> Option<Self::Item>;
1828 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1829 type Item = I::Item;
1830 default fn last(self) -> Option<I::Item> {
1832 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1836 self.fold(None, some)
1840 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1841 /// instead of the default.
1842 #[stable(feature = "rust1", since = "1.0.0")]
1843 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1844 fn last(self) -> Option<I::Item> {
1849 #[stable(feature = "rust1", since = "1.0.0")]
1850 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1851 fn next_back(&mut self) -> Option<I::Item> {
1852 (**self).next_back()
1854 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1855 (**self).nth_back(n)
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1860 fn len(&self) -> usize {
1863 fn is_empty(&self) -> bool {
1868 #[stable(feature = "fused", since = "1.26.0")]
1869 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1871 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1872 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1873 type Output = <F as FnOnce<Args>>::Output;
1875 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1876 <F as FnOnce<Args>>::call_once(*self, args)
1880 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1881 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1882 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1883 <F as FnMut<Args>>::call_mut(self, args)
1887 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1888 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1889 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1890 <F as Fn<Args>>::call(self, args)
1894 #[unstable(feature = "coerce_unsized", issue = "27732")]
1895 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1897 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1898 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1900 #[cfg(not(no_global_oom_handling))]
1901 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1902 impl<I> FromIterator<I> for Box<[I]> {
1903 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1904 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1908 #[cfg(not(no_global_oom_handling))]
1909 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1910 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1911 fn clone(&self) -> Self {
1912 let alloc = Box::allocator(self).clone();
1913 self.to_vec_in(alloc).into_boxed_slice()
1916 fn clone_from(&mut self, other: &Self) {
1917 if self.len() == other.len() {
1918 self.clone_from_slice(&other);
1920 *self = other.clone();
1925 #[stable(feature = "box_borrow", since = "1.1.0")]
1926 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1927 fn borrow(&self) -> &T {
1932 #[stable(feature = "box_borrow", since = "1.1.0")]
1933 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1934 fn borrow_mut(&mut self) -> &mut T {
1939 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1940 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1941 fn as_ref(&self) -> &T {
1946 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1947 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1948 fn as_mut(&mut self) -> &mut T {
1955 * We could have chosen not to add this impl, and instead have written a
1956 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1957 * because Box<T> implements Unpin even when T does not, as a result of
1960 * We chose this API instead of the alternative for a few reasons:
1961 * - Logically, it is helpful to understand pinning in regard to the
1962 * memory region being pointed to. For this reason none of the
1963 * standard library pointer types support projecting through a pin
1964 * (Box<T> is the only pointer type in std for which this would be
1966 * - It is in practice very useful to have Box<T> be unconditionally
1967 * Unpin because of trait objects, for which the structural auto
1968 * trait functionality does not apply (e.g., Box<dyn Foo> would
1969 * otherwise not be Unpin).
1971 * Another type with the same semantics as Box but only a conditional
1972 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1973 * could have a method to project a Pin<T> from it.
1975 #[stable(feature = "pin", since = "1.33.0")]
1976 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1977 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
1979 #[unstable(feature = "generator_trait", issue = "43122")]
1980 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1984 type Yield = G::Yield;
1985 type Return = G::Return;
1987 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1988 G::resume(Pin::new(&mut *self), arg)
1992 #[unstable(feature = "generator_trait", issue = "43122")]
1993 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1997 type Yield = G::Yield;
1998 type Return = G::Return;
2000 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2001 G::resume((*self).as_mut(), arg)
2005 #[stable(feature = "futures_api", since = "1.36.0")]
2006 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2010 type Output = F::Output;
2012 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2013 F::poll(Pin::new(&mut *self), cx)
2017 #[unstable(feature = "async_iterator", issue = "79024")]
2018 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2019 type Item = S::Item;
2021 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2022 Pin::new(&mut **self).poll_next(cx)
2025 fn size_hint(&self) -> (usize, Option<usize>) {
2026 (**self).size_hint()