1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 //! The `Box<T>` 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 //! # Considerations for unsafe code
129 //! **Warning: This section is not normative and is subject to change, possibly
130 //! being relaxed in the future! It is a simplified summary of the rules
131 //! currently implemented in the compiler.**
133 //! The aliasing rules for `Box<T>` are the same as for `&mut T`. `Box<T>`
134 //! asserts uniqueness over its content. Using raw pointers derived from a box
135 //! after that box has been mutated through, moved or borrowed as `&mut T`
136 //! is not allowed. For more guidance on working with box from unsafe code, see
137 //! [rust-lang/unsafe-code-guidelines#326][ucg#326].
140 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
141 //! [ucg#326]: https://github.com/rust-lang/unsafe-code-guidelines/issues/326
142 //! [dereferencing]: core::ops::Deref
143 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
144 //! [`Global`]: crate::alloc::Global
145 //! [`Layout`]: crate::alloc::Layout
146 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
147 //! [valid]: ptr#safety
149 #![stable(feature = "rust1", since = "1.0.0")]
152 use core::async_iter::AsyncIterator;
154 use core::cmp::Ordering;
155 use core::error::Error;
157 use core::future::Future;
158 use core::hash::{Hash, Hasher};
159 use core::iter::FusedIterator;
160 use core::marker::Tuple;
161 use core::marker::Unsize;
162 use core::mem::{self, SizedTypeProperties};
164 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
167 use core::ptr::{self, NonNull, Unique};
168 use core::task::{Context, Poll};
170 #[cfg(not(no_global_oom_handling))]
171 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
172 use crate::alloc::{AllocError, Allocator, Global, Layout};
173 #[cfg(not(no_global_oom_handling))]
174 use crate::borrow::Cow;
175 use crate::raw_vec::RawVec;
176 #[cfg(not(no_global_oom_handling))]
177 use crate::str::from_boxed_utf8_unchecked;
178 #[cfg(not(no_global_oom_handling))]
179 use crate::string::String;
180 #[cfg(not(no_global_oom_handling))]
184 #[unstable(feature = "thin_box", issue = "92791")]
185 pub use thin::ThinBox;
190 /// A pointer type that uniquely owns a heap allocation of type `T`.
192 /// See the [module-level documentation](../../std/boxed/index.html) for more.
193 #[lang = "owned_box"]
195 #[stable(feature = "rust1", since = "1.0.0")]
196 // The declaration of the `Box` struct must be kept in sync with the
197 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
198 // on `box_free` for more details.
201 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
205 /// Allocates memory on the heap and then places `x` into it.
207 /// This doesn't actually allocate if `T` is zero-sized.
212 /// let five = Box::new(5);
214 #[cfg(all(not(no_global_oom_handling)))]
216 #[stable(feature = "rust1", since = "1.0.0")]
218 #[rustc_diagnostic_item = "box_new"]
219 pub fn new(x: T) -> Self {
224 /// Constructs a new box with uninitialized contents.
229 /// #![feature(new_uninit)]
231 /// let mut five = Box::<u32>::new_uninit();
233 /// let five = unsafe {
234 /// // Deferred initialization:
235 /// five.as_mut_ptr().write(5);
237 /// five.assume_init()
240 /// assert_eq!(*five, 5)
242 #[cfg(not(no_global_oom_handling))]
243 #[unstable(feature = "new_uninit", issue = "63291")]
246 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
247 Self::new_uninit_in(Global)
250 /// Constructs a new `Box` with uninitialized contents, with the memory
251 /// being filled with `0` bytes.
253 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
259 /// #![feature(new_uninit)]
261 /// let zero = Box::<u32>::new_zeroed();
262 /// let zero = unsafe { zero.assume_init() };
264 /// assert_eq!(*zero, 0)
267 /// [zeroed]: mem::MaybeUninit::zeroed
268 #[cfg(not(no_global_oom_handling))]
270 #[unstable(feature = "new_uninit", issue = "63291")]
272 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
273 Self::new_zeroed_in(Global)
276 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
277 /// `x` will be pinned in memory and unable to be moved.
279 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
280 /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
281 /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
282 /// construct a (pinned) `Box` in a different way than with [`Box::new`].
283 #[cfg(not(no_global_oom_handling))]
284 #[stable(feature = "pin", since = "1.33.0")]
287 pub fn pin(x: T) -> Pin<Box<T>> {
291 /// Allocates memory on the heap then places `x` into it,
292 /// returning an error if the allocation fails
294 /// This doesn't actually allocate if `T` is zero-sized.
299 /// #![feature(allocator_api)]
301 /// let five = Box::try_new(5)?;
302 /// # Ok::<(), std::alloc::AllocError>(())
304 #[unstable(feature = "allocator_api", issue = "32838")]
306 pub fn try_new(x: T) -> Result<Self, AllocError> {
307 Self::try_new_in(x, Global)
310 /// Constructs a new box with uninitialized contents on the heap,
311 /// returning an error if the allocation fails
316 /// #![feature(allocator_api, new_uninit)]
318 /// let mut five = Box::<u32>::try_new_uninit()?;
320 /// let five = unsafe {
321 /// // Deferred initialization:
322 /// five.as_mut_ptr().write(5);
324 /// five.assume_init()
327 /// assert_eq!(*five, 5);
328 /// # Ok::<(), std::alloc::AllocError>(())
330 #[unstable(feature = "allocator_api", issue = "32838")]
331 // #[unstable(feature = "new_uninit", issue = "63291")]
333 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
334 Box::try_new_uninit_in(Global)
337 /// Constructs a new `Box` with uninitialized contents, with the memory
338 /// being filled with `0` bytes on the heap
340 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
346 /// #![feature(allocator_api, new_uninit)]
348 /// let zero = Box::<u32>::try_new_zeroed()?;
349 /// let zero = unsafe { zero.assume_init() };
351 /// assert_eq!(*zero, 0);
352 /// # Ok::<(), std::alloc::AllocError>(())
355 /// [zeroed]: mem::MaybeUninit::zeroed
356 #[unstable(feature = "allocator_api", issue = "32838")]
357 // #[unstable(feature = "new_uninit", issue = "63291")]
359 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
360 Box::try_new_zeroed_in(Global)
364 impl<T, A: Allocator> Box<T, A> {
365 /// Allocates memory in the given allocator then places `x` into it.
367 /// This doesn't actually allocate if `T` is zero-sized.
372 /// #![feature(allocator_api)]
374 /// use std::alloc::System;
376 /// let five = Box::new_in(5, System);
378 #[cfg(not(no_global_oom_handling))]
379 #[unstable(feature = "allocator_api", issue = "32838")]
382 pub fn new_in(x: T, alloc: A) -> Self
386 let mut boxed = Self::new_uninit_in(alloc);
388 boxed.as_mut_ptr().write(x);
393 /// Allocates memory in the given allocator then places `x` into it,
394 /// returning an error if the allocation fails
396 /// This doesn't actually allocate if `T` is zero-sized.
401 /// #![feature(allocator_api)]
403 /// use std::alloc::System;
405 /// let five = Box::try_new_in(5, System)?;
406 /// # Ok::<(), std::alloc::AllocError>(())
408 #[unstable(feature = "allocator_api", issue = "32838")]
410 pub fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
414 let mut boxed = Self::try_new_uninit_in(alloc)?;
416 boxed.as_mut_ptr().write(x);
417 Ok(boxed.assume_init())
421 /// Constructs a new box with uninitialized contents in the provided allocator.
426 /// #![feature(allocator_api, new_uninit)]
428 /// use std::alloc::System;
430 /// let mut five = Box::<u32, _>::new_uninit_in(System);
432 /// let five = unsafe {
433 /// // Deferred initialization:
434 /// five.as_mut_ptr().write(5);
436 /// five.assume_init()
439 /// assert_eq!(*five, 5)
441 #[unstable(feature = "allocator_api", issue = "32838")]
442 #[cfg(not(no_global_oom_handling))]
444 // #[unstable(feature = "new_uninit", issue = "63291")]
445 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
449 let layout = Layout::new::<mem::MaybeUninit<T>>();
450 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
451 // That would make code size bigger.
452 match Box::try_new_uninit_in(alloc) {
454 Err(_) => handle_alloc_error(layout),
458 /// Constructs a new box with uninitialized contents in the provided allocator,
459 /// returning an error if the allocation fails
464 /// #![feature(allocator_api, new_uninit)]
466 /// use std::alloc::System;
468 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
470 /// let five = unsafe {
471 /// // Deferred initialization:
472 /// five.as_mut_ptr().write(5);
474 /// five.assume_init()
477 /// assert_eq!(*five, 5);
478 /// # Ok::<(), std::alloc::AllocError>(())
480 #[unstable(feature = "allocator_api", issue = "32838")]
481 // #[unstable(feature = "new_uninit", issue = "63291")]
482 pub fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
486 let ptr = if T::IS_ZST {
489 let layout = Layout::new::<mem::MaybeUninit<T>>();
490 alloc.allocate(layout)?.cast()
492 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
495 /// Constructs a new `Box` with uninitialized contents, with the memory
496 /// being filled with `0` bytes in the provided allocator.
498 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
504 /// #![feature(allocator_api, new_uninit)]
506 /// use std::alloc::System;
508 /// let zero = Box::<u32, _>::new_zeroed_in(System);
509 /// let zero = unsafe { zero.assume_init() };
511 /// assert_eq!(*zero, 0)
514 /// [zeroed]: mem::MaybeUninit::zeroed
515 #[unstable(feature = "allocator_api", issue = "32838")]
516 #[cfg(not(no_global_oom_handling))]
517 // #[unstable(feature = "new_uninit", issue = "63291")]
519 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
523 let layout = Layout::new::<mem::MaybeUninit<T>>();
524 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
525 // That would make code size bigger.
526 match Box::try_new_zeroed_in(alloc) {
528 Err(_) => handle_alloc_error(layout),
532 /// Constructs a new `Box` with uninitialized contents, with the memory
533 /// being filled with `0` bytes in the provided allocator,
534 /// returning an error if the allocation fails,
536 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
542 /// #![feature(allocator_api, new_uninit)]
544 /// use std::alloc::System;
546 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
547 /// let zero = unsafe { zero.assume_init() };
549 /// assert_eq!(*zero, 0);
550 /// # Ok::<(), std::alloc::AllocError>(())
553 /// [zeroed]: mem::MaybeUninit::zeroed
554 #[unstable(feature = "allocator_api", issue = "32838")]
555 // #[unstable(feature = "new_uninit", issue = "63291")]
556 pub fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
560 let ptr = if T::IS_ZST {
563 let layout = Layout::new::<mem::MaybeUninit<T>>();
564 alloc.allocate_zeroed(layout)?.cast()
566 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
569 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
570 /// `x` will be pinned in memory and unable to be moved.
572 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin_in(x, alloc)`
573 /// does the same as <code>[Box::into_pin]\([Box::new_in]\(x, alloc))</code>. Consider using
574 /// [`into_pin`](Box::into_pin) if you already have a `Box<T, A>`, or if you want to
575 /// construct a (pinned) `Box` in a different way than with [`Box::new_in`].
576 #[cfg(not(no_global_oom_handling))]
577 #[unstable(feature = "allocator_api", issue = "32838")]
580 pub fn pin_in(x: T, alloc: A) -> Pin<Self>
582 A: 'static + Allocator,
584 Self::into_pin(Self::new_in(x, alloc))
587 /// Converts a `Box<T>` into a `Box<[T]>`
589 /// This conversion does not allocate on the heap and happens in place.
590 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
591 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
592 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
593 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
596 /// Consumes the `Box`, returning the wrapped value.
601 /// #![feature(box_into_inner)]
603 /// let c = Box::new(5);
605 /// assert_eq!(Box::into_inner(c), 5);
607 #[unstable(feature = "box_into_inner", issue = "80437")]
609 pub fn into_inner(boxed: Self) -> T {
615 /// Constructs a new boxed slice with uninitialized contents.
620 /// #![feature(new_uninit)]
622 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
624 /// let values = unsafe {
625 /// // Deferred initialization:
626 /// values[0].as_mut_ptr().write(1);
627 /// values[1].as_mut_ptr().write(2);
628 /// values[2].as_mut_ptr().write(3);
630 /// values.assume_init()
633 /// assert_eq!(*values, [1, 2, 3])
635 #[cfg(not(no_global_oom_handling))]
636 #[unstable(feature = "new_uninit", issue = "63291")]
638 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
639 unsafe { RawVec::with_capacity(len).into_box(len) }
642 /// Constructs a new boxed slice with uninitialized contents, with the memory
643 /// being filled with `0` bytes.
645 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
651 /// #![feature(new_uninit)]
653 /// let values = Box::<[u32]>::new_zeroed_slice(3);
654 /// let values = unsafe { values.assume_init() };
656 /// assert_eq!(*values, [0, 0, 0])
659 /// [zeroed]: mem::MaybeUninit::zeroed
660 #[cfg(not(no_global_oom_handling))]
661 #[unstable(feature = "new_uninit", issue = "63291")]
663 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
664 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
667 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
668 /// the allocation fails
673 /// #![feature(allocator_api, new_uninit)]
675 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
676 /// let values = unsafe {
677 /// // Deferred initialization:
678 /// values[0].as_mut_ptr().write(1);
679 /// values[1].as_mut_ptr().write(2);
680 /// values[2].as_mut_ptr().write(3);
681 /// values.assume_init()
684 /// assert_eq!(*values, [1, 2, 3]);
685 /// # Ok::<(), std::alloc::AllocError>(())
687 #[unstable(feature = "allocator_api", issue = "32838")]
689 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
690 let ptr = if T::IS_ZST || len == 0 {
693 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
695 Err(_) => return Err(AllocError),
697 Global.allocate(layout)?.cast()
699 unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
702 /// Constructs a new boxed slice with uninitialized contents, with the memory
703 /// being filled with `0` bytes. Returns an error if the allocation fails
705 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
711 /// #![feature(allocator_api, new_uninit)]
713 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
714 /// let values = unsafe { values.assume_init() };
716 /// assert_eq!(*values, [0, 0, 0]);
717 /// # Ok::<(), std::alloc::AllocError>(())
720 /// [zeroed]: mem::MaybeUninit::zeroed
721 #[unstable(feature = "allocator_api", issue = "32838")]
723 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
724 let ptr = if T::IS_ZST || len == 0 {
727 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
729 Err(_) => return Err(AllocError),
731 Global.allocate_zeroed(layout)?.cast()
733 unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
737 impl<T, A: Allocator> Box<[T], A> {
738 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
743 /// #![feature(allocator_api, new_uninit)]
745 /// use std::alloc::System;
747 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
749 /// let values = unsafe {
750 /// // Deferred initialization:
751 /// values[0].as_mut_ptr().write(1);
752 /// values[1].as_mut_ptr().write(2);
753 /// values[2].as_mut_ptr().write(3);
755 /// values.assume_init()
758 /// assert_eq!(*values, [1, 2, 3])
760 #[cfg(not(no_global_oom_handling))]
761 #[unstable(feature = "allocator_api", issue = "32838")]
762 // #[unstable(feature = "new_uninit", issue = "63291")]
764 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
765 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
768 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
769 /// with the memory being filled with `0` bytes.
771 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
777 /// #![feature(allocator_api, new_uninit)]
779 /// use std::alloc::System;
781 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
782 /// let values = unsafe { values.assume_init() };
784 /// assert_eq!(*values, [0, 0, 0])
787 /// [zeroed]: mem::MaybeUninit::zeroed
788 #[cfg(not(no_global_oom_handling))]
789 #[unstable(feature = "allocator_api", issue = "32838")]
790 // #[unstable(feature = "new_uninit", issue = "63291")]
792 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
793 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
797 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
798 /// Converts to `Box<T, A>`.
802 /// As with [`MaybeUninit::assume_init`],
803 /// it is up to the caller to guarantee that the value
804 /// really is in an initialized state.
805 /// Calling this when the content is not yet fully initialized
806 /// causes immediate undefined behavior.
808 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
813 /// #![feature(new_uninit)]
815 /// let mut five = Box::<u32>::new_uninit();
817 /// let five: Box<u32> = unsafe {
818 /// // Deferred initialization:
819 /// five.as_mut_ptr().write(5);
821 /// five.assume_init()
824 /// assert_eq!(*five, 5)
826 #[unstable(feature = "new_uninit", issue = "63291")]
828 pub unsafe fn assume_init(self) -> Box<T, A> {
829 let (raw, alloc) = Box::into_raw_with_allocator(self);
830 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
833 /// Writes the value and converts to `Box<T, A>`.
835 /// This method converts the box similarly to [`Box::assume_init`] but
836 /// writes `value` into it before conversion thus guaranteeing safety.
837 /// In some scenarios use of this method may improve performance because
838 /// the compiler may be able to optimize copying from stack.
843 /// #![feature(new_uninit)]
845 /// let big_box = Box::<[usize; 1024]>::new_uninit();
847 /// let mut array = [0; 1024];
848 /// for (i, place) in array.iter_mut().enumerate() {
852 /// // The optimizer may be able to elide this copy, so previous code writes
853 /// // to heap directly.
854 /// let big_box = Box::write(big_box, array);
856 /// for (i, x) in big_box.iter().enumerate() {
857 /// assert_eq!(*x, i);
860 #[unstable(feature = "new_uninit", issue = "63291")]
862 pub fn write(mut boxed: Self, value: T) -> Box<T, A> {
864 (*boxed).write(value);
870 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
871 /// Converts to `Box<[T], A>`.
875 /// As with [`MaybeUninit::assume_init`],
876 /// it is up to the caller to guarantee that the values
877 /// really are in an initialized state.
878 /// Calling this when the content is not yet fully initialized
879 /// causes immediate undefined behavior.
881 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
886 /// #![feature(new_uninit)]
888 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
890 /// let values = unsafe {
891 /// // Deferred initialization:
892 /// values[0].as_mut_ptr().write(1);
893 /// values[1].as_mut_ptr().write(2);
894 /// values[2].as_mut_ptr().write(3);
896 /// values.assume_init()
899 /// assert_eq!(*values, [1, 2, 3])
901 #[unstable(feature = "new_uninit", issue = "63291")]
903 pub unsafe fn assume_init(self) -> Box<[T], A> {
904 let (raw, alloc) = Box::into_raw_with_allocator(self);
905 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
909 impl<T: ?Sized> Box<T> {
910 /// Constructs a box from a raw pointer.
912 /// After calling this function, the raw pointer is owned by the
913 /// resulting `Box`. Specifically, the `Box` destructor will call
914 /// the destructor of `T` and free the allocated memory. For this
915 /// to be safe, the memory must have been allocated in accordance
916 /// with the [memory layout] used by `Box` .
920 /// This function is unsafe because improper use may lead to
921 /// memory problems. For example, a double-free may occur if the
922 /// function is called twice on the same raw pointer.
924 /// The safety conditions are described in the [memory layout] section.
928 /// Recreate a `Box` which was previously converted to a raw pointer
929 /// using [`Box::into_raw`]:
931 /// let x = Box::new(5);
932 /// let ptr = Box::into_raw(x);
933 /// let x = unsafe { Box::from_raw(ptr) };
935 /// Manually create a `Box` from scratch by using the global allocator:
937 /// use std::alloc::{alloc, Layout};
940 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
941 /// // In general .write is required to avoid attempting to destruct
942 /// // the (uninitialized) previous contents of `ptr`, though for this
943 /// // simple example `*ptr = 5` would have worked as well.
945 /// let x = Box::from_raw(ptr);
949 /// [memory layout]: self#memory-layout
950 /// [`Layout`]: crate::Layout
951 #[stable(feature = "box_raw", since = "1.4.0")]
953 #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
954 pub unsafe fn from_raw(raw: *mut T) -> Self {
955 unsafe { Self::from_raw_in(raw, Global) }
959 impl<T: ?Sized, A: Allocator> Box<T, A> {
960 /// Constructs a box from a raw pointer in the given allocator.
962 /// After calling this function, the raw pointer is owned by the
963 /// resulting `Box`. Specifically, the `Box` destructor will call
964 /// the destructor of `T` and free the allocated memory. For this
965 /// to be safe, the memory must have been allocated in accordance
966 /// with the [memory layout] used by `Box` .
970 /// This function is unsafe because improper use may lead to
971 /// memory problems. For example, a double-free may occur if the
972 /// function is called twice on the same raw pointer.
977 /// Recreate a `Box` which was previously converted to a raw pointer
978 /// using [`Box::into_raw_with_allocator`]:
980 /// #![feature(allocator_api)]
982 /// use std::alloc::System;
984 /// let x = Box::new_in(5, System);
985 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
986 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
988 /// Manually create a `Box` from scratch by using the system allocator:
990 /// #![feature(allocator_api, slice_ptr_get)]
992 /// use std::alloc::{Allocator, Layout, System};
995 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
996 /// // In general .write is required to avoid attempting to destruct
997 /// // the (uninitialized) previous contents of `ptr`, though for this
998 /// // simple example `*ptr = 5` would have worked as well.
1000 /// let x = Box::from_raw_in(ptr, System);
1002 /// # Ok::<(), std::alloc::AllocError>(())
1005 /// [memory layout]: self#memory-layout
1006 /// [`Layout`]: crate::Layout
1007 #[unstable(feature = "allocator_api", issue = "32838")]
1008 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1010 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1011 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1014 /// Consumes the `Box`, returning a wrapped raw pointer.
1016 /// The pointer will be properly aligned and non-null.
1018 /// After calling this function, the caller is responsible for the
1019 /// memory previously managed by the `Box`. In particular, the
1020 /// caller should properly destroy `T` and release the memory, taking
1021 /// into account the [memory layout] used by `Box`. The easiest way to
1022 /// do this is to convert the raw pointer back into a `Box` with the
1023 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1026 /// Note: this is an associated function, which means that you have
1027 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1028 /// is so that there is no conflict with a method on the inner type.
1031 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1032 /// for automatic cleanup:
1034 /// let x = Box::new(String::from("Hello"));
1035 /// let ptr = Box::into_raw(x);
1036 /// let x = unsafe { Box::from_raw(ptr) };
1038 /// Manual cleanup by explicitly running the destructor and deallocating
1041 /// use std::alloc::{dealloc, Layout};
1044 /// let x = Box::new(String::from("Hello"));
1045 /// let p = Box::into_raw(x);
1047 /// ptr::drop_in_place(p);
1048 /// dealloc(p as *mut u8, Layout::new::<String>());
1052 /// [memory layout]: self#memory-layout
1053 #[stable(feature = "box_raw", since = "1.4.0")]
1055 pub fn into_raw(b: Self) -> *mut T {
1056 Self::into_raw_with_allocator(b).0
1059 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1061 /// The pointer will be properly aligned and non-null.
1063 /// After calling this function, the caller is responsible for the
1064 /// memory previously managed by the `Box`. In particular, the
1065 /// caller should properly destroy `T` and release the memory, taking
1066 /// into account the [memory layout] used by `Box`. The easiest way to
1067 /// do this is to convert the raw pointer back into a `Box` with the
1068 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1071 /// Note: this is an associated function, which means that you have
1072 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1073 /// is so that there is no conflict with a method on the inner type.
1076 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1077 /// for automatic cleanup:
1079 /// #![feature(allocator_api)]
1081 /// use std::alloc::System;
1083 /// let x = Box::new_in(String::from("Hello"), System);
1084 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1085 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1087 /// Manual cleanup by explicitly running the destructor and deallocating
1090 /// #![feature(allocator_api)]
1092 /// use std::alloc::{Allocator, Layout, System};
1093 /// use std::ptr::{self, NonNull};
1095 /// let x = Box::new_in(String::from("Hello"), System);
1096 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1098 /// ptr::drop_in_place(ptr);
1099 /// let non_null = NonNull::new_unchecked(ptr);
1100 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1104 /// [memory layout]: self#memory-layout
1105 #[unstable(feature = "allocator_api", issue = "32838")]
1107 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1108 let (leaked, alloc) = Box::into_unique(b);
1109 (leaked.as_ptr(), alloc)
1113 feature = "ptr_internals",
1115 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1119 pub fn into_unique(b: Self) -> (Unique<T>, A) {
1120 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1121 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1122 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1123 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1124 // behaves correctly.
1125 let alloc = unsafe { ptr::read(&b.1) };
1126 (Unique::from(Box::leak(b)), alloc)
1129 /// Returns a reference to the underlying allocator.
1131 /// Note: this is an associated function, which means that you have
1132 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1133 /// is so that there is no conflict with a method on the inner type.
1134 #[unstable(feature = "allocator_api", issue = "32838")]
1135 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1137 pub const fn allocator(b: &Self) -> &A {
1141 /// Consumes and leaks the `Box`, returning a mutable reference,
1142 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1143 /// `'a`. If the type has only static references, or none at all, then this
1144 /// may be chosen to be `'static`.
1146 /// This function is mainly useful for data that lives for the remainder of
1147 /// the program's life. Dropping the returned reference will cause a memory
1148 /// leak. If this is not acceptable, the reference should first be wrapped
1149 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1150 /// then be dropped which will properly destroy `T` and release the
1151 /// allocated memory.
1153 /// Note: this is an associated function, which means that you have
1154 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1155 /// is so that there is no conflict with a method on the inner type.
1162 /// let x = Box::new(41);
1163 /// let static_ref: &'static mut usize = Box::leak(x);
1164 /// *static_ref += 1;
1165 /// assert_eq!(*static_ref, 42);
1171 /// let x = vec![1, 2, 3].into_boxed_slice();
1172 /// let static_ref = Box::leak(x);
1173 /// static_ref[0] = 4;
1174 /// assert_eq!(*static_ref, [4, 2, 3]);
1176 #[stable(feature = "box_leak", since = "1.26.0")]
1178 pub fn leak<'a>(b: Self) -> &'a mut T
1182 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1185 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1186 /// `*boxed` will be pinned in memory and unable to be moved.
1188 /// This conversion does not allocate on the heap and happens in place.
1190 /// This is also available via [`From`].
1192 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1193 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1194 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1195 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1199 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1200 /// as it'll introduce an ambiguity when calling `Pin::from`.
1201 /// A demonstration of such a poor impl is shown below.
1204 /// # use std::pin::Pin;
1205 /// struct Foo; // A type defined in this crate.
1206 /// impl From<Box<()>> for Pin<Foo> {
1207 /// fn from(_: Box<()>) -> Pin<Foo> {
1212 /// let foo = Box::new(());
1213 /// let bar = Pin::from(foo);
1215 #[stable(feature = "box_into_pin", since = "1.63.0")]
1216 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1217 pub const fn into_pin(boxed: Self) -> Pin<Self>
1221 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1222 // when `T: !Unpin`, so it's safe to pin it directly without any
1223 // additional requirements.
1224 unsafe { Pin::new_unchecked(boxed) }
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1231 fn drop(&mut self) {
1232 // the T in the Box is dropped by the compiler before the destructor is run
1237 let layout = Layout::for_value_raw(ptr.as_ptr());
1238 if layout.size() != 0 {
1239 self.1.deallocate(From::from(ptr.cast()), layout);
1245 #[cfg(not(no_global_oom_handling))]
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 impl<T: Default> Default for Box<T> {
1248 /// Creates a `Box<T>`, with the `Default` value for T.
1250 fn default() -> Self {
1251 Box::new(T::default())
1255 #[cfg(not(no_global_oom_handling))]
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 impl<T> Default for Box<[T]> {
1259 fn default() -> Self {
1260 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1265 #[cfg(not(no_global_oom_handling))]
1266 #[stable(feature = "default_box_extra", since = "1.17.0")]
1267 impl Default for Box<str> {
1269 fn default() -> Self {
1270 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1271 let ptr: Unique<str> = unsafe {
1272 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1273 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1279 #[cfg(not(no_global_oom_handling))]
1280 #[stable(feature = "rust1", since = "1.0.0")]
1281 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1282 /// Returns a new box with a `clone()` of this box's contents.
1287 /// let x = Box::new(5);
1288 /// let y = x.clone();
1290 /// // The value is the same
1291 /// assert_eq!(x, y);
1293 /// // But they are unique objects
1294 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1297 fn clone(&self) -> Self {
1298 // Pre-allocate memory to allow writing the cloned value directly.
1299 let mut boxed = Self::new_uninit_in(self.1.clone());
1301 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1306 /// Copies `source`'s contents into `self` without creating a new allocation.
1311 /// let x = Box::new(5);
1312 /// let mut y = Box::new(10);
1313 /// let yp: *const i32 = &*y;
1315 /// y.clone_from(&x);
1317 /// // The value is the same
1318 /// assert_eq!(x, y);
1320 /// // And no allocation occurred
1321 /// assert_eq!(yp, &*y);
1324 fn clone_from(&mut self, source: &Self) {
1325 (**self).clone_from(&(**source));
1329 #[cfg(not(no_global_oom_handling))]
1330 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1331 impl Clone for Box<str> {
1332 fn clone(&self) -> Self {
1333 // this makes a copy of the data
1334 let buf: Box<[u8]> = self.as_bytes().into();
1335 unsafe { from_boxed_utf8_unchecked(buf) }
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1342 fn eq(&self, other: &Self) -> bool {
1343 PartialEq::eq(&**self, &**other)
1346 fn ne(&self, other: &Self) -> bool {
1347 PartialEq::ne(&**self, &**other)
1350 #[stable(feature = "rust1", since = "1.0.0")]
1351 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1353 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1354 PartialOrd::partial_cmp(&**self, &**other)
1357 fn lt(&self, other: &Self) -> bool {
1358 PartialOrd::lt(&**self, &**other)
1361 fn le(&self, other: &Self) -> bool {
1362 PartialOrd::le(&**self, &**other)
1365 fn ge(&self, other: &Self) -> bool {
1366 PartialOrd::ge(&**self, &**other)
1369 fn gt(&self, other: &Self) -> bool {
1370 PartialOrd::gt(&**self, &**other)
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1376 fn cmp(&self, other: &Self) -> Ordering {
1377 Ord::cmp(&**self, &**other)
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1383 #[stable(feature = "rust1", since = "1.0.0")]
1384 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1385 fn hash<H: Hasher>(&self, state: &mut H) {
1386 (**self).hash(state);
1390 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1391 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1392 fn finish(&self) -> u64 {
1395 fn write(&mut self, bytes: &[u8]) {
1396 (**self).write(bytes)
1398 fn write_u8(&mut self, i: u8) {
1399 (**self).write_u8(i)
1401 fn write_u16(&mut self, i: u16) {
1402 (**self).write_u16(i)
1404 fn write_u32(&mut self, i: u32) {
1405 (**self).write_u32(i)
1407 fn write_u64(&mut self, i: u64) {
1408 (**self).write_u64(i)
1410 fn write_u128(&mut self, i: u128) {
1411 (**self).write_u128(i)
1413 fn write_usize(&mut self, i: usize) {
1414 (**self).write_usize(i)
1416 fn write_i8(&mut self, i: i8) {
1417 (**self).write_i8(i)
1419 fn write_i16(&mut self, i: i16) {
1420 (**self).write_i16(i)
1422 fn write_i32(&mut self, i: i32) {
1423 (**self).write_i32(i)
1425 fn write_i64(&mut self, i: i64) {
1426 (**self).write_i64(i)
1428 fn write_i128(&mut self, i: i128) {
1429 (**self).write_i128(i)
1431 fn write_isize(&mut self, i: isize) {
1432 (**self).write_isize(i)
1434 fn write_length_prefix(&mut self, len: usize) {
1435 (**self).write_length_prefix(len)
1437 fn write_str(&mut self, s: &str) {
1438 (**self).write_str(s)
1442 #[cfg(not(no_global_oom_handling))]
1443 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1444 impl<T> From<T> for Box<T> {
1445 /// Converts a `T` into a `Box<T>`
1447 /// The conversion allocates on the heap and moves `t`
1448 /// from the stack into it.
1454 /// let boxed = Box::new(5);
1456 /// assert_eq!(Box::from(x), boxed);
1458 fn from(t: T) -> Self {
1463 #[stable(feature = "pin", since = "1.33.0")]
1464 impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
1468 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1469 /// `*boxed` will be pinned in memory and unable to be moved.
1471 /// This conversion does not allocate on the heap and happens in place.
1473 /// This is also available via [`Box::into_pin`].
1475 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
1476 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1477 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
1478 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1479 fn from(boxed: Box<T, A>) -> Self {
1480 Box::into_pin(boxed)
1484 /// Specialization trait used for `From<&[T]>`.
1485 #[cfg(not(no_global_oom_handling))]
1486 trait BoxFromSlice<T> {
1487 fn from_slice(slice: &[T]) -> Self;
1490 #[cfg(not(no_global_oom_handling))]
1491 impl<T: Clone> BoxFromSlice<T> for Box<[T]> {
1493 default fn from_slice(slice: &[T]) -> Self {
1494 slice.to_vec().into_boxed_slice()
1498 #[cfg(not(no_global_oom_handling))]
1499 impl<T: Copy> BoxFromSlice<T> for Box<[T]> {
1501 fn from_slice(slice: &[T]) -> Self {
1502 let len = slice.len();
1503 let buf = RawVec::with_capacity(len);
1505 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1506 buf.into_box(slice.len()).assume_init()
1511 #[cfg(not(no_global_oom_handling))]
1512 #[stable(feature = "box_from_slice", since = "1.17.0")]
1513 impl<T: Clone> From<&[T]> for Box<[T]> {
1514 /// Converts a `&[T]` into a `Box<[T]>`
1516 /// This conversion allocates on the heap
1517 /// and performs a copy of `slice` and its contents.
1521 /// // create a &[u8] which will be used to create a Box<[u8]>
1522 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1523 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1525 /// println!("{boxed_slice:?}");
1528 fn from(slice: &[T]) -> Box<[T]> {
1529 <Self as BoxFromSlice<T>>::from_slice(slice)
1533 #[cfg(not(no_global_oom_handling))]
1534 #[stable(feature = "box_from_cow", since = "1.45.0")]
1535 impl<T: Clone> From<Cow<'_, [T]>> for Box<[T]> {
1536 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1538 /// When `cow` is the `Cow::Borrowed` variant, this
1539 /// conversion allocates on the heap and copies the
1540 /// underlying slice. Otherwise, it will try to reuse the owned
1541 /// `Vec`'s allocation.
1543 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1545 Cow::Borrowed(slice) => Box::from(slice),
1546 Cow::Owned(slice) => Box::from(slice),
1551 #[cfg(not(no_global_oom_handling))]
1552 #[stable(feature = "box_from_slice", since = "1.17.0")]
1553 impl From<&str> for Box<str> {
1554 /// Converts a `&str` into a `Box<str>`
1556 /// This conversion allocates on the heap
1557 /// and performs a copy of `s`.
1562 /// let boxed: Box<str> = Box::from("hello");
1563 /// println!("{boxed}");
1566 fn from(s: &str) -> Box<str> {
1567 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1571 #[cfg(not(no_global_oom_handling))]
1572 #[stable(feature = "box_from_cow", since = "1.45.0")]
1573 impl From<Cow<'_, str>> for Box<str> {
1574 /// Converts a `Cow<'_, str>` into a `Box<str>`
1576 /// When `cow` is the `Cow::Borrowed` variant, this
1577 /// conversion allocates on the heap and copies the
1578 /// underlying `str`. Otherwise, it will try to reuse the owned
1579 /// `String`'s allocation.
1584 /// use std::borrow::Cow;
1586 /// let unboxed = Cow::Borrowed("hello");
1587 /// let boxed: Box<str> = Box::from(unboxed);
1588 /// println!("{boxed}");
1592 /// # use std::borrow::Cow;
1593 /// let unboxed = Cow::Owned("hello".to_string());
1594 /// let boxed: Box<str> = Box::from(unboxed);
1595 /// println!("{boxed}");
1598 fn from(cow: Cow<'_, str>) -> Box<str> {
1600 Cow::Borrowed(s) => Box::from(s),
1601 Cow::Owned(s) => Box::from(s),
1606 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1607 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1608 /// Converts a `Box<str>` into a `Box<[u8]>`
1610 /// This conversion does not allocate on the heap and happens in place.
1614 /// // create a Box<str> which will be used to create a Box<[u8]>
1615 /// let boxed: Box<str> = Box::from("hello");
1616 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1618 /// // create a &[u8] which will be used to create a Box<[u8]>
1619 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1620 /// let boxed_slice = Box::from(slice);
1622 /// assert_eq!(boxed_slice, boxed_str);
1625 fn from(s: Box<str, A>) -> Self {
1626 let (raw, alloc) = Box::into_raw_with_allocator(s);
1627 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1631 #[cfg(not(no_global_oom_handling))]
1632 #[stable(feature = "box_from_array", since = "1.45.0")]
1633 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1634 /// Converts a `[T; N]` into a `Box<[T]>`
1636 /// This conversion moves the array to newly heap-allocated memory.
1641 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1642 /// println!("{boxed:?}");
1644 fn from(array: [T; N]) -> Box<[T]> {
1649 /// Casts a boxed slice to a boxed array.
1653 /// `boxed_slice.len()` must be exactly `N`.
1654 unsafe fn boxed_slice_as_array_unchecked<T, A: Allocator, const N: usize>(
1655 boxed_slice: Box<[T], A>,
1656 ) -> Box<[T; N], A> {
1657 debug_assert_eq!(boxed_slice.len(), N);
1659 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
1660 // SAFETY: Pointer and allocator came from an existing box,
1661 // and our safety condition requires that the length is exactly `N`
1662 unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) }
1665 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1666 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1667 type Error = Box<[T]>;
1669 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1671 /// The conversion occurs in-place and does not require a
1672 /// new memory allocation.
1676 /// Returns the old `Box<[T]>` in the `Err` variant if
1677 /// `boxed_slice.len()` does not equal `N`.
1678 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1679 if boxed_slice.len() == N {
1680 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1687 #[cfg(not(no_global_oom_handling))]
1688 #[stable(feature = "boxed_array_try_from_vec", since = "1.66.0")]
1689 impl<T, const N: usize> TryFrom<Vec<T>> for Box<[T; N]> {
1690 type Error = Vec<T>;
1692 /// Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.
1694 /// Like [`Vec::into_boxed_slice`], this is in-place if `vec.capacity() == N`,
1695 /// but will require a reallocation otherwise.
1699 /// Returns the original `Vec<T>` in the `Err` variant if
1700 /// `boxed_slice.len()` does not equal `N`.
1704 /// This can be used with [`vec!`] to create an array on the heap:
1707 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
1708 /// assert_eq!(state.len(), 100);
1710 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1712 let boxed_slice = vec.into_boxed_slice();
1713 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1720 impl<A: Allocator> Box<dyn Any, A> {
1721 /// Attempt to downcast the box to a concrete type.
1726 /// use std::any::Any;
1728 /// fn print_if_string(value: Box<dyn Any>) {
1729 /// if let Ok(string) = value.downcast::<String>() {
1730 /// println!("String ({}): {}", string.len(), string);
1734 /// let my_string = "Hello World".to_string();
1735 /// print_if_string(Box::new(my_string));
1736 /// print_if_string(Box::new(0i8));
1739 #[stable(feature = "rust1", since = "1.0.0")]
1740 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1741 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1744 /// Downcasts the box to a concrete type.
1746 /// For a safe alternative see [`downcast`].
1751 /// #![feature(downcast_unchecked)]
1753 /// use std::any::Any;
1755 /// let x: Box<dyn Any> = Box::new(1_usize);
1758 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1764 /// The contained value must be of type `T`. Calling this method
1765 /// with the incorrect type is *undefined behavior*.
1767 /// [`downcast`]: Self::downcast
1769 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1770 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1771 debug_assert!(self.is::<T>());
1773 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1774 Box::from_raw_in(raw as *mut T, alloc)
1779 impl<A: Allocator> Box<dyn Any + Send, A> {
1780 /// Attempt to downcast the box to a concrete type.
1785 /// use std::any::Any;
1787 /// fn print_if_string(value: Box<dyn Any + Send>) {
1788 /// if let Ok(string) = value.downcast::<String>() {
1789 /// println!("String ({}): {}", string.len(), string);
1793 /// let my_string = "Hello World".to_string();
1794 /// print_if_string(Box::new(my_string));
1795 /// print_if_string(Box::new(0i8));
1798 #[stable(feature = "rust1", since = "1.0.0")]
1799 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1800 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1803 /// Downcasts the box to a concrete type.
1805 /// For a safe alternative see [`downcast`].
1810 /// #![feature(downcast_unchecked)]
1812 /// use std::any::Any;
1814 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1817 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1823 /// The contained value must be of type `T`. Calling this method
1824 /// with the incorrect type is *undefined behavior*.
1826 /// [`downcast`]: Self::downcast
1828 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1829 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1830 debug_assert!(self.is::<T>());
1832 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1833 Box::from_raw_in(raw as *mut T, alloc)
1838 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1839 /// Attempt to downcast the box to a concrete type.
1844 /// use std::any::Any;
1846 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1847 /// if let Ok(string) = value.downcast::<String>() {
1848 /// println!("String ({}): {}", string.len(), string);
1852 /// let my_string = "Hello World".to_string();
1853 /// print_if_string(Box::new(my_string));
1854 /// print_if_string(Box::new(0i8));
1857 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1858 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1859 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1862 /// Downcasts the box to a concrete type.
1864 /// For a safe alternative see [`downcast`].
1869 /// #![feature(downcast_unchecked)]
1871 /// use std::any::Any;
1873 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1876 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1882 /// The contained value must be of type `T`. Calling this method
1883 /// with the incorrect type is *undefined behavior*.
1885 /// [`downcast`]: Self::downcast
1887 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1888 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1889 debug_assert!(self.is::<T>());
1891 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1892 Box::into_raw_with_allocator(self);
1893 Box::from_raw_in(raw as *mut T, alloc)
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1900 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1901 fmt::Display::fmt(&**self, f)
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1907 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1908 fmt::Debug::fmt(&**self, f)
1912 #[stable(feature = "rust1", since = "1.0.0")]
1913 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1914 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1915 // It's not possible to extract the inner Uniq directly from the Box,
1916 // instead we cast it to a *const which aliases the Unique
1917 let ptr: *const T = &**self;
1918 fmt::Pointer::fmt(&ptr, f)
1922 #[stable(feature = "rust1", since = "1.0.0")]
1923 impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
1926 fn deref(&self) -> &T {
1931 #[stable(feature = "rust1", since = "1.0.0")]
1932 impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
1933 fn deref_mut(&mut self) -> &mut T {
1938 #[unstable(feature = "receiver_trait", issue = "none")]
1939 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1941 #[stable(feature = "rust1", since = "1.0.0")]
1942 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1943 type Item = I::Item;
1944 fn next(&mut self) -> Option<I::Item> {
1947 fn size_hint(&self) -> (usize, Option<usize>) {
1948 (**self).size_hint()
1950 fn nth(&mut self, n: usize) -> Option<I::Item> {
1953 fn last(self) -> Option<I::Item> {
1960 fn last(self) -> Option<Self::Item>;
1963 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1964 type Item = I::Item;
1965 default fn last(self) -> Option<I::Item> {
1967 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1971 self.fold(None, some)
1975 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1976 /// instead of the default.
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1979 fn last(self) -> Option<I::Item> {
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1986 fn next_back(&mut self) -> Option<I::Item> {
1987 (**self).next_back()
1989 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1990 (**self).nth_back(n)
1993 #[stable(feature = "rust1", since = "1.0.0")]
1994 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1995 fn len(&self) -> usize {
1998 fn is_empty(&self) -> bool {
2003 #[stable(feature = "fused", since = "1.26.0")]
2004 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
2006 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2007 impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
2008 type Output = <F as FnOnce<Args>>::Output;
2010 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
2011 <F as FnOnce<Args>>::call_once(*self, args)
2015 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2016 impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
2017 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
2018 <F as FnMut<Args>>::call_mut(self, args)
2022 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2023 impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2024 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2025 <F as Fn<Args>>::call(self, args)
2029 #[unstable(feature = "coerce_unsized", issue = "18598")]
2030 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2032 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2033 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2035 #[cfg(not(no_global_oom_handling))]
2036 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
2037 impl<I> FromIterator<I> for Box<[I]> {
2038 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
2039 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
2043 #[cfg(not(no_global_oom_handling))]
2044 #[stable(feature = "box_slice_clone", since = "1.3.0")]
2045 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2046 fn clone(&self) -> Self {
2047 let alloc = Box::allocator(self).clone();
2048 self.to_vec_in(alloc).into_boxed_slice()
2051 fn clone_from(&mut self, other: &Self) {
2052 if self.len() == other.len() {
2053 self.clone_from_slice(&other);
2055 *self = other.clone();
2060 #[stable(feature = "box_borrow", since = "1.1.0")]
2061 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
2062 fn borrow(&self) -> &T {
2067 #[stable(feature = "box_borrow", since = "1.1.0")]
2068 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
2069 fn borrow_mut(&mut self) -> &mut T {
2074 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2075 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2076 fn as_ref(&self) -> &T {
2081 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2082 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2083 fn as_mut(&mut self) -> &mut T {
2090 * We could have chosen not to add this impl, and instead have written a
2091 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2092 * because Box<T> implements Unpin even when T does not, as a result of
2095 * We chose this API instead of the alternative for a few reasons:
2096 * - Logically, it is helpful to understand pinning in regard to the
2097 * memory region being pointed to. For this reason none of the
2098 * standard library pointer types support projecting through a pin
2099 * (Box<T> is the only pointer type in std for which this would be
2101 * - It is in practice very useful to have Box<T> be unconditionally
2102 * Unpin because of trait objects, for which the structural auto
2103 * trait functionality does not apply (e.g., Box<dyn Foo> would
2104 * otherwise not be Unpin).
2106 * Another type with the same semantics as Box but only a conditional
2107 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2108 * could have a method to project a Pin<T> from it.
2110 #[stable(feature = "pin", since = "1.33.0")]
2111 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
2113 #[unstable(feature = "generator_trait", issue = "43122")]
2114 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2118 type Yield = G::Yield;
2119 type Return = G::Return;
2121 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2122 G::resume(Pin::new(&mut *self), arg)
2126 #[unstable(feature = "generator_trait", issue = "43122")]
2127 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2131 type Yield = G::Yield;
2132 type Return = G::Return;
2134 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2135 G::resume((*self).as_mut(), arg)
2139 #[stable(feature = "futures_api", since = "1.36.0")]
2140 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2144 type Output = F::Output;
2146 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2147 F::poll(Pin::new(&mut *self), cx)
2151 #[unstable(feature = "async_iterator", issue = "79024")]
2152 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2153 type Item = S::Item;
2155 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2156 Pin::new(&mut **self).poll_next(cx)
2159 fn size_hint(&self) -> (usize, Option<usize>) {
2160 (**self).size_hint()
2166 #[stable(feature = "error_downcast", since = "1.3.0")]
2167 #[rustc_allow_incoherent_impl]
2168 /// Attempts to downcast the box to a concrete type.
2169 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
2172 let raw: *mut dyn Error = Box::into_raw(self);
2173 Ok(Box::from_raw(raw as *mut T))
2181 impl dyn Error + Send {
2183 #[stable(feature = "error_downcast", since = "1.3.0")]
2184 #[rustc_allow_incoherent_impl]
2185 /// Attempts to downcast the box to a concrete type.
2186 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
2187 let err: Box<dyn Error> = self;
2188 <dyn Error>::downcast(err).map_err(|s| unsafe {
2189 // Reapply the `Send` marker.
2190 Box::from_raw(Box::into_raw(s) as *mut (dyn Error + Send))
2195 impl dyn Error + Send + Sync {
2197 #[stable(feature = "error_downcast", since = "1.3.0")]
2198 #[rustc_allow_incoherent_impl]
2199 /// Attempts to downcast the box to a concrete type.
2200 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
2201 let err: Box<dyn Error> = self;
2202 <dyn Error>::downcast(err).map_err(|s| unsafe {
2203 // Reapply the `Send + Sync` marker.
2204 Box::from_raw(Box::into_raw(s) as *mut (dyn Error + Send + Sync))
2209 #[cfg(not(no_global_oom_handling))]
2210 #[stable(feature = "rust1", since = "1.0.0")]
2211 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
2212 /// Converts a type of [`Error`] into a box of dyn [`Error`].
2217 /// use std::error::Error;
2221 /// #[derive(Debug)]
2224 /// impl fmt::Display for AnError {
2225 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 /// write!(f, "An error")
2230 /// impl Error for AnError {}
2232 /// let an_error = AnError;
2233 /// assert!(0 == mem::size_of_val(&an_error));
2234 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
2235 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2237 fn from(err: E) -> Box<dyn Error + 'a> {
2242 #[cfg(not(no_global_oom_handling))]
2243 #[stable(feature = "rust1", since = "1.0.0")]
2244 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
2245 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
2246 /// dyn [`Error`] + [`Send`] + [`Sync`].
2251 /// use std::error::Error;
2255 /// #[derive(Debug)]
2258 /// impl fmt::Display for AnError {
2259 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2260 /// write!(f, "An error")
2264 /// impl Error for AnError {}
2266 /// unsafe impl Send for AnError {}
2268 /// unsafe impl Sync for AnError {}
2270 /// let an_error = AnError;
2271 /// assert!(0 == mem::size_of_val(&an_error));
2272 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
2274 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2276 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
2281 #[cfg(not(no_global_oom_handling))]
2282 #[stable(feature = "rust1", since = "1.0.0")]
2283 impl From<String> for Box<dyn Error + Send + Sync> {
2284 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2289 /// use std::error::Error;
2292 /// let a_string_error = "a string error".to_string();
2293 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
2295 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2298 fn from(err: String) -> Box<dyn Error + Send + Sync> {
2299 struct StringError(String);
2301 impl Error for StringError {
2302 #[allow(deprecated)]
2303 fn description(&self) -> &str {
2308 impl fmt::Display for StringError {
2309 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2310 fmt::Display::fmt(&self.0, f)
2314 // Purposefully skip printing "StringError(..)"
2315 impl fmt::Debug for StringError {
2316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2317 fmt::Debug::fmt(&self.0, f)
2321 Box::new(StringError(err))
2325 #[cfg(not(no_global_oom_handling))]
2326 #[stable(feature = "string_box_error", since = "1.6.0")]
2327 impl From<String> for Box<dyn Error> {
2328 /// Converts a [`String`] into a box of dyn [`Error`].
2333 /// use std::error::Error;
2336 /// let a_string_error = "a string error".to_string();
2337 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
2338 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2340 fn from(str_err: String) -> Box<dyn Error> {
2341 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
2342 let err2: Box<dyn Error> = err1;
2347 #[cfg(not(no_global_oom_handling))]
2348 #[stable(feature = "rust1", since = "1.0.0")]
2349 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
2350 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2352 /// [`str`]: prim@str
2357 /// use std::error::Error;
2360 /// let a_str_error = "a str error";
2361 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
2363 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2366 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
2367 From::from(String::from(err))
2371 #[cfg(not(no_global_oom_handling))]
2372 #[stable(feature = "string_box_error", since = "1.6.0")]
2373 impl From<&str> for Box<dyn Error> {
2374 /// Converts a [`str`] into a box of dyn [`Error`].
2376 /// [`str`]: prim@str
2381 /// use std::error::Error;
2384 /// let a_str_error = "a str error";
2385 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
2386 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2388 fn from(err: &str) -> Box<dyn Error> {
2389 From::from(String::from(err))
2393 #[cfg(not(no_global_oom_handling))]
2394 #[stable(feature = "cow_box_error", since = "1.22.0")]
2395 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
2396 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2401 /// use std::error::Error;
2403 /// use std::borrow::Cow;
2405 /// let a_cow_str_error = Cow::from("a str error");
2406 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
2408 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2410 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
2411 From::from(String::from(err))
2415 #[cfg(not(no_global_oom_handling))]
2416 #[stable(feature = "cow_box_error", since = "1.22.0")]
2417 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
2418 /// Converts a [`Cow`] into a box of dyn [`Error`].
2423 /// use std::error::Error;
2425 /// use std::borrow::Cow;
2427 /// let a_cow_str_error = Cow::from("a str error");
2428 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
2429 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2431 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
2432 From::from(String::from(err))
2436 #[stable(feature = "box_error", since = "1.8.0")]
2437 impl<T: core::error::Error> core::error::Error for Box<T> {
2438 #[allow(deprecated, deprecated_in_future)]
2439 fn description(&self) -> &str {
2440 core::error::Error::description(&**self)
2443 #[allow(deprecated)]
2444 fn cause(&self) -> Option<&dyn core::error::Error> {
2445 core::error::Error::cause(&**self)
2448 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
2449 core::error::Error::source(&**self)