1 //! The `Box<T>` 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 //! # Considerations for unsafe code
127 //! **Warning: This section is not normative and is subject to change, possibly
128 //! being relaxed in the future! It is a simplified summary of the rules
129 //! currently implemented in the compiler.**
131 //! The aliasing rules for `Box<T>` are the same as for `&mut T`. `Box<T>`
132 //! asserts uniqueness over its content. Using raw pointers derived from a box
133 //! after that box has been mutated through, moved or borrowed as `&mut T`
134 //! is not allowed. For more guidance on working with box from unsafe code, see
135 //! [rust-lang/unsafe-code-guidelines#326][ucg#326].
138 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
139 //! [ucg#326]: https://github.com/rust-lang/unsafe-code-guidelines/issues/326
140 //! [dereferencing]: core::ops::Deref
141 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
142 //! [`Global`]: crate::alloc::Global
143 //! [`Layout`]: crate::alloc::Layout
144 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
145 //! [valid]: ptr#safety
147 #![stable(feature = "rust1", since = "1.0.0")]
150 use core::async_iter::AsyncIterator;
152 use core::cmp::Ordering;
153 use core::convert::{From, TryFrom};
154 use core::error::Error;
156 use core::future::Future;
157 use core::hash::{Hash, Hasher};
158 #[cfg(not(no_global_oom_handling))]
159 use core::iter::FromIterator;
160 use core::iter::{FusedIterator, Iterator};
161 #[cfg(not(bootstrap))]
162 use core::marker::Tuple;
163 use core::marker::{Destruct, Unpin, Unsize};
166 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
169 use core::ptr::{self, Unique};
170 use core::task::{Context, Poll};
172 #[cfg(not(no_global_oom_handling))]
173 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
174 use crate::alloc::{AllocError, Allocator, Global, Layout};
175 #[cfg(not(no_global_oom_handling))]
176 use crate::borrow::Cow;
177 use crate::raw_vec::RawVec;
178 #[cfg(not(no_global_oom_handling))]
179 use crate::str::from_boxed_utf8_unchecked;
180 #[cfg(not(no_global_oom_handling))]
181 use crate::string::String;
182 #[cfg(not(no_global_oom_handling))]
185 #[unstable(feature = "thin_box", issue = "92791")]
186 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 pub fn new(x: T) -> Self {
223 /// Constructs a new box with uninitialized contents.
228 /// #![feature(new_uninit)]
230 /// let mut five = Box::<u32>::new_uninit();
232 /// let five = unsafe {
233 /// // Deferred initialization:
234 /// five.as_mut_ptr().write(5);
236 /// five.assume_init()
239 /// assert_eq!(*five, 5)
241 #[cfg(not(no_global_oom_handling))]
242 #[unstable(feature = "new_uninit", issue = "63291")]
245 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
246 Self::new_uninit_in(Global)
249 /// Constructs a new `Box` with uninitialized contents, with the memory
250 /// being filled with `0` bytes.
252 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
258 /// #![feature(new_uninit)]
260 /// let zero = Box::<u32>::new_zeroed();
261 /// let zero = unsafe { zero.assume_init() };
263 /// assert_eq!(*zero, 0)
266 /// [zeroed]: mem::MaybeUninit::zeroed
267 #[cfg(not(no_global_oom_handling))]
269 #[unstable(feature = "new_uninit", issue = "63291")]
271 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
272 Self::new_zeroed_in(Global)
275 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
276 /// `x` will be pinned in memory and unable to be moved.
278 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
279 /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
280 /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
281 /// construct a (pinned) `Box` in a different way than with [`Box::new`].
282 #[cfg(not(no_global_oom_handling))]
283 #[stable(feature = "pin", since = "1.33.0")]
286 pub fn pin(x: T) -> Pin<Box<T>> {
292 /// Allocates memory on the heap then places `x` into it,
293 /// returning an error if the allocation fails
295 /// This doesn't actually allocate if `T` is zero-sized.
300 /// #![feature(allocator_api)]
302 /// let five = Box::try_new(5)?;
303 /// # Ok::<(), std::alloc::AllocError>(())
305 #[unstable(feature = "allocator_api", issue = "32838")]
307 pub fn try_new(x: T) -> Result<Self, AllocError> {
308 Self::try_new_in(x, Global)
311 /// Constructs a new box with uninitialized contents on the heap,
312 /// returning an error if the allocation fails
317 /// #![feature(allocator_api, new_uninit)]
319 /// let mut five = Box::<u32>::try_new_uninit()?;
321 /// let five = unsafe {
322 /// // Deferred initialization:
323 /// five.as_mut_ptr().write(5);
325 /// five.assume_init()
328 /// assert_eq!(*five, 5);
329 /// # Ok::<(), std::alloc::AllocError>(())
331 #[unstable(feature = "allocator_api", issue = "32838")]
332 // #[unstable(feature = "new_uninit", issue = "63291")]
334 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
335 Box::try_new_uninit_in(Global)
338 /// Constructs a new `Box` with uninitialized contents, with the memory
339 /// being filled with `0` bytes on the heap
341 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
347 /// #![feature(allocator_api, new_uninit)]
349 /// let zero = Box::<u32>::try_new_zeroed()?;
350 /// let zero = unsafe { zero.assume_init() };
352 /// assert_eq!(*zero, 0);
353 /// # Ok::<(), std::alloc::AllocError>(())
356 /// [zeroed]: mem::MaybeUninit::zeroed
357 #[unstable(feature = "allocator_api", issue = "32838")]
358 // #[unstable(feature = "new_uninit", issue = "63291")]
360 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
361 Box::try_new_zeroed_in(Global)
365 impl<T, A: Allocator> Box<T, A> {
366 /// Allocates memory in the given allocator then places `x` into it.
368 /// This doesn't actually allocate if `T` is zero-sized.
373 /// #![feature(allocator_api)]
375 /// use std::alloc::System;
377 /// let five = Box::new_in(5, System);
379 #[cfg(not(no_global_oom_handling))]
380 #[unstable(feature = "allocator_api", issue = "32838")]
381 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
384 pub const fn new_in(x: T, alloc: A) -> Self
386 A: ~const Allocator + ~const Destruct,
388 let mut boxed = Self::new_uninit_in(alloc);
390 boxed.as_mut_ptr().write(x);
395 /// Allocates memory in the given allocator then places `x` into it,
396 /// returning an error if the allocation fails
398 /// This doesn't actually allocate if `T` is zero-sized.
403 /// #![feature(allocator_api)]
405 /// use std::alloc::System;
407 /// let five = Box::try_new_in(5, System)?;
408 /// # Ok::<(), std::alloc::AllocError>(())
410 #[unstable(feature = "allocator_api", issue = "32838")]
411 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
413 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
416 A: ~const Allocator + ~const Destruct,
418 let mut boxed = Self::try_new_uninit_in(alloc)?;
420 boxed.as_mut_ptr().write(x);
421 Ok(boxed.assume_init())
425 /// Constructs a new box with uninitialized contents in the provided allocator.
430 /// #![feature(allocator_api, new_uninit)]
432 /// use std::alloc::System;
434 /// let mut five = Box::<u32, _>::new_uninit_in(System);
436 /// let five = unsafe {
437 /// // Deferred initialization:
438 /// five.as_mut_ptr().write(5);
440 /// five.assume_init()
443 /// assert_eq!(*five, 5)
445 #[unstable(feature = "allocator_api", issue = "32838")]
446 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
447 #[cfg(not(no_global_oom_handling))]
449 // #[unstable(feature = "new_uninit", issue = "63291")]
450 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
452 A: ~const Allocator + ~const Destruct,
454 let layout = Layout::new::<mem::MaybeUninit<T>>();
455 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
456 // That would make code size bigger.
457 match Box::try_new_uninit_in(alloc) {
459 Err(_) => handle_alloc_error(layout),
463 /// Constructs a new box with uninitialized contents in the provided allocator,
464 /// returning an error if the allocation fails
469 /// #![feature(allocator_api, new_uninit)]
471 /// use std::alloc::System;
473 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
475 /// let five = unsafe {
476 /// // Deferred initialization:
477 /// five.as_mut_ptr().write(5);
479 /// five.assume_init()
482 /// assert_eq!(*five, 5);
483 /// # Ok::<(), std::alloc::AllocError>(())
485 #[unstable(feature = "allocator_api", issue = "32838")]
486 // #[unstable(feature = "new_uninit", issue = "63291")]
487 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
488 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
490 A: ~const Allocator + ~const Destruct,
492 let layout = Layout::new::<mem::MaybeUninit<T>>();
493 let ptr = alloc.allocate(layout)?.cast();
494 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
497 /// Constructs a new `Box` with uninitialized contents, with the memory
498 /// being filled with `0` bytes in the provided allocator.
500 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
506 /// #![feature(allocator_api, new_uninit)]
508 /// use std::alloc::System;
510 /// let zero = Box::<u32, _>::new_zeroed_in(System);
511 /// let zero = unsafe { zero.assume_init() };
513 /// assert_eq!(*zero, 0)
516 /// [zeroed]: mem::MaybeUninit::zeroed
517 #[unstable(feature = "allocator_api", issue = "32838")]
518 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
519 #[cfg(not(no_global_oom_handling))]
520 // #[unstable(feature = "new_uninit", issue = "63291")]
522 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
524 A: ~const Allocator + ~const Destruct,
526 let layout = Layout::new::<mem::MaybeUninit<T>>();
527 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
528 // That would make code size bigger.
529 match Box::try_new_zeroed_in(alloc) {
531 Err(_) => handle_alloc_error(layout),
535 /// Constructs a new `Box` with uninitialized contents, with the memory
536 /// being filled with `0` bytes in the provided allocator,
537 /// returning an error if the allocation fails,
539 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
545 /// #![feature(allocator_api, new_uninit)]
547 /// use std::alloc::System;
549 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
550 /// let zero = unsafe { zero.assume_init() };
552 /// assert_eq!(*zero, 0);
553 /// # Ok::<(), std::alloc::AllocError>(())
556 /// [zeroed]: mem::MaybeUninit::zeroed
557 #[unstable(feature = "allocator_api", issue = "32838")]
558 // #[unstable(feature = "new_uninit", issue = "63291")]
559 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
560 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
562 A: ~const Allocator + ~const Destruct,
564 let layout = Layout::new::<mem::MaybeUninit<T>>();
565 let ptr = 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")]
578 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
581 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
583 A: 'static + ~const Allocator + ~const Destruct,
585 Self::into_pin(Self::new_in(x, alloc))
588 /// Converts a `Box<T>` into a `Box<[T]>`
590 /// This conversion does not allocate on the heap and happens in place.
591 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
592 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
593 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
594 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
595 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
598 /// Consumes the `Box`, returning the wrapped value.
603 /// #![feature(box_into_inner)]
605 /// let c = Box::new(5);
607 /// assert_eq!(Box::into_inner(c), 5);
609 #[unstable(feature = "box_into_inner", issue = "80437")]
610 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
612 pub const fn into_inner(boxed: Self) -> T
614 Self: ~const Destruct,
621 /// Constructs a new boxed slice with uninitialized contents.
626 /// #![feature(new_uninit)]
628 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
630 /// let values = unsafe {
631 /// // Deferred initialization:
632 /// values[0].as_mut_ptr().write(1);
633 /// values[1].as_mut_ptr().write(2);
634 /// values[2].as_mut_ptr().write(3);
636 /// values.assume_init()
639 /// assert_eq!(*values, [1, 2, 3])
641 #[cfg(not(no_global_oom_handling))]
642 #[unstable(feature = "new_uninit", issue = "63291")]
644 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
645 unsafe { RawVec::with_capacity(len).into_box(len) }
648 /// Constructs a new boxed slice with uninitialized contents, with the memory
649 /// being filled with `0` bytes.
651 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
657 /// #![feature(new_uninit)]
659 /// let values = Box::<[u32]>::new_zeroed_slice(3);
660 /// let values = unsafe { values.assume_init() };
662 /// assert_eq!(*values, [0, 0, 0])
665 /// [zeroed]: mem::MaybeUninit::zeroed
666 #[cfg(not(no_global_oom_handling))]
667 #[unstable(feature = "new_uninit", issue = "63291")]
669 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
670 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
673 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
674 /// the allocation fails
679 /// #![feature(allocator_api, new_uninit)]
681 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
682 /// let values = unsafe {
683 /// // Deferred initialization:
684 /// values[0].as_mut_ptr().write(1);
685 /// values[1].as_mut_ptr().write(2);
686 /// values[2].as_mut_ptr().write(3);
687 /// values.assume_init()
690 /// assert_eq!(*values, [1, 2, 3]);
691 /// # Ok::<(), std::alloc::AllocError>(())
693 #[unstable(feature = "allocator_api", issue = "32838")]
695 pub fn try_new_uninit_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(layout)?;
702 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
706 /// Constructs a new boxed slice with uninitialized contents, with the memory
707 /// being filled with `0` bytes. Returns an error if the allocation fails
709 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
715 /// #![feature(allocator_api, new_uninit)]
717 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
718 /// let values = unsafe { values.assume_init() };
720 /// assert_eq!(*values, [0, 0, 0]);
721 /// # Ok::<(), std::alloc::AllocError>(())
724 /// [zeroed]: mem::MaybeUninit::zeroed
725 #[unstable(feature = "allocator_api", issue = "32838")]
727 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
729 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
731 Err(_) => return Err(AllocError),
733 let ptr = Global.allocate_zeroed(layout)?;
734 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
739 impl<T, A: Allocator> Box<[T], A> {
740 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
745 /// #![feature(allocator_api, new_uninit)]
747 /// use std::alloc::System;
749 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
751 /// let values = unsafe {
752 /// // Deferred initialization:
753 /// values[0].as_mut_ptr().write(1);
754 /// values[1].as_mut_ptr().write(2);
755 /// values[2].as_mut_ptr().write(3);
757 /// values.assume_init()
760 /// assert_eq!(*values, [1, 2, 3])
762 #[cfg(not(no_global_oom_handling))]
763 #[unstable(feature = "allocator_api", issue = "32838")]
764 // #[unstable(feature = "new_uninit", issue = "63291")]
766 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
767 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
770 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
771 /// with the memory being filled with `0` bytes.
773 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
779 /// #![feature(allocator_api, new_uninit)]
781 /// use std::alloc::System;
783 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
784 /// let values = unsafe { values.assume_init() };
786 /// assert_eq!(*values, [0, 0, 0])
789 /// [zeroed]: mem::MaybeUninit::zeroed
790 #[cfg(not(no_global_oom_handling))]
791 #[unstable(feature = "allocator_api", issue = "32838")]
792 // #[unstable(feature = "new_uninit", issue = "63291")]
794 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
795 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
799 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
800 /// Converts to `Box<T, A>`.
804 /// As with [`MaybeUninit::assume_init`],
805 /// it is up to the caller to guarantee that the value
806 /// really is in an initialized state.
807 /// Calling this when the content is not yet fully initialized
808 /// causes immediate undefined behavior.
810 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
815 /// #![feature(new_uninit)]
817 /// let mut five = Box::<u32>::new_uninit();
819 /// let five: Box<u32> = unsafe {
820 /// // Deferred initialization:
821 /// five.as_mut_ptr().write(5);
823 /// five.assume_init()
826 /// assert_eq!(*five, 5)
828 #[unstable(feature = "new_uninit", issue = "63291")]
829 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
831 pub const unsafe fn assume_init(self) -> Box<T, A> {
832 let (raw, alloc) = Box::into_raw_with_allocator(self);
833 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
836 /// Writes the value and converts to `Box<T, A>`.
838 /// This method converts the box similarly to [`Box::assume_init`] but
839 /// writes `value` into it before conversion thus guaranteeing safety.
840 /// In some scenarios use of this method may improve performance because
841 /// the compiler may be able to optimize copying from stack.
846 /// #![feature(new_uninit)]
848 /// let big_box = Box::<[usize; 1024]>::new_uninit();
850 /// let mut array = [0; 1024];
851 /// for (i, place) in array.iter_mut().enumerate() {
855 /// // The optimizer may be able to elide this copy, so previous code writes
856 /// // to heap directly.
857 /// let big_box = Box::write(big_box, array);
859 /// for (i, x) in big_box.iter().enumerate() {
860 /// assert_eq!(*x, i);
863 #[unstable(feature = "new_uninit", issue = "63291")]
864 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
866 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
868 (*boxed).write(value);
874 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
875 /// Converts to `Box<[T], A>`.
879 /// As with [`MaybeUninit::assume_init`],
880 /// it is up to the caller to guarantee that the values
881 /// really are in an initialized state.
882 /// Calling this when the content is not yet fully initialized
883 /// causes immediate undefined behavior.
885 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
890 /// #![feature(new_uninit)]
892 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
894 /// let values = unsafe {
895 /// // Deferred initialization:
896 /// values[0].as_mut_ptr().write(1);
897 /// values[1].as_mut_ptr().write(2);
898 /// values[2].as_mut_ptr().write(3);
900 /// values.assume_init()
903 /// assert_eq!(*values, [1, 2, 3])
905 #[unstable(feature = "new_uninit", issue = "63291")]
907 pub unsafe fn assume_init(self) -> Box<[T], A> {
908 let (raw, alloc) = Box::into_raw_with_allocator(self);
909 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
913 impl<T: ?Sized> Box<T> {
914 /// Constructs a box from a raw pointer.
916 /// After calling this function, the raw pointer is owned by the
917 /// resulting `Box`. Specifically, the `Box` destructor will call
918 /// the destructor of `T` and free the allocated memory. For this
919 /// to be safe, the memory must have been allocated in accordance
920 /// with the [memory layout] used by `Box` .
924 /// This function is unsafe because improper use may lead to
925 /// memory problems. For example, a double-free may occur if the
926 /// function is called twice on the same raw pointer.
928 /// The safety conditions are described in the [memory layout] section.
932 /// Recreate a `Box` which was previously converted to a raw pointer
933 /// using [`Box::into_raw`]:
935 /// let x = Box::new(5);
936 /// let ptr = Box::into_raw(x);
937 /// let x = unsafe { Box::from_raw(ptr) };
939 /// Manually create a `Box` from scratch by using the global allocator:
941 /// use std::alloc::{alloc, Layout};
944 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
945 /// // In general .write is required to avoid attempting to destruct
946 /// // the (uninitialized) previous contents of `ptr`, though for this
947 /// // simple example `*ptr = 5` would have worked as well.
949 /// let x = Box::from_raw(ptr);
953 /// [memory layout]: self#memory-layout
954 /// [`Layout`]: crate::Layout
955 #[stable(feature = "box_raw", since = "1.4.0")]
957 #[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `Box`"]
958 pub unsafe fn from_raw(raw: *mut T) -> Self {
959 unsafe { Self::from_raw_in(raw, Global) }
963 impl<T: ?Sized, A: Allocator> Box<T, A> {
964 /// Constructs a box from a raw pointer in the given allocator.
966 /// After calling this function, the raw pointer is owned by the
967 /// resulting `Box`. Specifically, the `Box` destructor will call
968 /// the destructor of `T` and free the allocated memory. For this
969 /// to be safe, the memory must have been allocated in accordance
970 /// with the [memory layout] used by `Box` .
974 /// This function is unsafe because improper use may lead to
975 /// memory problems. For example, a double-free may occur if the
976 /// function is called twice on the same raw pointer.
981 /// Recreate a `Box` which was previously converted to a raw pointer
982 /// using [`Box::into_raw_with_allocator`]:
984 /// #![feature(allocator_api)]
986 /// use std::alloc::System;
988 /// let x = Box::new_in(5, System);
989 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
990 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
992 /// Manually create a `Box` from scratch by using the system allocator:
994 /// #![feature(allocator_api, slice_ptr_get)]
996 /// use std::alloc::{Allocator, Layout, System};
999 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1000 /// // In general .write is required to avoid attempting to destruct
1001 /// // the (uninitialized) previous contents of `ptr`, though for this
1002 /// // simple example `*ptr = 5` would have worked as well.
1004 /// let x = Box::from_raw_in(ptr, System);
1006 /// # Ok::<(), std::alloc::AllocError>(())
1009 /// [memory layout]: self#memory-layout
1010 /// [`Layout`]: crate::Layout
1011 #[unstable(feature = "allocator_api", issue = "32838")]
1012 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1014 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1015 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1018 /// Consumes the `Box`, returning a wrapped raw pointer.
1020 /// The pointer will be properly aligned and non-null.
1022 /// After calling this function, the caller is responsible for the
1023 /// memory previously managed by the `Box`. In particular, the
1024 /// caller should properly destroy `T` and release the memory, taking
1025 /// into account the [memory layout] used by `Box`. The easiest way to
1026 /// do this is to convert the raw pointer back into a `Box` with the
1027 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1030 /// Note: this is an associated function, which means that you have
1031 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1032 /// is so that there is no conflict with a method on the inner type.
1035 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1036 /// for automatic cleanup:
1038 /// let x = Box::new(String::from("Hello"));
1039 /// let ptr = Box::into_raw(x);
1040 /// let x = unsafe { Box::from_raw(ptr) };
1042 /// Manual cleanup by explicitly running the destructor and deallocating
1045 /// use std::alloc::{dealloc, Layout};
1048 /// let x = Box::new(String::from("Hello"));
1049 /// let p = Box::into_raw(x);
1051 /// ptr::drop_in_place(p);
1052 /// dealloc(p as *mut u8, Layout::new::<String>());
1056 /// [memory layout]: self#memory-layout
1057 #[stable(feature = "box_raw", since = "1.4.0")]
1059 pub fn into_raw(b: Self) -> *mut T {
1060 Self::into_raw_with_allocator(b).0
1063 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1065 /// The pointer will be properly aligned and non-null.
1067 /// After calling this function, the caller is responsible for the
1068 /// memory previously managed by the `Box`. In particular, the
1069 /// caller should properly destroy `T` and release the memory, taking
1070 /// into account the [memory layout] used by `Box`. The easiest way to
1071 /// do this is to convert the raw pointer back into a `Box` with the
1072 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1075 /// Note: this is an associated function, which means that you have
1076 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1077 /// is so that there is no conflict with a method on the inner type.
1080 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1081 /// for automatic cleanup:
1083 /// #![feature(allocator_api)]
1085 /// use std::alloc::System;
1087 /// let x = Box::new_in(String::from("Hello"), System);
1088 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1089 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1091 /// Manual cleanup by explicitly running the destructor and deallocating
1094 /// #![feature(allocator_api)]
1096 /// use std::alloc::{Allocator, Layout, System};
1097 /// use std::ptr::{self, NonNull};
1099 /// let x = Box::new_in(String::from("Hello"), System);
1100 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1102 /// ptr::drop_in_place(ptr);
1103 /// let non_null = NonNull::new_unchecked(ptr);
1104 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1108 /// [memory layout]: self#memory-layout
1109 #[unstable(feature = "allocator_api", issue = "32838")]
1110 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1112 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1113 let (leaked, alloc) = Box::into_unique(b);
1114 (leaked.as_ptr(), alloc)
1118 feature = "ptr_internals",
1120 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1122 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1125 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1126 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1127 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1128 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1129 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1130 // behaves correctly.
1131 let alloc = unsafe { ptr::read(&b.1) };
1132 (Unique::from(Box::leak(b)), alloc)
1135 /// Returns a reference to the underlying allocator.
1137 /// Note: this is an associated function, which means that you have
1138 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1139 /// is so that there is no conflict with a method on the inner type.
1140 #[unstable(feature = "allocator_api", issue = "32838")]
1141 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1143 pub const fn allocator(b: &Self) -> &A {
1147 /// Consumes and leaks the `Box`, returning a mutable reference,
1148 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1149 /// `'a`. If the type has only static references, or none at all, then this
1150 /// may be chosen to be `'static`.
1152 /// This function is mainly useful for data that lives for the remainder of
1153 /// the program's life. Dropping the returned reference will cause a memory
1154 /// leak. If this is not acceptable, the reference should first be wrapped
1155 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1156 /// then be dropped which will properly destroy `T` and release the
1157 /// allocated memory.
1159 /// Note: this is an associated function, which means that you have
1160 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1161 /// is so that there is no conflict with a method on the inner type.
1168 /// let x = Box::new(41);
1169 /// let static_ref: &'static mut usize = Box::leak(x);
1170 /// *static_ref += 1;
1171 /// assert_eq!(*static_ref, 42);
1177 /// let x = vec![1, 2, 3].into_boxed_slice();
1178 /// let static_ref = Box::leak(x);
1179 /// static_ref[0] = 4;
1180 /// assert_eq!(*static_ref, [4, 2, 3]);
1182 #[stable(feature = "box_leak", since = "1.26.0")]
1183 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1185 pub const fn leak<'a>(b: Self) -> &'a mut T
1189 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1192 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1193 /// `*boxed` will be pinned in memory and unable to be moved.
1195 /// This conversion does not allocate on the heap and happens in place.
1197 /// This is also available via [`From`].
1199 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1200 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1201 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1202 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1206 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1207 /// as it'll introduce an ambiguity when calling `Pin::from`.
1208 /// A demonstration of such a poor impl is shown below.
1211 /// # use std::pin::Pin;
1212 /// struct Foo; // A type defined in this crate.
1213 /// impl From<Box<()>> for Pin<Foo> {
1214 /// fn from(_: Box<()>) -> Pin<Foo> {
1219 /// let foo = Box::new(());
1220 /// let bar = Pin::from(foo);
1222 #[stable(feature = "box_into_pin", since = "1.63.0")]
1223 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1224 pub const fn into_pin(boxed: Self) -> Pin<Self>
1228 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1229 // when `T: !Unpin`, so it's safe to pin it directly without any
1230 // additional requirements.
1231 unsafe { Pin::new_unchecked(boxed) }
1235 #[stable(feature = "rust1", since = "1.0.0")]
1236 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1237 fn drop(&mut self) {
1238 // FIXME: Do nothing, drop is currently performed by compiler.
1242 #[cfg(not(no_global_oom_handling))]
1243 #[stable(feature = "rust1", since = "1.0.0")]
1244 impl<T: Default> Default for Box<T> {
1245 /// Creates a `Box<T>`, with the `Default` value for T.
1246 fn default() -> Self {
1248 Box::new(T::default())
1252 #[cfg(not(no_global_oom_handling))]
1253 #[stable(feature = "rust1", since = "1.0.0")]
1254 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1255 impl<T> const Default for Box<[T]> {
1256 fn default() -> Self {
1257 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1262 #[cfg(not(no_global_oom_handling))]
1263 #[stable(feature = "default_box_extra", since = "1.17.0")]
1264 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1265 impl const Default for Box<str> {
1266 fn default() -> Self {
1267 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1268 let ptr: Unique<str> = unsafe {
1269 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1270 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1276 #[cfg(not(no_global_oom_handling))]
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1279 /// Returns a new box with a `clone()` of this box's contents.
1284 /// let x = Box::new(5);
1285 /// let y = x.clone();
1287 /// // The value is the same
1288 /// assert_eq!(x, y);
1290 /// // But they are unique objects
1291 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1294 fn clone(&self) -> Self {
1295 // Pre-allocate memory to allow writing the cloned value directly.
1296 let mut boxed = Self::new_uninit_in(self.1.clone());
1298 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1303 /// Copies `source`'s contents into `self` without creating a new allocation.
1308 /// let x = Box::new(5);
1309 /// let mut y = Box::new(10);
1310 /// let yp: *const i32 = &*y;
1312 /// y.clone_from(&x);
1314 /// // The value is the same
1315 /// assert_eq!(x, y);
1317 /// // And no allocation occurred
1318 /// assert_eq!(yp, &*y);
1321 fn clone_from(&mut self, source: &Self) {
1322 (**self).clone_from(&(**source));
1326 #[cfg(not(no_global_oom_handling))]
1327 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1328 impl Clone for Box<str> {
1329 fn clone(&self) -> Self {
1330 // this makes a copy of the data
1331 let buf: Box<[u8]> = self.as_bytes().into();
1332 unsafe { from_boxed_utf8_unchecked(buf) }
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1339 fn eq(&self, other: &Self) -> bool {
1340 PartialEq::eq(&**self, &**other)
1343 fn ne(&self, other: &Self) -> bool {
1344 PartialEq::ne(&**self, &**other)
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1350 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1351 PartialOrd::partial_cmp(&**self, &**other)
1354 fn lt(&self, other: &Self) -> bool {
1355 PartialOrd::lt(&**self, &**other)
1358 fn le(&self, other: &Self) -> bool {
1359 PartialOrd::le(&**self, &**other)
1362 fn ge(&self, other: &Self) -> bool {
1363 PartialOrd::ge(&**self, &**other)
1366 fn gt(&self, other: &Self) -> bool {
1367 PartialOrd::gt(&**self, &**other)
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1373 fn cmp(&self, other: &Self) -> Ordering {
1374 Ord::cmp(&**self, &**other)
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1382 fn hash<H: Hasher>(&self, state: &mut H) {
1383 (**self).hash(state);
1387 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1388 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1389 fn finish(&self) -> u64 {
1392 fn write(&mut self, bytes: &[u8]) {
1393 (**self).write(bytes)
1395 fn write_u8(&mut self, i: u8) {
1396 (**self).write_u8(i)
1398 fn write_u16(&mut self, i: u16) {
1399 (**self).write_u16(i)
1401 fn write_u32(&mut self, i: u32) {
1402 (**self).write_u32(i)
1404 fn write_u64(&mut self, i: u64) {
1405 (**self).write_u64(i)
1407 fn write_u128(&mut self, i: u128) {
1408 (**self).write_u128(i)
1410 fn write_usize(&mut self, i: usize) {
1411 (**self).write_usize(i)
1413 fn write_i8(&mut self, i: i8) {
1414 (**self).write_i8(i)
1416 fn write_i16(&mut self, i: i16) {
1417 (**self).write_i16(i)
1419 fn write_i32(&mut self, i: i32) {
1420 (**self).write_i32(i)
1422 fn write_i64(&mut self, i: i64) {
1423 (**self).write_i64(i)
1425 fn write_i128(&mut self, i: i128) {
1426 (**self).write_i128(i)
1428 fn write_isize(&mut self, i: isize) {
1429 (**self).write_isize(i)
1431 fn write_length_prefix(&mut self, len: usize) {
1432 (**self).write_length_prefix(len)
1434 fn write_str(&mut self, s: &str) {
1435 (**self).write_str(s)
1439 #[cfg(not(no_global_oom_handling))]
1440 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1441 impl<T> From<T> for Box<T> {
1442 /// Converts a `T` into a `Box<T>`
1444 /// The conversion allocates on the heap and moves `t`
1445 /// from the stack into it.
1451 /// let boxed = Box::new(5);
1453 /// assert_eq!(Box::from(x), boxed);
1455 fn from(t: T) -> Self {
1460 #[stable(feature = "pin", since = "1.33.0")]
1461 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1462 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1466 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1467 /// `*boxed` will be pinned in memory and unable to be moved.
1469 /// This conversion does not allocate on the heap and happens in place.
1471 /// This is also available via [`Box::into_pin`].
1473 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
1474 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1475 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
1476 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1477 fn from(boxed: Box<T, A>) -> Self {
1478 Box::into_pin(boxed)
1482 #[cfg(not(no_global_oom_handling))]
1483 #[stable(feature = "box_from_slice", since = "1.17.0")]
1484 impl<T: Copy> From<&[T]> for Box<[T]> {
1485 /// Converts a `&[T]` into a `Box<[T]>`
1487 /// This conversion allocates on the heap
1488 /// and performs a copy of `slice` and its contents.
1492 /// // create a &[u8] which will be used to create a Box<[u8]>
1493 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1494 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1496 /// println!("{boxed_slice:?}");
1498 fn from(slice: &[T]) -> Box<[T]> {
1499 let len = slice.len();
1500 let buf = RawVec::with_capacity(len);
1502 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1503 buf.into_box(slice.len()).assume_init()
1508 #[cfg(not(no_global_oom_handling))]
1509 #[stable(feature = "box_from_cow", since = "1.45.0")]
1510 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1511 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1513 /// When `cow` is the `Cow::Borrowed` variant, this
1514 /// conversion allocates on the heap and copies the
1515 /// underlying slice. Otherwise, it will try to reuse the owned
1516 /// `Vec`'s allocation.
1518 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1520 Cow::Borrowed(slice) => Box::from(slice),
1521 Cow::Owned(slice) => Box::from(slice),
1526 #[cfg(not(no_global_oom_handling))]
1527 #[stable(feature = "box_from_slice", since = "1.17.0")]
1528 impl From<&str> for Box<str> {
1529 /// Converts a `&str` into a `Box<str>`
1531 /// This conversion allocates on the heap
1532 /// and performs a copy of `s`.
1537 /// let boxed: Box<str> = Box::from("hello");
1538 /// println!("{boxed}");
1541 fn from(s: &str) -> Box<str> {
1542 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1546 #[cfg(not(no_global_oom_handling))]
1547 #[stable(feature = "box_from_cow", since = "1.45.0")]
1548 impl From<Cow<'_, str>> for Box<str> {
1549 /// Converts a `Cow<'_, str>` into a `Box<str>`
1551 /// When `cow` is the `Cow::Borrowed` variant, this
1552 /// conversion allocates on the heap and copies the
1553 /// underlying `str`. Otherwise, it will try to reuse the owned
1554 /// `String`'s allocation.
1559 /// use std::borrow::Cow;
1561 /// let unboxed = Cow::Borrowed("hello");
1562 /// let boxed: Box<str> = Box::from(unboxed);
1563 /// println!("{boxed}");
1567 /// # use std::borrow::Cow;
1568 /// let unboxed = Cow::Owned("hello".to_string());
1569 /// let boxed: Box<str> = Box::from(unboxed);
1570 /// println!("{boxed}");
1573 fn from(cow: Cow<'_, str>) -> Box<str> {
1575 Cow::Borrowed(s) => Box::from(s),
1576 Cow::Owned(s) => Box::from(s),
1581 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1582 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1583 /// Converts a `Box<str>` into a `Box<[u8]>`
1585 /// This conversion does not allocate on the heap and happens in place.
1589 /// // create a Box<str> which will be used to create a Box<[u8]>
1590 /// let boxed: Box<str> = Box::from("hello");
1591 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1593 /// // create a &[u8] which will be used to create a Box<[u8]>
1594 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1595 /// let boxed_slice = Box::from(slice);
1597 /// assert_eq!(boxed_slice, boxed_str);
1600 fn from(s: Box<str, A>) -> Self {
1601 let (raw, alloc) = Box::into_raw_with_allocator(s);
1602 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1606 #[cfg(not(no_global_oom_handling))]
1607 #[stable(feature = "box_from_array", since = "1.45.0")]
1608 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1609 /// Converts a `[T; N]` into a `Box<[T]>`
1611 /// This conversion moves the array to newly heap-allocated memory.
1616 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1617 /// println!("{boxed:?}");
1619 fn from(array: [T; N]) -> Box<[T]> {
1625 /// Casts a boxed slice to a boxed array.
1629 /// `boxed_slice.len()` must be exactly `N`.
1630 unsafe fn boxed_slice_as_array_unchecked<T, A: Allocator, const N: usize>(
1631 boxed_slice: Box<[T], A>,
1632 ) -> Box<[T; N], A> {
1633 debug_assert_eq!(boxed_slice.len(), N);
1635 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
1636 // SAFETY: Pointer and allocator came from an existing box,
1637 // and our safety condition requires that the length is exactly `N`
1638 unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) }
1641 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1642 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1643 type Error = Box<[T]>;
1645 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1647 /// The conversion occurs in-place and does not require a
1648 /// new memory allocation.
1652 /// Returns the old `Box<[T]>` in the `Err` variant if
1653 /// `boxed_slice.len()` does not equal `N`.
1654 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1655 if boxed_slice.len() == N {
1656 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1663 #[cfg(not(no_global_oom_handling))]
1664 #[stable(feature = "boxed_array_try_from_vec", since = "1.66.0")]
1665 impl<T, const N: usize> TryFrom<Vec<T>> for Box<[T; N]> {
1666 type Error = Vec<T>;
1668 /// Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.
1670 /// Like [`Vec::into_boxed_slice`], this is in-place if `vec.capacity() == N`,
1671 /// but will require a reallocation otherwise.
1675 /// Returns the original `Vec<T>` in the `Err` variant if
1676 /// `boxed_slice.len()` does not equal `N`.
1680 /// This can be used with [`vec!`] to create an array on the heap:
1683 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
1684 /// assert_eq!(state.len(), 100);
1686 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1688 let boxed_slice = vec.into_boxed_slice();
1689 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1696 impl<A: Allocator> Box<dyn Any, A> {
1697 /// Attempt to downcast the box to a concrete type.
1702 /// use std::any::Any;
1704 /// fn print_if_string(value: Box<dyn Any>) {
1705 /// if let Ok(string) = value.downcast::<String>() {
1706 /// println!("String ({}): {}", string.len(), string);
1710 /// let my_string = "Hello World".to_string();
1711 /// print_if_string(Box::new(my_string));
1712 /// print_if_string(Box::new(0i8));
1715 #[stable(feature = "rust1", since = "1.0.0")]
1716 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1717 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1720 /// Downcasts the box to a concrete type.
1722 /// For a safe alternative see [`downcast`].
1727 /// #![feature(downcast_unchecked)]
1729 /// use std::any::Any;
1731 /// let x: Box<dyn Any> = Box::new(1_usize);
1734 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1740 /// The contained value must be of type `T`. Calling this method
1741 /// with the incorrect type is *undefined behavior*.
1743 /// [`downcast`]: Self::downcast
1745 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1746 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1747 debug_assert!(self.is::<T>());
1749 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1750 Box::from_raw_in(raw as *mut T, alloc)
1755 impl<A: Allocator> Box<dyn Any + Send, A> {
1756 /// Attempt to downcast the box to a concrete type.
1761 /// use std::any::Any;
1763 /// fn print_if_string(value: Box<dyn Any + Send>) {
1764 /// if let Ok(string) = value.downcast::<String>() {
1765 /// println!("String ({}): {}", string.len(), string);
1769 /// let my_string = "Hello World".to_string();
1770 /// print_if_string(Box::new(my_string));
1771 /// print_if_string(Box::new(0i8));
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1776 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1779 /// Downcasts the box to a concrete type.
1781 /// For a safe alternative see [`downcast`].
1786 /// #![feature(downcast_unchecked)]
1788 /// use std::any::Any;
1790 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1793 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1799 /// The contained value must be of type `T`. Calling this method
1800 /// with the incorrect type is *undefined behavior*.
1802 /// [`downcast`]: Self::downcast
1804 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1805 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1806 debug_assert!(self.is::<T>());
1808 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1809 Box::from_raw_in(raw as *mut T, alloc)
1814 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1815 /// Attempt to downcast the box to a concrete type.
1820 /// use std::any::Any;
1822 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1823 /// if let Ok(string) = value.downcast::<String>() {
1824 /// println!("String ({}): {}", string.len(), string);
1828 /// let my_string = "Hello World".to_string();
1829 /// print_if_string(Box::new(my_string));
1830 /// print_if_string(Box::new(0i8));
1833 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1834 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1835 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1838 /// Downcasts the box to a concrete type.
1840 /// For a safe alternative see [`downcast`].
1845 /// #![feature(downcast_unchecked)]
1847 /// use std::any::Any;
1849 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1852 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1858 /// The contained value must be of type `T`. Calling this method
1859 /// with the incorrect type is *undefined behavior*.
1861 /// [`downcast`]: Self::downcast
1863 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1864 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1865 debug_assert!(self.is::<T>());
1867 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1868 Box::into_raw_with_allocator(self);
1869 Box::from_raw_in(raw as *mut T, alloc)
1874 #[stable(feature = "rust1", since = "1.0.0")]
1875 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1876 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1877 fmt::Display::fmt(&**self, f)
1881 #[stable(feature = "rust1", since = "1.0.0")]
1882 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1883 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1884 fmt::Debug::fmt(&**self, f)
1888 #[stable(feature = "rust1", since = "1.0.0")]
1889 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1890 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1891 // It's not possible to extract the inner Uniq directly from the Box,
1892 // instead we cast it to a *const which aliases the Unique
1893 let ptr: *const T = &**self;
1894 fmt::Pointer::fmt(&ptr, f)
1898 #[stable(feature = "rust1", since = "1.0.0")]
1899 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1900 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1903 fn deref(&self) -> &T {
1908 #[stable(feature = "rust1", since = "1.0.0")]
1909 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1910 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1911 fn deref_mut(&mut self) -> &mut T {
1916 #[unstable(feature = "receiver_trait", issue = "none")]
1917 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1919 #[stable(feature = "rust1", since = "1.0.0")]
1920 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1921 type Item = I::Item;
1922 fn next(&mut self) -> Option<I::Item> {
1925 fn size_hint(&self) -> (usize, Option<usize>) {
1926 (**self).size_hint()
1928 fn nth(&mut self, n: usize) -> Option<I::Item> {
1931 fn last(self) -> Option<I::Item> {
1938 fn last(self) -> Option<Self::Item>;
1941 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1942 type Item = I::Item;
1943 default fn last(self) -> Option<I::Item> {
1945 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1949 self.fold(None, some)
1953 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1954 /// instead of the default.
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1957 fn last(self) -> Option<I::Item> {
1962 #[stable(feature = "rust1", since = "1.0.0")]
1963 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1964 fn next_back(&mut self) -> Option<I::Item> {
1965 (**self).next_back()
1967 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1968 (**self).nth_back(n)
1971 #[stable(feature = "rust1", since = "1.0.0")]
1972 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1973 fn len(&self) -> usize {
1976 fn is_empty(&self) -> bool {
1981 #[stable(feature = "fused", since = "1.26.0")]
1982 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1985 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1986 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1987 type Output = <F as FnOnce<Args>>::Output;
1989 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1990 <F as FnOnce<Args>>::call_once(*self, args)
1994 #[cfg(not(bootstrap))]
1995 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1996 impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1997 type Output = <F as FnOnce<Args>>::Output;
1999 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
2000 <F as FnOnce<Args>>::call_once(*self, args)
2005 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2006 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
2007 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
2008 <F as FnMut<Args>>::call_mut(self, args)
2012 #[cfg(not(bootstrap))]
2013 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2014 impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
2015 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
2016 <F as FnMut<Args>>::call_mut(self, args)
2021 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2022 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2023 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2024 <F as Fn<Args>>::call(self, args)
2028 #[cfg(not(bootstrap))]
2029 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2030 impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2031 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2032 <F as Fn<Args>>::call(self, args)
2036 #[unstable(feature = "coerce_unsized", issue = "27732")]
2037 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2039 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2040 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2042 #[cfg(not(no_global_oom_handling))]
2043 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
2044 impl<I> FromIterator<I> for Box<[I]> {
2045 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
2046 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
2050 #[cfg(not(no_global_oom_handling))]
2051 #[stable(feature = "box_slice_clone", since = "1.3.0")]
2052 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2053 fn clone(&self) -> Self {
2054 let alloc = Box::allocator(self).clone();
2055 self.to_vec_in(alloc).into_boxed_slice()
2058 fn clone_from(&mut self, other: &Self) {
2059 if self.len() == other.len() {
2060 self.clone_from_slice(&other);
2062 *self = other.clone();
2067 #[stable(feature = "box_borrow", since = "1.1.0")]
2068 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
2069 fn borrow(&self) -> &T {
2074 #[stable(feature = "box_borrow", since = "1.1.0")]
2075 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
2076 fn borrow_mut(&mut self) -> &mut T {
2081 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2082 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2083 fn as_ref(&self) -> &T {
2088 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2089 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2090 fn as_mut(&mut self) -> &mut T {
2097 * We could have chosen not to add this impl, and instead have written a
2098 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2099 * because Box<T> implements Unpin even when T does not, as a result of
2102 * We chose this API instead of the alternative for a few reasons:
2103 * - Logically, it is helpful to understand pinning in regard to the
2104 * memory region being pointed to. For this reason none of the
2105 * standard library pointer types support projecting through a pin
2106 * (Box<T> is the only pointer type in std for which this would be
2108 * - It is in practice very useful to have Box<T> be unconditionally
2109 * Unpin because of trait objects, for which the structural auto
2110 * trait functionality does not apply (e.g., Box<dyn Foo> would
2111 * otherwise not be Unpin).
2113 * Another type with the same semantics as Box but only a conditional
2114 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2115 * could have a method to project a Pin<T> from it.
2117 #[stable(feature = "pin", since = "1.33.0")]
2118 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
2120 #[unstable(feature = "generator_trait", issue = "43122")]
2121 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2125 type Yield = G::Yield;
2126 type Return = G::Return;
2128 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2129 G::resume(Pin::new(&mut *self), arg)
2133 #[unstable(feature = "generator_trait", issue = "43122")]
2134 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2138 type Yield = G::Yield;
2139 type Return = G::Return;
2141 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2142 G::resume((*self).as_mut(), arg)
2146 #[stable(feature = "futures_api", since = "1.36.0")]
2147 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2151 type Output = F::Output;
2153 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2154 F::poll(Pin::new(&mut *self), cx)
2158 #[unstable(feature = "async_iterator", issue = "79024")]
2159 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2160 type Item = S::Item;
2162 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2163 Pin::new(&mut **self).poll_next(cx)
2166 fn size_hint(&self) -> (usize, Option<usize>) {
2167 (**self).size_hint()
2173 #[stable(feature = "error_downcast", since = "1.3.0")]
2174 #[rustc_allow_incoherent_impl]
2175 /// Attempts to downcast the box to a concrete type.
2176 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
2179 let raw: *mut dyn Error = Box::into_raw(self);
2180 Ok(Box::from_raw(raw as *mut T))
2188 impl dyn Error + Send {
2190 #[stable(feature = "error_downcast", since = "1.3.0")]
2191 #[rustc_allow_incoherent_impl]
2192 /// Attempts to downcast the box to a concrete type.
2193 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
2194 let err: Box<dyn Error> = self;
2195 <dyn Error>::downcast(err).map_err(|s| unsafe {
2196 // Reapply the `Send` marker.
2197 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
2202 impl dyn Error + Send + Sync {
2204 #[stable(feature = "error_downcast", since = "1.3.0")]
2205 #[rustc_allow_incoherent_impl]
2206 /// Attempts to downcast the box to a concrete type.
2207 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
2208 let err: Box<dyn Error> = self;
2209 <dyn Error>::downcast(err).map_err(|s| unsafe {
2210 // Reapply the `Send + Sync` marker.
2211 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
2216 #[cfg(not(no_global_oom_handling))]
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
2219 /// Converts a type of [`Error`] into a box of dyn [`Error`].
2224 /// use std::error::Error;
2228 /// #[derive(Debug)]
2231 /// impl fmt::Display for AnError {
2232 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2233 /// write!(f, "An error")
2237 /// impl Error for AnError {}
2239 /// let an_error = AnError;
2240 /// assert!(0 == mem::size_of_val(&an_error));
2241 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
2242 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2244 fn from(err: E) -> Box<dyn Error + 'a> {
2249 #[cfg(not(no_global_oom_handling))]
2250 #[stable(feature = "rust1", since = "1.0.0")]
2251 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
2252 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
2253 /// dyn [`Error`] + [`Send`] + [`Sync`].
2258 /// use std::error::Error;
2262 /// #[derive(Debug)]
2265 /// impl fmt::Display for AnError {
2266 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2267 /// write!(f, "An error")
2271 /// impl Error for AnError {}
2273 /// unsafe impl Send for AnError {}
2275 /// unsafe impl Sync for AnError {}
2277 /// let an_error = AnError;
2278 /// assert!(0 == mem::size_of_val(&an_error));
2279 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
2281 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2283 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
2288 #[cfg(not(no_global_oom_handling))]
2289 #[stable(feature = "rust1", since = "1.0.0")]
2290 impl From<String> for Box<dyn Error + Send + Sync> {
2291 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2296 /// use std::error::Error;
2299 /// let a_string_error = "a string error".to_string();
2300 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
2302 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2305 fn from(err: String) -> Box<dyn Error + Send + Sync> {
2306 struct StringError(String);
2308 impl Error for StringError {
2309 #[allow(deprecated)]
2310 fn description(&self) -> &str {
2315 impl fmt::Display for StringError {
2316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2317 fmt::Display::fmt(&self.0, f)
2321 // Purposefully skip printing "StringError(..)"
2322 impl fmt::Debug for StringError {
2323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2324 fmt::Debug::fmt(&self.0, f)
2328 Box::new(StringError(err))
2332 #[cfg(not(no_global_oom_handling))]
2333 #[stable(feature = "string_box_error", since = "1.6.0")]
2334 impl From<String> for Box<dyn Error> {
2335 /// Converts a [`String`] into a box of dyn [`Error`].
2340 /// use std::error::Error;
2343 /// let a_string_error = "a string error".to_string();
2344 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
2345 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2347 fn from(str_err: String) -> Box<dyn Error> {
2348 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
2349 let err2: Box<dyn Error> = err1;
2354 #[cfg(not(no_global_oom_handling))]
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
2357 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2359 /// [`str`]: prim@str
2364 /// use std::error::Error;
2367 /// let a_str_error = "a str error";
2368 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
2370 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2373 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
2374 From::from(String::from(err))
2378 #[cfg(not(no_global_oom_handling))]
2379 #[stable(feature = "string_box_error", since = "1.6.0")]
2380 impl From<&str> for Box<dyn Error> {
2381 /// Converts a [`str`] into a box of dyn [`Error`].
2383 /// [`str`]: prim@str
2388 /// use std::error::Error;
2391 /// let a_str_error = "a str error";
2392 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
2393 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2395 fn from(err: &str) -> Box<dyn Error> {
2396 From::from(String::from(err))
2400 #[cfg(not(no_global_oom_handling))]
2401 #[stable(feature = "cow_box_error", since = "1.22.0")]
2402 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
2403 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2408 /// use std::error::Error;
2410 /// use std::borrow::Cow;
2412 /// let a_cow_str_error = Cow::from("a str error");
2413 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
2415 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2417 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
2418 From::from(String::from(err))
2422 #[cfg(not(no_global_oom_handling))]
2423 #[stable(feature = "cow_box_error", since = "1.22.0")]
2424 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
2425 /// Converts a [`Cow`] into a box of dyn [`Error`].
2430 /// use std::error::Error;
2432 /// use std::borrow::Cow;
2434 /// let a_cow_str_error = Cow::from("a str error");
2435 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
2436 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2438 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
2439 From::from(String::from(err))
2443 #[stable(feature = "box_error", since = "1.8.0")]
2444 impl<T: core::error::Error> core::error::Error for Box<T> {
2445 #[allow(deprecated, deprecated_in_future)]
2446 fn description(&self) -> &str {
2447 core::error::Error::description(&**self)
2450 #[allow(deprecated)]
2451 fn cause(&self) -> Option<&dyn core::error::Error> {
2452 core::error::Error::cause(&**self)
2455 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
2456 core::error::Error::source(&**self)