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")]
136 use core::async_iter::AsyncIterator;
138 use core::cmp::Ordering;
139 use core::convert::{From, TryFrom};
141 use core::future::Future;
142 use core::hash::{Hash, Hasher};
143 #[cfg(not(no_global_oom_handling))]
144 use core::iter::FromIterator;
145 use core::iter::{FusedIterator, Iterator};
146 use core::marker::{Destruct, Unpin, Unsize};
149 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
152 use core::ptr::{self, Unique};
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 #[unstable(feature = "thin_box", issue = "92791")]
167 pub use thin::ThinBox;
171 /// A pointer type for heap allocation.
173 /// See the [module-level documentation](../../std/boxed/index.html) for more.
174 #[lang = "owned_box"]
176 #[stable(feature = "rust1", since = "1.0.0")]
177 // The declaration of the `Box` struct must be kept in sync with the
178 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
179 // on `box_free` for more details.
182 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
186 /// Allocates memory on the heap and then places `x` into it.
188 /// This doesn't actually allocate if `T` is zero-sized.
193 /// let five = Box::new(5);
195 #[cfg(not(no_global_oom_handling))]
197 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn new(x: T) -> Self {
203 /// Constructs a new box with uninitialized contents.
208 /// #![feature(new_uninit)]
210 /// let mut five = Box::<u32>::new_uninit();
212 /// let five = unsafe {
213 /// // Deferred initialization:
214 /// five.as_mut_ptr().write(5);
216 /// five.assume_init()
219 /// assert_eq!(*five, 5)
221 #[cfg(not(no_global_oom_handling))]
222 #[unstable(feature = "new_uninit", issue = "63291")]
225 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
226 Self::new_uninit_in(Global)
229 /// Constructs a new `Box` with uninitialized contents, with the memory
230 /// being filled with `0` bytes.
232 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
238 /// #![feature(new_uninit)]
240 /// let zero = Box::<u32>::new_zeroed();
241 /// let zero = unsafe { zero.assume_init() };
243 /// assert_eq!(*zero, 0)
246 /// [zeroed]: mem::MaybeUninit::zeroed
247 #[cfg(not(no_global_oom_handling))]
249 #[unstable(feature = "new_uninit", issue = "63291")]
251 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
252 Self::new_zeroed_in(Global)
255 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
256 /// `x` will be pinned in memory and unable to be moved.
257 #[cfg(not(no_global_oom_handling))]
258 #[stable(feature = "pin", since = "1.33.0")]
261 pub fn pin(x: T) -> Pin<Box<T>> {
265 /// Allocates memory on the heap then places `x` into it,
266 /// returning an error if the allocation fails
268 /// This doesn't actually allocate if `T` is zero-sized.
273 /// #![feature(allocator_api)]
275 /// let five = Box::try_new(5)?;
276 /// # Ok::<(), std::alloc::AllocError>(())
278 #[unstable(feature = "allocator_api", issue = "32838")]
280 pub fn try_new(x: T) -> Result<Self, AllocError> {
281 Self::try_new_in(x, Global)
284 /// Constructs a new box with uninitialized contents on the heap,
285 /// returning an error if the allocation fails
290 /// #![feature(allocator_api, new_uninit)]
292 /// let mut five = Box::<u32>::try_new_uninit()?;
294 /// let five = unsafe {
295 /// // Deferred initialization:
296 /// five.as_mut_ptr().write(5);
298 /// five.assume_init()
301 /// assert_eq!(*five, 5);
302 /// # Ok::<(), std::alloc::AllocError>(())
304 #[unstable(feature = "allocator_api", issue = "32838")]
305 // #[unstable(feature = "new_uninit", issue = "63291")]
307 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
308 Box::try_new_uninit_in(Global)
311 /// Constructs a new `Box` with uninitialized contents, with the memory
312 /// being filled with `0` bytes on the heap
314 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
320 /// #![feature(allocator_api, new_uninit)]
322 /// let zero = Box::<u32>::try_new_zeroed()?;
323 /// let zero = unsafe { zero.assume_init() };
325 /// assert_eq!(*zero, 0);
326 /// # Ok::<(), std::alloc::AllocError>(())
329 /// [zeroed]: mem::MaybeUninit::zeroed
330 #[unstable(feature = "allocator_api", issue = "32838")]
331 // #[unstable(feature = "new_uninit", issue = "63291")]
333 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
334 Box::try_new_zeroed_in(Global)
338 impl<T, A: Allocator> Box<T, A> {
339 /// Allocates memory in the given allocator then places `x` into it.
341 /// This doesn't actually allocate if `T` is zero-sized.
346 /// #![feature(allocator_api)]
348 /// use std::alloc::System;
350 /// let five = Box::new_in(5, System);
352 #[cfg(not(no_global_oom_handling))]
353 #[unstable(feature = "allocator_api", issue = "32838")]
354 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
357 pub const fn new_in(x: T, alloc: A) -> Self
359 A: ~const Allocator + ~const Destruct,
361 let mut boxed = Self::new_uninit_in(alloc);
363 boxed.as_mut_ptr().write(x);
368 /// Allocates memory in the given allocator then places `x` into it,
369 /// returning an error if the allocation fails
371 /// This doesn't actually allocate if `T` is zero-sized.
376 /// #![feature(allocator_api)]
378 /// use std::alloc::System;
380 /// let five = Box::try_new_in(5, System)?;
381 /// # Ok::<(), std::alloc::AllocError>(())
383 #[unstable(feature = "allocator_api", issue = "32838")]
384 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
386 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
389 A: ~const Allocator + ~const Destruct,
391 let mut boxed = Self::try_new_uninit_in(alloc)?;
393 boxed.as_mut_ptr().write(x);
394 Ok(boxed.assume_init())
398 /// Constructs a new box with uninitialized contents in the provided allocator.
403 /// #![feature(allocator_api, new_uninit)]
405 /// use std::alloc::System;
407 /// let mut five = Box::<u32, _>::new_uninit_in(System);
409 /// let five = unsafe {
410 /// // Deferred initialization:
411 /// five.as_mut_ptr().write(5);
413 /// five.assume_init()
416 /// assert_eq!(*five, 5)
418 #[unstable(feature = "allocator_api", issue = "32838")]
419 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
420 #[cfg(not(no_global_oom_handling))]
422 // #[unstable(feature = "new_uninit", issue = "63291")]
423 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
425 A: ~const Allocator + ~const Destruct,
427 let layout = Layout::new::<mem::MaybeUninit<T>>();
428 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
429 // That would make code size bigger.
430 match Box::try_new_uninit_in(alloc) {
432 Err(_) => handle_alloc_error(layout),
436 /// Constructs a new box with uninitialized contents in the provided allocator,
437 /// returning an error if the allocation fails
442 /// #![feature(allocator_api, new_uninit)]
444 /// use std::alloc::System;
446 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
448 /// let five = unsafe {
449 /// // Deferred initialization:
450 /// five.as_mut_ptr().write(5);
452 /// five.assume_init()
455 /// assert_eq!(*five, 5);
456 /// # Ok::<(), std::alloc::AllocError>(())
458 #[unstable(feature = "allocator_api", issue = "32838")]
459 // #[unstable(feature = "new_uninit", issue = "63291")]
460 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
461 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
463 A: ~const Allocator + ~const Destruct,
465 let layout = Layout::new::<mem::MaybeUninit<T>>();
466 let ptr = alloc.allocate(layout)?.cast();
467 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
470 /// Constructs a new `Box` with uninitialized contents, with the memory
471 /// being filled with `0` bytes in the provided allocator.
473 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
479 /// #![feature(allocator_api, new_uninit)]
481 /// use std::alloc::System;
483 /// let zero = Box::<u32, _>::new_zeroed_in(System);
484 /// let zero = unsafe { zero.assume_init() };
486 /// assert_eq!(*zero, 0)
489 /// [zeroed]: mem::MaybeUninit::zeroed
490 #[unstable(feature = "allocator_api", issue = "32838")]
491 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
492 #[cfg(not(no_global_oom_handling))]
493 // #[unstable(feature = "new_uninit", issue = "63291")]
495 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
497 A: ~const Allocator + ~const Destruct,
499 let layout = Layout::new::<mem::MaybeUninit<T>>();
500 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
501 // That would make code size bigger.
502 match Box::try_new_zeroed_in(alloc) {
504 Err(_) => handle_alloc_error(layout),
508 /// Constructs a new `Box` with uninitialized contents, with the memory
509 /// being filled with `0` bytes in the provided allocator,
510 /// returning an error if the allocation fails,
512 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
518 /// #![feature(allocator_api, new_uninit)]
520 /// use std::alloc::System;
522 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
523 /// let zero = unsafe { zero.assume_init() };
525 /// assert_eq!(*zero, 0);
526 /// # Ok::<(), std::alloc::AllocError>(())
529 /// [zeroed]: mem::MaybeUninit::zeroed
530 #[unstable(feature = "allocator_api", issue = "32838")]
531 // #[unstable(feature = "new_uninit", issue = "63291")]
532 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
533 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
535 A: ~const Allocator + ~const Destruct,
537 let layout = Layout::new::<mem::MaybeUninit<T>>();
538 let ptr = alloc.allocate_zeroed(layout)?.cast();
539 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
542 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
543 /// `x` will be pinned in memory and unable to be moved.
544 #[cfg(not(no_global_oom_handling))]
545 #[unstable(feature = "allocator_api", issue = "32838")]
546 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
549 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
551 A: 'static + ~const Allocator + ~const Destruct,
553 Self::into_pin(Self::new_in(x, alloc))
556 /// Converts a `Box<T>` into a `Box<[T]>`
558 /// This conversion does not allocate on the heap and happens in place.
559 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
560 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
561 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
562 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
563 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
566 /// Consumes the `Box`, returning the wrapped value.
571 /// #![feature(box_into_inner)]
573 /// let c = Box::new(5);
575 /// assert_eq!(Box::into_inner(c), 5);
577 #[unstable(feature = "box_into_inner", issue = "80437")]
578 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
580 pub const fn into_inner(boxed: Self) -> T
582 Self: ~const Destruct,
589 /// Constructs a new boxed slice with uninitialized contents.
594 /// #![feature(new_uninit)]
596 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
598 /// let values = unsafe {
599 /// // Deferred initialization:
600 /// values[0].as_mut_ptr().write(1);
601 /// values[1].as_mut_ptr().write(2);
602 /// values[2].as_mut_ptr().write(3);
604 /// values.assume_init()
607 /// assert_eq!(*values, [1, 2, 3])
609 #[cfg(not(no_global_oom_handling))]
610 #[unstable(feature = "new_uninit", issue = "63291")]
612 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
613 unsafe { RawVec::with_capacity(len).into_box(len) }
616 /// Constructs a new boxed slice with uninitialized contents, with the memory
617 /// being filled with `0` bytes.
619 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
625 /// #![feature(new_uninit)]
627 /// let values = Box::<[u32]>::new_zeroed_slice(3);
628 /// let values = unsafe { values.assume_init() };
630 /// assert_eq!(*values, [0, 0, 0])
633 /// [zeroed]: mem::MaybeUninit::zeroed
634 #[cfg(not(no_global_oom_handling))]
635 #[unstable(feature = "new_uninit", issue = "63291")]
637 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
638 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
641 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
642 /// the allocation fails
647 /// #![feature(allocator_api, new_uninit)]
649 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
650 /// let values = unsafe {
651 /// // Deferred initialization:
652 /// values[0].as_mut_ptr().write(1);
653 /// values[1].as_mut_ptr().write(2);
654 /// values[2].as_mut_ptr().write(3);
655 /// values.assume_init()
658 /// assert_eq!(*values, [1, 2, 3]);
659 /// # Ok::<(), std::alloc::AllocError>(())
661 #[unstable(feature = "allocator_api", issue = "32838")]
663 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
665 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
667 Err(_) => return Err(AllocError),
669 let ptr = Global.allocate(layout)?;
670 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
674 /// Constructs a new boxed slice with uninitialized contents, with the memory
675 /// being filled with `0` bytes. Returns an error if the allocation fails
677 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
683 /// #![feature(allocator_api, new_uninit)]
685 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
686 /// let values = unsafe { values.assume_init() };
688 /// assert_eq!(*values, [0, 0, 0]);
689 /// # Ok::<(), std::alloc::AllocError>(())
692 /// [zeroed]: mem::MaybeUninit::zeroed
693 #[unstable(feature = "allocator_api", issue = "32838")]
695 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
697 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
699 Err(_) => return Err(AllocError),
701 let ptr = Global.allocate_zeroed(layout)?;
702 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
707 impl<T, A: Allocator> Box<[T], A> {
708 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
713 /// #![feature(allocator_api, new_uninit)]
715 /// use std::alloc::System;
717 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
719 /// let values = unsafe {
720 /// // Deferred initialization:
721 /// values[0].as_mut_ptr().write(1);
722 /// values[1].as_mut_ptr().write(2);
723 /// values[2].as_mut_ptr().write(3);
725 /// values.assume_init()
728 /// assert_eq!(*values, [1, 2, 3])
730 #[cfg(not(no_global_oom_handling))]
731 #[unstable(feature = "allocator_api", issue = "32838")]
732 // #[unstable(feature = "new_uninit", issue = "63291")]
734 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
735 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
738 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
739 /// with the memory being filled with `0` bytes.
741 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
747 /// #![feature(allocator_api, new_uninit)]
749 /// use std::alloc::System;
751 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
752 /// let values = unsafe { values.assume_init() };
754 /// assert_eq!(*values, [0, 0, 0])
757 /// [zeroed]: mem::MaybeUninit::zeroed
758 #[cfg(not(no_global_oom_handling))]
759 #[unstable(feature = "allocator_api", issue = "32838")]
760 // #[unstable(feature = "new_uninit", issue = "63291")]
762 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
763 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
767 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
768 /// Converts to `Box<T, A>`.
772 /// As with [`MaybeUninit::assume_init`],
773 /// it is up to the caller to guarantee that the value
774 /// really is in an initialized state.
775 /// Calling this when the content is not yet fully initialized
776 /// causes immediate undefined behavior.
778 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
783 /// #![feature(new_uninit)]
785 /// let mut five = Box::<u32>::new_uninit();
787 /// let five: Box<u32> = unsafe {
788 /// // Deferred initialization:
789 /// five.as_mut_ptr().write(5);
791 /// five.assume_init()
794 /// assert_eq!(*five, 5)
796 #[unstable(feature = "new_uninit", issue = "63291")]
797 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
799 pub const unsafe fn assume_init(self) -> Box<T, A> {
800 let (raw, alloc) = Box::into_raw_with_allocator(self);
801 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
804 /// Writes the value and converts to `Box<T, A>`.
806 /// This method converts the box similarly to [`Box::assume_init`] but
807 /// writes `value` into it before conversion thus guaranteeing safety.
808 /// In some scenarios use of this method may improve performance because
809 /// the compiler may be able to optimize copying from stack.
814 /// #![feature(new_uninit)]
816 /// let big_box = Box::<[usize; 1024]>::new_uninit();
818 /// let mut array = [0; 1024];
819 /// for (i, place) in array.iter_mut().enumerate() {
823 /// // The optimizer may be able to elide this copy, so previous code writes
824 /// // to heap directly.
825 /// let big_box = Box::write(big_box, array);
827 /// for (i, x) in big_box.iter().enumerate() {
828 /// assert_eq!(*x, i);
831 #[unstable(feature = "new_uninit", issue = "63291")]
832 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
834 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
836 (*boxed).write(value);
842 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
843 /// Converts to `Box<[T], A>`.
847 /// As with [`MaybeUninit::assume_init`],
848 /// it is up to the caller to guarantee that the values
849 /// really are in an initialized state.
850 /// Calling this when the content is not yet fully initialized
851 /// causes immediate undefined behavior.
853 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
858 /// #![feature(new_uninit)]
860 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
862 /// let values = unsafe {
863 /// // Deferred initialization:
864 /// values[0].as_mut_ptr().write(1);
865 /// values[1].as_mut_ptr().write(2);
866 /// values[2].as_mut_ptr().write(3);
868 /// values.assume_init()
871 /// assert_eq!(*values, [1, 2, 3])
873 #[unstable(feature = "new_uninit", issue = "63291")]
875 pub unsafe fn assume_init(self) -> Box<[T], A> {
876 let (raw, alloc) = Box::into_raw_with_allocator(self);
877 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
881 impl<T: ?Sized> Box<T> {
882 /// Constructs a box from a raw pointer.
884 /// After calling this function, the raw pointer is owned by the
885 /// resulting `Box`. Specifically, the `Box` destructor will call
886 /// the destructor of `T` and free the allocated memory. For this
887 /// to be safe, the memory must have been allocated in accordance
888 /// with the [memory layout] used by `Box` .
892 /// This function is unsafe because improper use may lead to
893 /// memory problems. For example, a double-free may occur if the
894 /// function is called twice on the same raw pointer.
896 /// The safety conditions are described in the [memory layout] section.
900 /// Recreate a `Box` which was previously converted to a raw pointer
901 /// using [`Box::into_raw`]:
903 /// let x = Box::new(5);
904 /// let ptr = Box::into_raw(x);
905 /// let x = unsafe { Box::from_raw(ptr) };
907 /// Manually create a `Box` from scratch by using the global allocator:
909 /// use std::alloc::{alloc, Layout};
912 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
913 /// // In general .write is required to avoid attempting to destruct
914 /// // the (uninitialized) previous contents of `ptr`, though for this
915 /// // simple example `*ptr = 5` would have worked as well.
917 /// let x = Box::from_raw(ptr);
921 /// [memory layout]: self#memory-layout
922 /// [`Layout`]: crate::Layout
923 #[stable(feature = "box_raw", since = "1.4.0")]
925 pub unsafe fn from_raw(raw: *mut T) -> Self {
926 unsafe { Self::from_raw_in(raw, Global) }
930 impl<T: ?Sized, A: Allocator> Box<T, A> {
931 /// Constructs a box from a raw pointer in the given allocator.
933 /// After calling this function, the raw pointer is owned by the
934 /// resulting `Box`. Specifically, the `Box` destructor will call
935 /// the destructor of `T` and free the allocated memory. For this
936 /// to be safe, the memory must have been allocated in accordance
937 /// with the [memory layout] used by `Box` .
941 /// This function is unsafe because improper use may lead to
942 /// memory problems. For example, a double-free may occur if the
943 /// function is called twice on the same raw pointer.
948 /// Recreate a `Box` which was previously converted to a raw pointer
949 /// using [`Box::into_raw_with_allocator`]:
951 /// #![feature(allocator_api)]
953 /// use std::alloc::System;
955 /// let x = Box::new_in(5, System);
956 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
957 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
959 /// Manually create a `Box` from scratch by using the system allocator:
961 /// #![feature(allocator_api, slice_ptr_get)]
963 /// use std::alloc::{Allocator, Layout, System};
966 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
967 /// // In general .write is required to avoid attempting to destruct
968 /// // the (uninitialized) previous contents of `ptr`, though for this
969 /// // simple example `*ptr = 5` would have worked as well.
971 /// let x = Box::from_raw_in(ptr, System);
973 /// # Ok::<(), std::alloc::AllocError>(())
976 /// [memory layout]: self#memory-layout
977 /// [`Layout`]: crate::Layout
978 #[unstable(feature = "allocator_api", issue = "32838")]
979 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
981 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
982 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
985 /// Consumes the `Box`, returning a wrapped raw pointer.
987 /// The pointer will be properly aligned and non-null.
989 /// After calling this function, the caller is responsible for the
990 /// memory previously managed by the `Box`. In particular, the
991 /// caller should properly destroy `T` and release the memory, taking
992 /// into account the [memory layout] used by `Box`. The easiest way to
993 /// do this is to convert the raw pointer back into a `Box` with the
994 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
997 /// Note: this is an associated function, which means that you have
998 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
999 /// is so that there is no conflict with a method on the inner type.
1002 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1003 /// for automatic cleanup:
1005 /// let x = Box::new(String::from("Hello"));
1006 /// let ptr = Box::into_raw(x);
1007 /// let x = unsafe { Box::from_raw(ptr) };
1009 /// Manual cleanup by explicitly running the destructor and deallocating
1012 /// use std::alloc::{dealloc, Layout};
1015 /// let x = Box::new(String::from("Hello"));
1016 /// let p = Box::into_raw(x);
1018 /// ptr::drop_in_place(p);
1019 /// dealloc(p as *mut u8, Layout::new::<String>());
1023 /// [memory layout]: self#memory-layout
1024 #[stable(feature = "box_raw", since = "1.4.0")]
1026 pub fn into_raw(b: Self) -> *mut T {
1027 Self::into_raw_with_allocator(b).0
1030 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1032 /// The pointer will be properly aligned and non-null.
1034 /// After calling this function, the caller is responsible for the
1035 /// memory previously managed by the `Box`. In particular, the
1036 /// caller should properly destroy `T` and release the memory, taking
1037 /// into account the [memory layout] used by `Box`. The easiest way to
1038 /// do this is to convert the raw pointer back into a `Box` with the
1039 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1042 /// Note: this is an associated function, which means that you have
1043 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1044 /// is so that there is no conflict with a method on the inner type.
1047 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1048 /// for automatic cleanup:
1050 /// #![feature(allocator_api)]
1052 /// use std::alloc::System;
1054 /// let x = Box::new_in(String::from("Hello"), System);
1055 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1056 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1058 /// Manual cleanup by explicitly running the destructor and deallocating
1061 /// #![feature(allocator_api)]
1063 /// use std::alloc::{Allocator, Layout, System};
1064 /// use std::ptr::{self, NonNull};
1066 /// let x = Box::new_in(String::from("Hello"), System);
1067 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1069 /// ptr::drop_in_place(ptr);
1070 /// let non_null = NonNull::new_unchecked(ptr);
1071 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1075 /// [memory layout]: self#memory-layout
1076 #[unstable(feature = "allocator_api", issue = "32838")]
1077 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1079 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1080 let (leaked, alloc) = Box::into_unique(b);
1081 (leaked.as_ptr(), alloc)
1085 feature = "ptr_internals",
1087 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1089 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1092 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1093 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1094 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1095 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1096 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1097 // behaves correctly.
1098 let alloc = unsafe { ptr::read(&b.1) };
1099 (Unique::from(Box::leak(b)), alloc)
1102 /// Returns a reference to the underlying allocator.
1104 /// Note: this is an associated function, which means that you have
1105 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1106 /// is so that there is no conflict with a method on the inner type.
1107 #[unstable(feature = "allocator_api", issue = "32838")]
1108 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1110 pub const fn allocator(b: &Self) -> &A {
1114 /// Consumes and leaks the `Box`, returning a mutable reference,
1115 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1116 /// `'a`. If the type has only static references, or none at all, then this
1117 /// may be chosen to be `'static`.
1119 /// This function is mainly useful for data that lives for the remainder of
1120 /// the program's life. Dropping the returned reference will cause a memory
1121 /// leak. If this is not acceptable, the reference should first be wrapped
1122 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1123 /// then be dropped which will properly destroy `T` and release the
1124 /// allocated memory.
1126 /// Note: this is an associated function, which means that you have
1127 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1128 /// is so that there is no conflict with a method on the inner type.
1135 /// let x = Box::new(41);
1136 /// let static_ref: &'static mut usize = Box::leak(x);
1137 /// *static_ref += 1;
1138 /// assert_eq!(*static_ref, 42);
1144 /// let x = vec![1, 2, 3].into_boxed_slice();
1145 /// let static_ref = Box::leak(x);
1146 /// static_ref[0] = 4;
1147 /// assert_eq!(*static_ref, [4, 2, 3]);
1149 #[stable(feature = "box_leak", since = "1.26.0")]
1150 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1152 pub const fn leak<'a>(b: Self) -> &'a mut T
1156 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1159 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1161 /// This conversion does not allocate on the heap and happens in place.
1163 /// This is also available via [`From`].
1164 #[unstable(feature = "box_into_pin", issue = "62370")]
1165 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1166 pub const fn into_pin(boxed: Self) -> Pin<Self>
1170 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1171 // when `T: !Unpin`, so it's safe to pin it directly without any
1172 // additional requirements.
1173 unsafe { Pin::new_unchecked(boxed) }
1177 #[stable(feature = "rust1", since = "1.0.0")]
1178 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1179 fn drop(&mut self) {
1180 // FIXME: Do nothing, drop is currently performed by compiler.
1184 #[cfg(not(no_global_oom_handling))]
1185 #[stable(feature = "rust1", since = "1.0.0")]
1186 impl<T: Default> Default for Box<T> {
1187 /// Creates a `Box<T>`, with the `Default` value for T.
1188 fn default() -> Self {
1193 #[cfg(not(no_global_oom_handling))]
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1196 impl<T> const Default for Box<[T]> {
1197 fn default() -> Self {
1198 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1203 #[cfg(not(no_global_oom_handling))]
1204 #[stable(feature = "default_box_extra", since = "1.17.0")]
1205 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1206 impl const Default for Box<str> {
1207 fn default() -> Self {
1208 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1209 let ptr: Unique<str> = unsafe {
1210 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1211 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1217 #[cfg(not(no_global_oom_handling))]
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1220 /// Returns a new box with a `clone()` of this box's contents.
1225 /// let x = Box::new(5);
1226 /// let y = x.clone();
1228 /// // The value is the same
1229 /// assert_eq!(x, y);
1231 /// // But they are unique objects
1232 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1235 fn clone(&self) -> Self {
1236 // Pre-allocate memory to allow writing the cloned value directly.
1237 let mut boxed = Self::new_uninit_in(self.1.clone());
1239 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1244 /// Copies `source`'s contents into `self` without creating a new allocation.
1249 /// let x = Box::new(5);
1250 /// let mut y = Box::new(10);
1251 /// let yp: *const i32 = &*y;
1253 /// y.clone_from(&x);
1255 /// // The value is the same
1256 /// assert_eq!(x, y);
1258 /// // And no allocation occurred
1259 /// assert_eq!(yp, &*y);
1262 fn clone_from(&mut self, source: &Self) {
1263 (**self).clone_from(&(**source));
1267 #[cfg(not(no_global_oom_handling))]
1268 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1269 impl Clone for Box<str> {
1270 fn clone(&self) -> Self {
1271 // this makes a copy of the data
1272 let buf: Box<[u8]> = self.as_bytes().into();
1273 unsafe { from_boxed_utf8_unchecked(buf) }
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1280 fn eq(&self, other: &Self) -> bool {
1281 PartialEq::eq(&**self, &**other)
1284 fn ne(&self, other: &Self) -> bool {
1285 PartialEq::ne(&**self, &**other)
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1291 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1292 PartialOrd::partial_cmp(&**self, &**other)
1295 fn lt(&self, other: &Self) -> bool {
1296 PartialOrd::lt(&**self, &**other)
1299 fn le(&self, other: &Self) -> bool {
1300 PartialOrd::le(&**self, &**other)
1303 fn ge(&self, other: &Self) -> bool {
1304 PartialOrd::ge(&**self, &**other)
1307 fn gt(&self, other: &Self) -> bool {
1308 PartialOrd::gt(&**self, &**other)
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1314 fn cmp(&self, other: &Self) -> Ordering {
1315 Ord::cmp(&**self, &**other)
1318 #[stable(feature = "rust1", since = "1.0.0")]
1319 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1323 fn hash<H: Hasher>(&self, state: &mut H) {
1324 (**self).hash(state);
1328 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1329 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1330 fn finish(&self) -> u64 {
1333 fn write(&mut self, bytes: &[u8]) {
1334 (**self).write(bytes)
1336 fn write_u8(&mut self, i: u8) {
1337 (**self).write_u8(i)
1339 fn write_u16(&mut self, i: u16) {
1340 (**self).write_u16(i)
1342 fn write_u32(&mut self, i: u32) {
1343 (**self).write_u32(i)
1345 fn write_u64(&mut self, i: u64) {
1346 (**self).write_u64(i)
1348 fn write_u128(&mut self, i: u128) {
1349 (**self).write_u128(i)
1351 fn write_usize(&mut self, i: usize) {
1352 (**self).write_usize(i)
1354 fn write_i8(&mut self, i: i8) {
1355 (**self).write_i8(i)
1357 fn write_i16(&mut self, i: i16) {
1358 (**self).write_i16(i)
1360 fn write_i32(&mut self, i: i32) {
1361 (**self).write_i32(i)
1363 fn write_i64(&mut self, i: i64) {
1364 (**self).write_i64(i)
1366 fn write_i128(&mut self, i: i128) {
1367 (**self).write_i128(i)
1369 fn write_isize(&mut self, i: isize) {
1370 (**self).write_isize(i)
1372 fn write_length_prefix(&mut self, len: usize) {
1373 (**self).write_length_prefix(len)
1375 fn write_str(&mut self, s: &str) {
1376 (**self).write_str(s)
1380 #[cfg(not(no_global_oom_handling))]
1381 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1382 impl<T> From<T> for Box<T> {
1383 /// Converts a `T` into a `Box<T>`
1385 /// The conversion allocates on the heap and moves `t`
1386 /// from the stack into it.
1392 /// let boxed = Box::new(5);
1394 /// assert_eq!(Box::from(x), boxed);
1396 fn from(t: T) -> Self {
1401 #[stable(feature = "pin", since = "1.33.0")]
1402 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1403 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1407 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1409 /// This conversion does not allocate on the heap and happens in place.
1410 fn from(boxed: Box<T, A>) -> Self {
1411 Box::into_pin(boxed)
1415 #[cfg(not(no_global_oom_handling))]
1416 #[stable(feature = "box_from_slice", since = "1.17.0")]
1417 impl<T: Copy> From<&[T]> for Box<[T]> {
1418 /// Converts a `&[T]` into a `Box<[T]>`
1420 /// This conversion allocates on the heap
1421 /// and performs a copy of `slice`.
1425 /// // create a &[u8] which will be used to create a Box<[u8]>
1426 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1427 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1429 /// println!("{boxed_slice:?}");
1431 fn from(slice: &[T]) -> Box<[T]> {
1432 let len = slice.len();
1433 let buf = RawVec::with_capacity(len);
1435 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1436 buf.into_box(slice.len()).assume_init()
1441 #[cfg(not(no_global_oom_handling))]
1442 #[stable(feature = "box_from_cow", since = "1.45.0")]
1443 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1444 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1446 /// When `cow` is the `Cow::Borrowed` variant, this
1447 /// conversion allocates on the heap and copies the
1448 /// underlying slice. Otherwise, it will try to reuse the owned
1449 /// `Vec`'s allocation.
1451 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1453 Cow::Borrowed(slice) => Box::from(slice),
1454 Cow::Owned(slice) => Box::from(slice),
1459 #[cfg(not(no_global_oom_handling))]
1460 #[stable(feature = "box_from_slice", since = "1.17.0")]
1461 impl From<&str> for Box<str> {
1462 /// Converts a `&str` into a `Box<str>`
1464 /// This conversion allocates on the heap
1465 /// and performs a copy of `s`.
1470 /// let boxed: Box<str> = Box::from("hello");
1471 /// println!("{boxed}");
1474 fn from(s: &str) -> Box<str> {
1475 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1479 #[cfg(not(no_global_oom_handling))]
1480 #[stable(feature = "box_from_cow", since = "1.45.0")]
1481 impl From<Cow<'_, str>> for Box<str> {
1482 /// Converts a `Cow<'_, str>` into a `Box<str>`
1484 /// When `cow` is the `Cow::Borrowed` variant, this
1485 /// conversion allocates on the heap and copies the
1486 /// underlying `str`. Otherwise, it will try to reuse the owned
1487 /// `String`'s allocation.
1492 /// use std::borrow::Cow;
1494 /// let unboxed = Cow::Borrowed("hello");
1495 /// let boxed: Box<str> = Box::from(unboxed);
1496 /// println!("{boxed}");
1500 /// # use std::borrow::Cow;
1501 /// let unboxed = Cow::Owned("hello".to_string());
1502 /// let boxed: Box<str> = Box::from(unboxed);
1503 /// println!("{boxed}");
1506 fn from(cow: Cow<'_, str>) -> Box<str> {
1508 Cow::Borrowed(s) => Box::from(s),
1509 Cow::Owned(s) => Box::from(s),
1514 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1515 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1516 /// Converts a `Box<str>` into a `Box<[u8]>`
1518 /// This conversion does not allocate on the heap and happens in place.
1522 /// // create a Box<str> which will be used to create a Box<[u8]>
1523 /// let boxed: Box<str> = Box::from("hello");
1524 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1526 /// // create a &[u8] which will be used to create a Box<[u8]>
1527 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1528 /// let boxed_slice = Box::from(slice);
1530 /// assert_eq!(boxed_slice, boxed_str);
1533 fn from(s: Box<str, A>) -> Self {
1534 let (raw, alloc) = Box::into_raw_with_allocator(s);
1535 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1539 #[cfg(not(no_global_oom_handling))]
1540 #[stable(feature = "box_from_array", since = "1.45.0")]
1541 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1542 /// Converts a `[T; N]` into a `Box<[T]>`
1544 /// This conversion moves the array to newly heap-allocated memory.
1549 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1550 /// println!("{boxed:?}");
1552 fn from(array: [T; N]) -> Box<[T]> {
1557 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1558 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1559 type Error = Box<[T]>;
1561 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1563 /// The conversion occurs in-place and does not require a
1564 /// new memory allocation.
1568 /// Returns the old `Box<[T]>` in the `Err` variant if
1569 /// `boxed_slice.len()` does not equal `N`.
1570 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1571 if boxed_slice.len() == N {
1572 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1579 impl<A: Allocator> Box<dyn Any, A> {
1580 /// Attempt to downcast the box to a concrete type.
1585 /// use std::any::Any;
1587 /// fn print_if_string(value: Box<dyn Any>) {
1588 /// if let Ok(string) = value.downcast::<String>() {
1589 /// println!("String ({}): {}", string.len(), string);
1593 /// let my_string = "Hello World".to_string();
1594 /// print_if_string(Box::new(my_string));
1595 /// print_if_string(Box::new(0i8));
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1600 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1603 /// Downcasts the box to a concrete type.
1605 /// For a safe alternative see [`downcast`].
1610 /// #![feature(downcast_unchecked)]
1612 /// use std::any::Any;
1614 /// let x: Box<dyn Any> = Box::new(1_usize);
1617 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1623 /// The contained value must be of type `T`. Calling this method
1624 /// with the incorrect type is *undefined behavior*.
1626 /// [`downcast`]: Self::downcast
1628 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1629 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1630 debug_assert!(self.is::<T>());
1632 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1633 Box::from_raw_in(raw as *mut T, alloc)
1638 impl<A: Allocator> Box<dyn Any + Send, A> {
1639 /// Attempt to downcast the box to a concrete type.
1644 /// use std::any::Any;
1646 /// fn print_if_string(value: Box<dyn Any + Send>) {
1647 /// if let Ok(string) = value.downcast::<String>() {
1648 /// println!("String ({}): {}", string.len(), string);
1652 /// let my_string = "Hello World".to_string();
1653 /// print_if_string(Box::new(my_string));
1654 /// print_if_string(Box::new(0i8));
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1659 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1662 /// Downcasts the box to a concrete type.
1664 /// For a safe alternative see [`downcast`].
1669 /// #![feature(downcast_unchecked)]
1671 /// use std::any::Any;
1673 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1676 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1682 /// The contained value must be of type `T`. Calling this method
1683 /// with the incorrect type is *undefined behavior*.
1685 /// [`downcast`]: Self::downcast
1687 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1688 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1689 debug_assert!(self.is::<T>());
1691 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1692 Box::from_raw_in(raw as *mut T, alloc)
1697 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1698 /// Attempt to downcast the box to a concrete type.
1703 /// use std::any::Any;
1705 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1706 /// if let Ok(string) = value.downcast::<String>() {
1707 /// println!("String ({}): {}", string.len(), string);
1711 /// let my_string = "Hello World".to_string();
1712 /// print_if_string(Box::new(my_string));
1713 /// print_if_string(Box::new(0i8));
1716 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1717 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1718 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1721 /// Downcasts the box to a concrete type.
1723 /// For a safe alternative see [`downcast`].
1728 /// #![feature(downcast_unchecked)]
1730 /// use std::any::Any;
1732 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1735 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1741 /// The contained value must be of type `T`. Calling this method
1742 /// with the incorrect type is *undefined behavior*.
1744 /// [`downcast`]: Self::downcast
1746 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1747 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1748 debug_assert!(self.is::<T>());
1750 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1751 Box::into_raw_with_allocator(self);
1752 Box::from_raw_in(raw as *mut T, alloc)
1757 #[stable(feature = "rust1", since = "1.0.0")]
1758 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1759 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1760 fmt::Display::fmt(&**self, f)
1764 #[stable(feature = "rust1", since = "1.0.0")]
1765 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1766 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1767 fmt::Debug::fmt(&**self, f)
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774 // It's not possible to extract the inner Uniq directly from the Box,
1775 // instead we cast it to a *const which aliases the Unique
1776 let ptr: *const T = &**self;
1777 fmt::Pointer::fmt(&ptr, f)
1781 #[stable(feature = "rust1", since = "1.0.0")]
1782 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1783 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1786 fn deref(&self) -> &T {
1791 #[stable(feature = "rust1", since = "1.0.0")]
1792 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1793 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1794 fn deref_mut(&mut self) -> &mut T {
1799 #[unstable(feature = "receiver_trait", issue = "none")]
1800 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1804 type Item = I::Item;
1805 fn next(&mut self) -> Option<I::Item> {
1808 fn size_hint(&self) -> (usize, Option<usize>) {
1809 (**self).size_hint()
1811 fn nth(&mut self, n: usize) -> Option<I::Item> {
1814 fn last(self) -> Option<I::Item> {
1821 fn last(self) -> Option<Self::Item>;
1824 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1825 type Item = I::Item;
1826 default fn last(self) -> Option<I::Item> {
1828 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1832 self.fold(None, some)
1836 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1837 /// instead of the default.
1838 #[stable(feature = "rust1", since = "1.0.0")]
1839 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1840 fn last(self) -> Option<I::Item> {
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1847 fn next_back(&mut self) -> Option<I::Item> {
1848 (**self).next_back()
1850 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1851 (**self).nth_back(n)
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1856 fn len(&self) -> usize {
1859 fn is_empty(&self) -> bool {
1864 #[stable(feature = "fused", since = "1.26.0")]
1865 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1867 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1868 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1869 type Output = <F as FnOnce<Args>>::Output;
1871 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1872 <F as FnOnce<Args>>::call_once(*self, args)
1876 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1877 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1878 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1879 <F as FnMut<Args>>::call_mut(self, args)
1883 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1884 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1885 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1886 <F as Fn<Args>>::call(self, args)
1890 #[unstable(feature = "coerce_unsized", issue = "27732")]
1891 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1893 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1894 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1896 #[cfg(not(no_global_oom_handling))]
1897 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1898 impl<I> FromIterator<I> for Box<[I]> {
1899 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1900 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1904 #[cfg(not(no_global_oom_handling))]
1905 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1906 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1907 fn clone(&self) -> Self {
1908 let alloc = Box::allocator(self).clone();
1909 self.to_vec_in(alloc).into_boxed_slice()
1912 fn clone_from(&mut self, other: &Self) {
1913 if self.len() == other.len() {
1914 self.clone_from_slice(&other);
1916 *self = other.clone();
1921 #[stable(feature = "box_borrow", since = "1.1.0")]
1922 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1923 fn borrow(&self) -> &T {
1928 #[stable(feature = "box_borrow", since = "1.1.0")]
1929 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1930 fn borrow_mut(&mut self) -> &mut T {
1935 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1936 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1937 fn as_ref(&self) -> &T {
1942 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1943 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1944 fn as_mut(&mut self) -> &mut T {
1951 * We could have chosen not to add this impl, and instead have written a
1952 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1953 * because Box<T> implements Unpin even when T does not, as a result of
1956 * We chose this API instead of the alternative for a few reasons:
1957 * - Logically, it is helpful to understand pinning in regard to the
1958 * memory region being pointed to. For this reason none of the
1959 * standard library pointer types support projecting through a pin
1960 * (Box<T> is the only pointer type in std for which this would be
1962 * - It is in practice very useful to have Box<T> be unconditionally
1963 * Unpin because of trait objects, for which the structural auto
1964 * trait functionality does not apply (e.g., Box<dyn Foo> would
1965 * otherwise not be Unpin).
1967 * Another type with the same semantics as Box but only a conditional
1968 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1969 * could have a method to project a Pin<T> from it.
1971 #[stable(feature = "pin", since = "1.33.0")]
1972 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1973 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
1975 #[unstable(feature = "generator_trait", issue = "43122")]
1976 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1980 type Yield = G::Yield;
1981 type Return = G::Return;
1983 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1984 G::resume(Pin::new(&mut *self), arg)
1988 #[unstable(feature = "generator_trait", issue = "43122")]
1989 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1993 type Yield = G::Yield;
1994 type Return = G::Return;
1996 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1997 G::resume((*self).as_mut(), arg)
2001 #[stable(feature = "futures_api", since = "1.36.0")]
2002 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2006 type Output = F::Output;
2008 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2009 F::poll(Pin::new(&mut *self), cx)
2013 #[unstable(feature = "async_iterator", issue = "79024")]
2014 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2015 type Item = S::Item;
2017 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2018 Pin::new(&mut **self).poll_next(cx)
2021 fn size_hint(&self) -> (usize, Option<usize>) {
2022 (**self).size_hint()