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 use core::marker::Tuple;
162 use core::marker::{Destruct, Unpin, Unsize};
165 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
168 use core::ptr::{self, Unique};
169 use core::task::{Context, Poll};
171 #[cfg(not(no_global_oom_handling))]
172 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
173 use crate::alloc::{AllocError, Allocator, Global, Layout};
174 #[cfg(not(no_global_oom_handling))]
175 use crate::borrow::Cow;
176 use crate::raw_vec::RawVec;
177 #[cfg(not(no_global_oom_handling))]
178 use crate::str::from_boxed_utf8_unchecked;
179 #[cfg(not(no_global_oom_handling))]
180 use crate::string::String;
181 #[cfg(not(no_global_oom_handling))]
184 #[unstable(feature = "thin_box", issue = "92791")]
185 pub use thin::ThinBox;
189 /// A pointer type that uniquely owns a heap allocation of type `T`.
191 /// See the [module-level documentation](../../std/boxed/index.html) for more.
192 #[lang = "owned_box"]
194 #[stable(feature = "rust1", since = "1.0.0")]
195 // The declaration of the `Box` struct must be kept in sync with the
196 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
197 // on `box_free` for more details.
200 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
204 /// Allocates memory on the heap and then places `x` into it.
206 /// This doesn't actually allocate if `T` is zero-sized.
211 /// let five = Box::new(5);
213 #[cfg(all(not(no_global_oom_handling)))]
215 #[stable(feature = "rust1", since = "1.0.0")]
217 pub fn new(x: T) -> Self {
222 /// Constructs a new box with uninitialized contents.
227 /// #![feature(new_uninit)]
229 /// let mut five = Box::<u32>::new_uninit();
231 /// let five = unsafe {
232 /// // Deferred initialization:
233 /// five.as_mut_ptr().write(5);
235 /// five.assume_init()
238 /// assert_eq!(*five, 5)
240 #[cfg(not(no_global_oom_handling))]
241 #[unstable(feature = "new_uninit", issue = "63291")]
244 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
245 Self::new_uninit_in(Global)
248 /// Constructs a new `Box` with uninitialized contents, with the memory
249 /// being filled with `0` bytes.
251 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
257 /// #![feature(new_uninit)]
259 /// let zero = Box::<u32>::new_zeroed();
260 /// let zero = unsafe { zero.assume_init() };
262 /// assert_eq!(*zero, 0)
265 /// [zeroed]: mem::MaybeUninit::zeroed
266 #[cfg(not(no_global_oom_handling))]
268 #[unstable(feature = "new_uninit", issue = "63291")]
270 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
271 Self::new_zeroed_in(Global)
274 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
275 /// `x` will be pinned in memory and unable to be moved.
277 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
278 /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
279 /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
280 /// construct a (pinned) `Box` in a different way than with [`Box::new`].
281 #[cfg(not(no_global_oom_handling))]
282 #[stable(feature = "pin", since = "1.33.0")]
285 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")]
380 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
383 pub const fn new_in(x: T, alloc: A) -> Self
385 A: ~const Allocator + ~const Destruct,
387 let mut boxed = Self::new_uninit_in(alloc);
389 boxed.as_mut_ptr().write(x);
394 /// Allocates memory in the given allocator then places `x` into it,
395 /// returning an error if the allocation fails
397 /// This doesn't actually allocate if `T` is zero-sized.
402 /// #![feature(allocator_api)]
404 /// use std::alloc::System;
406 /// let five = Box::try_new_in(5, System)?;
407 /// # Ok::<(), std::alloc::AllocError>(())
409 #[unstable(feature = "allocator_api", issue = "32838")]
410 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
412 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
415 A: ~const Allocator + ~const Destruct,
417 let mut boxed = Self::try_new_uninit_in(alloc)?;
419 boxed.as_mut_ptr().write(x);
420 Ok(boxed.assume_init())
424 /// Constructs a new box with uninitialized contents in the provided allocator.
429 /// #![feature(allocator_api, new_uninit)]
431 /// use std::alloc::System;
433 /// let mut five = Box::<u32, _>::new_uninit_in(System);
435 /// let five = unsafe {
436 /// // Deferred initialization:
437 /// five.as_mut_ptr().write(5);
439 /// five.assume_init()
442 /// assert_eq!(*five, 5)
444 #[unstable(feature = "allocator_api", issue = "32838")]
445 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
446 #[cfg(not(no_global_oom_handling))]
448 // #[unstable(feature = "new_uninit", issue = "63291")]
449 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
451 A: ~const Allocator + ~const Destruct,
453 let layout = Layout::new::<mem::MaybeUninit<T>>();
454 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
455 // That would make code size bigger.
456 match Box::try_new_uninit_in(alloc) {
458 Err(_) => handle_alloc_error(layout),
462 /// Constructs a new box with uninitialized contents in the provided allocator,
463 /// returning an error if the allocation fails
468 /// #![feature(allocator_api, new_uninit)]
470 /// use std::alloc::System;
472 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
474 /// let five = unsafe {
475 /// // Deferred initialization:
476 /// five.as_mut_ptr().write(5);
478 /// five.assume_init()
481 /// assert_eq!(*five, 5);
482 /// # Ok::<(), std::alloc::AllocError>(())
484 #[unstable(feature = "allocator_api", issue = "32838")]
485 // #[unstable(feature = "new_uninit", issue = "63291")]
486 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
487 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
489 A: ~const Allocator + ~const Destruct,
491 let layout = Layout::new::<mem::MaybeUninit<T>>();
492 let ptr = alloc.allocate(layout)?.cast();
493 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
496 /// Constructs a new `Box` with uninitialized contents, with the memory
497 /// being filled with `0` bytes in the provided allocator.
499 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
505 /// #![feature(allocator_api, new_uninit)]
507 /// use std::alloc::System;
509 /// let zero = Box::<u32, _>::new_zeroed_in(System);
510 /// let zero = unsafe { zero.assume_init() };
512 /// assert_eq!(*zero, 0)
515 /// [zeroed]: mem::MaybeUninit::zeroed
516 #[unstable(feature = "allocator_api", issue = "32838")]
517 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
518 #[cfg(not(no_global_oom_handling))]
519 // #[unstable(feature = "new_uninit", issue = "63291")]
521 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
523 A: ~const Allocator + ~const Destruct,
525 let layout = Layout::new::<mem::MaybeUninit<T>>();
526 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
527 // That would make code size bigger.
528 match Box::try_new_zeroed_in(alloc) {
530 Err(_) => handle_alloc_error(layout),
534 /// Constructs a new `Box` with uninitialized contents, with the memory
535 /// being filled with `0` bytes in the provided allocator,
536 /// returning an error if the allocation fails,
538 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
544 /// #![feature(allocator_api, new_uninit)]
546 /// use std::alloc::System;
548 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
549 /// let zero = unsafe { zero.assume_init() };
551 /// assert_eq!(*zero, 0);
552 /// # Ok::<(), std::alloc::AllocError>(())
555 /// [zeroed]: mem::MaybeUninit::zeroed
556 #[unstable(feature = "allocator_api", issue = "32838")]
557 // #[unstable(feature = "new_uninit", issue = "63291")]
558 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
559 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
561 A: ~const Allocator + ~const Destruct,
563 let layout = Layout::new::<mem::MaybeUninit<T>>();
564 let ptr = alloc.allocate_zeroed(layout)?.cast();
565 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
568 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
569 /// `x` will be pinned in memory and unable to be moved.
571 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin_in(x, alloc)`
572 /// does the same as <code>[Box::into_pin]\([Box::new_in]\(x, alloc))</code>. Consider using
573 /// [`into_pin`](Box::into_pin) if you already have a `Box<T, A>`, or if you want to
574 /// construct a (pinned) `Box` in a different way than with [`Box::new_in`].
575 #[cfg(not(no_global_oom_handling))]
576 #[unstable(feature = "allocator_api", issue = "32838")]
577 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
580 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
582 A: 'static + ~const Allocator + ~const Destruct,
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 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
592 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
593 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
594 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
597 /// Consumes the `Box`, returning the wrapped value.
602 /// #![feature(box_into_inner)]
604 /// let c = Box::new(5);
606 /// assert_eq!(Box::into_inner(c), 5);
608 #[unstable(feature = "box_into_inner", issue = "80437")]
609 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
611 pub const fn into_inner(boxed: Self) -> T
613 Self: ~const Destruct,
620 /// Constructs a new boxed slice with uninitialized contents.
625 /// #![feature(new_uninit)]
627 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
629 /// let values = unsafe {
630 /// // Deferred initialization:
631 /// values[0].as_mut_ptr().write(1);
632 /// values[1].as_mut_ptr().write(2);
633 /// values[2].as_mut_ptr().write(3);
635 /// values.assume_init()
638 /// assert_eq!(*values, [1, 2, 3])
640 #[cfg(not(no_global_oom_handling))]
641 #[unstable(feature = "new_uninit", issue = "63291")]
643 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
644 unsafe { RawVec::with_capacity(len).into_box(len) }
647 /// Constructs a new boxed slice with uninitialized contents, with the memory
648 /// being filled with `0` bytes.
650 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
656 /// #![feature(new_uninit)]
658 /// let values = Box::<[u32]>::new_zeroed_slice(3);
659 /// let values = unsafe { values.assume_init() };
661 /// assert_eq!(*values, [0, 0, 0])
664 /// [zeroed]: mem::MaybeUninit::zeroed
665 #[cfg(not(no_global_oom_handling))]
666 #[unstable(feature = "new_uninit", issue = "63291")]
668 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
669 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
672 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
673 /// the allocation fails
678 /// #![feature(allocator_api, new_uninit)]
680 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
681 /// let values = unsafe {
682 /// // Deferred initialization:
683 /// values[0].as_mut_ptr().write(1);
684 /// values[1].as_mut_ptr().write(2);
685 /// values[2].as_mut_ptr().write(3);
686 /// values.assume_init()
689 /// assert_eq!(*values, [1, 2, 3]);
690 /// # Ok::<(), std::alloc::AllocError>(())
692 #[unstable(feature = "allocator_api", issue = "32838")]
694 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
696 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
698 Err(_) => return Err(AllocError),
700 let ptr = Global.allocate(layout)?;
701 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
705 /// Constructs a new boxed slice with uninitialized contents, with the memory
706 /// being filled with `0` bytes. Returns an error if the allocation fails
708 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
714 /// #![feature(allocator_api, new_uninit)]
716 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
717 /// let values = unsafe { values.assume_init() };
719 /// assert_eq!(*values, [0, 0, 0]);
720 /// # Ok::<(), std::alloc::AllocError>(())
723 /// [zeroed]: mem::MaybeUninit::zeroed
724 #[unstable(feature = "allocator_api", issue = "32838")]
726 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
728 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
730 Err(_) => return Err(AllocError),
732 let ptr = Global.allocate_zeroed(layout)?;
733 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
738 impl<T, A: Allocator> Box<[T], A> {
739 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
744 /// #![feature(allocator_api, new_uninit)]
746 /// use std::alloc::System;
748 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
750 /// let values = unsafe {
751 /// // Deferred initialization:
752 /// values[0].as_mut_ptr().write(1);
753 /// values[1].as_mut_ptr().write(2);
754 /// values[2].as_mut_ptr().write(3);
756 /// values.assume_init()
759 /// assert_eq!(*values, [1, 2, 3])
761 #[cfg(not(no_global_oom_handling))]
762 #[unstable(feature = "allocator_api", issue = "32838")]
763 // #[unstable(feature = "new_uninit", issue = "63291")]
765 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
766 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
769 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
770 /// with the memory being filled with `0` bytes.
772 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
778 /// #![feature(allocator_api, new_uninit)]
780 /// use std::alloc::System;
782 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
783 /// let values = unsafe { values.assume_init() };
785 /// assert_eq!(*values, [0, 0, 0])
788 /// [zeroed]: mem::MaybeUninit::zeroed
789 #[cfg(not(no_global_oom_handling))]
790 #[unstable(feature = "allocator_api", issue = "32838")]
791 // #[unstable(feature = "new_uninit", issue = "63291")]
793 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
794 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
798 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
799 /// Converts to `Box<T, A>`.
803 /// As with [`MaybeUninit::assume_init`],
804 /// it is up to the caller to guarantee that the value
805 /// really is in an initialized state.
806 /// Calling this when the content is not yet fully initialized
807 /// causes immediate undefined behavior.
809 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
814 /// #![feature(new_uninit)]
816 /// let mut five = Box::<u32>::new_uninit();
818 /// let five: Box<u32> = unsafe {
819 /// // Deferred initialization:
820 /// five.as_mut_ptr().write(5);
822 /// five.assume_init()
825 /// assert_eq!(*five, 5)
827 #[unstable(feature = "new_uninit", issue = "63291")]
828 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
830 pub const unsafe fn assume_init(self) -> Box<T, A> {
831 let (raw, alloc) = Box::into_raw_with_allocator(self);
832 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
835 /// Writes the value and converts to `Box<T, A>`.
837 /// This method converts the box similarly to [`Box::assume_init`] but
838 /// writes `value` into it before conversion thus guaranteeing safety.
839 /// In some scenarios use of this method may improve performance because
840 /// the compiler may be able to optimize copying from stack.
845 /// #![feature(new_uninit)]
847 /// let big_box = Box::<[usize; 1024]>::new_uninit();
849 /// let mut array = [0; 1024];
850 /// for (i, place) in array.iter_mut().enumerate() {
854 /// // The optimizer may be able to elide this copy, so previous code writes
855 /// // to heap directly.
856 /// let big_box = Box::write(big_box, array);
858 /// for (i, x) in big_box.iter().enumerate() {
859 /// assert_eq!(*x, i);
862 #[unstable(feature = "new_uninit", issue = "63291")]
863 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
865 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
867 (*boxed).write(value);
873 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
874 /// Converts to `Box<[T], A>`.
878 /// As with [`MaybeUninit::assume_init`],
879 /// it is up to the caller to guarantee that the values
880 /// really are in an initialized state.
881 /// Calling this when the content is not yet fully initialized
882 /// causes immediate undefined behavior.
884 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
889 /// #![feature(new_uninit)]
891 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
893 /// let values = unsafe {
894 /// // Deferred initialization:
895 /// values[0].as_mut_ptr().write(1);
896 /// values[1].as_mut_ptr().write(2);
897 /// values[2].as_mut_ptr().write(3);
899 /// values.assume_init()
902 /// assert_eq!(*values, [1, 2, 3])
904 #[unstable(feature = "new_uninit", issue = "63291")]
906 pub unsafe fn assume_init(self) -> Box<[T], A> {
907 let (raw, alloc) = Box::into_raw_with_allocator(self);
908 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
912 impl<T: ?Sized> Box<T> {
913 /// Constructs a box from a raw pointer.
915 /// After calling this function, the raw pointer is owned by the
916 /// resulting `Box`. Specifically, the `Box` destructor will call
917 /// the destructor of `T` and free the allocated memory. For this
918 /// to be safe, the memory must have been allocated in accordance
919 /// with the [memory layout] used by `Box` .
923 /// This function is unsafe because improper use may lead to
924 /// memory problems. For example, a double-free may occur if the
925 /// function is called twice on the same raw pointer.
927 /// The safety conditions are described in the [memory layout] section.
931 /// Recreate a `Box` which was previously converted to a raw pointer
932 /// using [`Box::into_raw`]:
934 /// let x = Box::new(5);
935 /// let ptr = Box::into_raw(x);
936 /// let x = unsafe { Box::from_raw(ptr) };
938 /// Manually create a `Box` from scratch by using the global allocator:
940 /// use std::alloc::{alloc, Layout};
943 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
944 /// // In general .write is required to avoid attempting to destruct
945 /// // the (uninitialized) previous contents of `ptr`, though for this
946 /// // simple example `*ptr = 5` would have worked as well.
948 /// let x = Box::from_raw(ptr);
952 /// [memory layout]: self#memory-layout
953 /// [`Layout`]: crate::Layout
954 #[stable(feature = "box_raw", since = "1.4.0")]
956 #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
957 pub unsafe fn from_raw(raw: *mut T) -> Self {
958 unsafe { Self::from_raw_in(raw, Global) }
962 impl<T: ?Sized, A: Allocator> Box<T, A> {
963 /// Constructs a box from a raw pointer in the given allocator.
965 /// After calling this function, the raw pointer is owned by the
966 /// resulting `Box`. Specifically, the `Box` destructor will call
967 /// the destructor of `T` and free the allocated memory. For this
968 /// to be safe, the memory must have been allocated in accordance
969 /// with the [memory layout] used by `Box` .
973 /// This function is unsafe because improper use may lead to
974 /// memory problems. For example, a double-free may occur if the
975 /// function is called twice on the same raw pointer.
980 /// Recreate a `Box` which was previously converted to a raw pointer
981 /// using [`Box::into_raw_with_allocator`]:
983 /// #![feature(allocator_api)]
985 /// use std::alloc::System;
987 /// let x = Box::new_in(5, System);
988 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
989 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
991 /// Manually create a `Box` from scratch by using the system allocator:
993 /// #![feature(allocator_api, slice_ptr_get)]
995 /// use std::alloc::{Allocator, Layout, System};
998 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
999 /// // In general .write is required to avoid attempting to destruct
1000 /// // the (uninitialized) previous contents of `ptr`, though for this
1001 /// // simple example `*ptr = 5` would have worked as well.
1003 /// let x = Box::from_raw_in(ptr, System);
1005 /// # Ok::<(), std::alloc::AllocError>(())
1008 /// [memory layout]: self#memory-layout
1009 /// [`Layout`]: crate::Layout
1010 #[unstable(feature = "allocator_api", issue = "32838")]
1011 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1013 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1014 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1017 /// Consumes the `Box`, returning a wrapped raw pointer.
1019 /// The pointer will be properly aligned and non-null.
1021 /// After calling this function, the caller is responsible for the
1022 /// memory previously managed by the `Box`. In particular, the
1023 /// caller should properly destroy `T` and release the memory, taking
1024 /// into account the [memory layout] used by `Box`. The easiest way to
1025 /// do this is to convert the raw pointer back into a `Box` with the
1026 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1029 /// Note: this is an associated function, which means that you have
1030 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1031 /// is so that there is no conflict with a method on the inner type.
1034 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1035 /// for automatic cleanup:
1037 /// let x = Box::new(String::from("Hello"));
1038 /// let ptr = Box::into_raw(x);
1039 /// let x = unsafe { Box::from_raw(ptr) };
1041 /// Manual cleanup by explicitly running the destructor and deallocating
1044 /// use std::alloc::{dealloc, Layout};
1047 /// let x = Box::new(String::from("Hello"));
1048 /// let p = Box::into_raw(x);
1050 /// ptr::drop_in_place(p);
1051 /// dealloc(p as *mut u8, Layout::new::<String>());
1055 /// [memory layout]: self#memory-layout
1056 #[stable(feature = "box_raw", since = "1.4.0")]
1058 pub fn into_raw(b: Self) -> *mut T {
1059 Self::into_raw_with_allocator(b).0
1062 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1064 /// The pointer will be properly aligned and non-null.
1066 /// After calling this function, the caller is responsible for the
1067 /// memory previously managed by the `Box`. In particular, the
1068 /// caller should properly destroy `T` and release the memory, taking
1069 /// into account the [memory layout] used by `Box`. The easiest way to
1070 /// do this is to convert the raw pointer back into a `Box` with the
1071 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1074 /// Note: this is an associated function, which means that you have
1075 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1076 /// is so that there is no conflict with a method on the inner type.
1079 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1080 /// for automatic cleanup:
1082 /// #![feature(allocator_api)]
1084 /// use std::alloc::System;
1086 /// let x = Box::new_in(String::from("Hello"), System);
1087 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1088 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1090 /// Manual cleanup by explicitly running the destructor and deallocating
1093 /// #![feature(allocator_api)]
1095 /// use std::alloc::{Allocator, Layout, System};
1096 /// use std::ptr::{self, NonNull};
1098 /// let x = Box::new_in(String::from("Hello"), System);
1099 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1101 /// ptr::drop_in_place(ptr);
1102 /// let non_null = NonNull::new_unchecked(ptr);
1103 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1107 /// [memory layout]: self#memory-layout
1108 #[unstable(feature = "allocator_api", issue = "32838")]
1109 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1111 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1112 let (leaked, alloc) = Box::into_unique(b);
1113 (leaked.as_ptr(), alloc)
1117 feature = "ptr_internals",
1119 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1121 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1124 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1125 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1126 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1127 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1128 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1129 // behaves correctly.
1130 let alloc = unsafe { ptr::read(&b.1) };
1131 (Unique::from(Box::leak(b)), alloc)
1134 /// Returns a reference to the underlying allocator.
1136 /// Note: this is an associated function, which means that you have
1137 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1138 /// is so that there is no conflict with a method on the inner type.
1139 #[unstable(feature = "allocator_api", issue = "32838")]
1140 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1142 pub const fn allocator(b: &Self) -> &A {
1146 /// Consumes and leaks the `Box`, returning a mutable reference,
1147 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1148 /// `'a`. If the type has only static references, or none at all, then this
1149 /// may be chosen to be `'static`.
1151 /// This function is mainly useful for data that lives for the remainder of
1152 /// the program's life. Dropping the returned reference will cause a memory
1153 /// leak. If this is not acceptable, the reference should first be wrapped
1154 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1155 /// then be dropped which will properly destroy `T` and release the
1156 /// allocated memory.
1158 /// Note: this is an associated function, which means that you have
1159 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1160 /// is so that there is no conflict with a method on the inner type.
1167 /// let x = Box::new(41);
1168 /// let static_ref: &'static mut usize = Box::leak(x);
1169 /// *static_ref += 1;
1170 /// assert_eq!(*static_ref, 42);
1176 /// let x = vec![1, 2, 3].into_boxed_slice();
1177 /// let static_ref = Box::leak(x);
1178 /// static_ref[0] = 4;
1179 /// assert_eq!(*static_ref, [4, 2, 3]);
1181 #[stable(feature = "box_leak", since = "1.26.0")]
1182 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1184 pub const fn leak<'a>(b: Self) -> &'a mut T
1188 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1191 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1192 /// `*boxed` will be pinned in memory and unable to be moved.
1194 /// This conversion does not allocate on the heap and happens in place.
1196 /// This is also available via [`From`].
1198 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1199 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1200 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1201 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1205 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1206 /// as it'll introduce an ambiguity when calling `Pin::from`.
1207 /// A demonstration of such a poor impl is shown below.
1210 /// # use std::pin::Pin;
1211 /// struct Foo; // A type defined in this crate.
1212 /// impl From<Box<()>> for Pin<Foo> {
1213 /// fn from(_: Box<()>) -> Pin<Foo> {
1218 /// let foo = Box::new(());
1219 /// let bar = Pin::from(foo);
1221 #[stable(feature = "box_into_pin", since = "1.63.0")]
1222 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1223 pub const fn into_pin(boxed: Self) -> Pin<Self>
1227 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1228 // when `T: !Unpin`, so it's safe to pin it directly without any
1229 // additional requirements.
1230 unsafe { Pin::new_unchecked(boxed) }
1234 #[stable(feature = "rust1", since = "1.0.0")]
1235 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1236 fn drop(&mut self) {
1237 // FIXME: Do nothing, drop is currently performed by compiler.
1241 #[cfg(not(no_global_oom_handling))]
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl<T: Default> Default for Box<T> {
1244 /// Creates a `Box<T>`, with the `Default` value for T.
1245 fn default() -> Self {
1247 Box::new(T::default())
1251 #[cfg(not(no_global_oom_handling))]
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1254 impl<T> const Default for Box<[T]> {
1255 fn default() -> Self {
1256 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1261 #[cfg(not(no_global_oom_handling))]
1262 #[stable(feature = "default_box_extra", since = "1.17.0")]
1263 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1264 impl const Default for Box<str> {
1265 fn default() -> Self {
1266 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1267 let ptr: Unique<str> = unsafe {
1268 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1269 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1275 #[cfg(not(no_global_oom_handling))]
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1278 /// Returns a new box with a `clone()` of this box's contents.
1283 /// let x = Box::new(5);
1284 /// let y = x.clone();
1286 /// // The value is the same
1287 /// assert_eq!(x, y);
1289 /// // But they are unique objects
1290 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1293 fn clone(&self) -> Self {
1294 // Pre-allocate memory to allow writing the cloned value directly.
1295 let mut boxed = Self::new_uninit_in(self.1.clone());
1297 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1302 /// Copies `source`'s contents into `self` without creating a new allocation.
1307 /// let x = Box::new(5);
1308 /// let mut y = Box::new(10);
1309 /// let yp: *const i32 = &*y;
1311 /// y.clone_from(&x);
1313 /// // The value is the same
1314 /// assert_eq!(x, y);
1316 /// // And no allocation occurred
1317 /// assert_eq!(yp, &*y);
1320 fn clone_from(&mut self, source: &Self) {
1321 (**self).clone_from(&(**source));
1325 #[cfg(not(no_global_oom_handling))]
1326 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1327 impl Clone for Box<str> {
1328 fn clone(&self) -> Self {
1329 // this makes a copy of the data
1330 let buf: Box<[u8]> = self.as_bytes().into();
1331 unsafe { from_boxed_utf8_unchecked(buf) }
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1338 fn eq(&self, other: &Self) -> bool {
1339 PartialEq::eq(&**self, &**other)
1342 fn ne(&self, other: &Self) -> bool {
1343 PartialEq::ne(&**self, &**other)
1346 #[stable(feature = "rust1", since = "1.0.0")]
1347 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1349 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1350 PartialOrd::partial_cmp(&**self, &**other)
1353 fn lt(&self, other: &Self) -> bool {
1354 PartialOrd::lt(&**self, &**other)
1357 fn le(&self, other: &Self) -> bool {
1358 PartialOrd::le(&**self, &**other)
1361 fn ge(&self, other: &Self) -> bool {
1362 PartialOrd::ge(&**self, &**other)
1365 fn gt(&self, other: &Self) -> bool {
1366 PartialOrd::gt(&**self, &**other)
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1372 fn cmp(&self, other: &Self) -> Ordering {
1373 Ord::cmp(&**self, &**other)
1376 #[stable(feature = "rust1", since = "1.0.0")]
1377 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1379 #[stable(feature = "rust1", since = "1.0.0")]
1380 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1381 fn hash<H: Hasher>(&self, state: &mut H) {
1382 (**self).hash(state);
1386 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1387 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1388 fn finish(&self) -> u64 {
1391 fn write(&mut self, bytes: &[u8]) {
1392 (**self).write(bytes)
1394 fn write_u8(&mut self, i: u8) {
1395 (**self).write_u8(i)
1397 fn write_u16(&mut self, i: u16) {
1398 (**self).write_u16(i)
1400 fn write_u32(&mut self, i: u32) {
1401 (**self).write_u32(i)
1403 fn write_u64(&mut self, i: u64) {
1404 (**self).write_u64(i)
1406 fn write_u128(&mut self, i: u128) {
1407 (**self).write_u128(i)
1409 fn write_usize(&mut self, i: usize) {
1410 (**self).write_usize(i)
1412 fn write_i8(&mut self, i: i8) {
1413 (**self).write_i8(i)
1415 fn write_i16(&mut self, i: i16) {
1416 (**self).write_i16(i)
1418 fn write_i32(&mut self, i: i32) {
1419 (**self).write_i32(i)
1421 fn write_i64(&mut self, i: i64) {
1422 (**self).write_i64(i)
1424 fn write_i128(&mut self, i: i128) {
1425 (**self).write_i128(i)
1427 fn write_isize(&mut self, i: isize) {
1428 (**self).write_isize(i)
1430 fn write_length_prefix(&mut self, len: usize) {
1431 (**self).write_length_prefix(len)
1433 fn write_str(&mut self, s: &str) {
1434 (**self).write_str(s)
1438 #[cfg(not(no_global_oom_handling))]
1439 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1440 impl<T> From<T> for Box<T> {
1441 /// Converts a `T` into a `Box<T>`
1443 /// The conversion allocates on the heap and moves `t`
1444 /// from the stack into it.
1450 /// let boxed = Box::new(5);
1452 /// assert_eq!(Box::from(x), boxed);
1454 fn from(t: T) -> Self {
1459 #[stable(feature = "pin", since = "1.33.0")]
1460 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1461 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1465 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1466 /// `*boxed` will be pinned in memory and unable to be moved.
1468 /// This conversion does not allocate on the heap and happens in place.
1470 /// This is also available via [`Box::into_pin`].
1472 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
1473 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1474 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
1475 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1476 fn from(boxed: Box<T, A>) -> Self {
1477 Box::into_pin(boxed)
1481 #[cfg(not(no_global_oom_handling))]
1482 #[stable(feature = "box_from_slice", since = "1.17.0")]
1483 impl<T: Copy> From<&[T]> for Box<[T]> {
1484 /// Converts a `&[T]` into a `Box<[T]>`
1486 /// This conversion allocates on the heap
1487 /// and performs a copy of `slice` and its contents.
1491 /// // create a &[u8] which will be used to create a Box<[u8]>
1492 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1493 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1495 /// println!("{boxed_slice:?}");
1497 fn from(slice: &[T]) -> Box<[T]> {
1498 let len = slice.len();
1499 let buf = RawVec::with_capacity(len);
1501 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1502 buf.into_box(slice.len()).assume_init()
1507 #[cfg(not(no_global_oom_handling))]
1508 #[stable(feature = "box_from_cow", since = "1.45.0")]
1509 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1510 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1512 /// When `cow` is the `Cow::Borrowed` variant, this
1513 /// conversion allocates on the heap and copies the
1514 /// underlying slice. Otherwise, it will try to reuse the owned
1515 /// `Vec`'s allocation.
1517 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1519 Cow::Borrowed(slice) => Box::from(slice),
1520 Cow::Owned(slice) => Box::from(slice),
1525 #[cfg(not(no_global_oom_handling))]
1526 #[stable(feature = "box_from_slice", since = "1.17.0")]
1527 impl From<&str> for Box<str> {
1528 /// Converts a `&str` into a `Box<str>`
1530 /// This conversion allocates on the heap
1531 /// and performs a copy of `s`.
1536 /// let boxed: Box<str> = Box::from("hello");
1537 /// println!("{boxed}");
1540 fn from(s: &str) -> Box<str> {
1541 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1545 #[cfg(not(no_global_oom_handling))]
1546 #[stable(feature = "box_from_cow", since = "1.45.0")]
1547 impl From<Cow<'_, str>> for Box<str> {
1548 /// Converts a `Cow<'_, str>` into a `Box<str>`
1550 /// When `cow` is the `Cow::Borrowed` variant, this
1551 /// conversion allocates on the heap and copies the
1552 /// underlying `str`. Otherwise, it will try to reuse the owned
1553 /// `String`'s allocation.
1558 /// use std::borrow::Cow;
1560 /// let unboxed = Cow::Borrowed("hello");
1561 /// let boxed: Box<str> = Box::from(unboxed);
1562 /// println!("{boxed}");
1566 /// # use std::borrow::Cow;
1567 /// let unboxed = Cow::Owned("hello".to_string());
1568 /// let boxed: Box<str> = Box::from(unboxed);
1569 /// println!("{boxed}");
1572 fn from(cow: Cow<'_, str>) -> Box<str> {
1574 Cow::Borrowed(s) => Box::from(s),
1575 Cow::Owned(s) => Box::from(s),
1580 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1581 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1582 /// Converts a `Box<str>` into a `Box<[u8]>`
1584 /// This conversion does not allocate on the heap and happens in place.
1588 /// // create a Box<str> which will be used to create a Box<[u8]>
1589 /// let boxed: Box<str> = Box::from("hello");
1590 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1592 /// // create a &[u8] which will be used to create a Box<[u8]>
1593 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1594 /// let boxed_slice = Box::from(slice);
1596 /// assert_eq!(boxed_slice, boxed_str);
1599 fn from(s: Box<str, A>) -> Self {
1600 let (raw, alloc) = Box::into_raw_with_allocator(s);
1601 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1605 #[cfg(not(no_global_oom_handling))]
1606 #[stable(feature = "box_from_array", since = "1.45.0")]
1607 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1608 /// Converts a `[T; N]` into a `Box<[T]>`
1610 /// This conversion moves the array to newly heap-allocated memory.
1615 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1616 /// println!("{boxed:?}");
1618 fn from(array: [T; N]) -> Box<[T]> {
1624 /// Casts a boxed slice to a boxed array.
1628 /// `boxed_slice.len()` must be exactly `N`.
1629 unsafe fn boxed_slice_as_array_unchecked<T, A: Allocator, const N: usize>(
1630 boxed_slice: Box<[T], A>,
1631 ) -> Box<[T; N], A> {
1632 debug_assert_eq!(boxed_slice.len(), N);
1634 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
1635 // SAFETY: Pointer and allocator came from an existing box,
1636 // and our safety condition requires that the length is exactly `N`
1637 unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) }
1640 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1641 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1642 type Error = Box<[T]>;
1644 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1646 /// The conversion occurs in-place and does not require a
1647 /// new memory allocation.
1651 /// Returns the old `Box<[T]>` in the `Err` variant if
1652 /// `boxed_slice.len()` does not equal `N`.
1653 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1654 if boxed_slice.len() == N {
1655 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1662 #[cfg(not(no_global_oom_handling))]
1663 #[stable(feature = "boxed_array_try_from_vec", since = "1.66.0")]
1664 impl<T, const N: usize> TryFrom<Vec<T>> for Box<[T; N]> {
1665 type Error = Vec<T>;
1667 /// Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.
1669 /// Like [`Vec::into_boxed_slice`], this is in-place if `vec.capacity() == N`,
1670 /// but will require a reallocation otherwise.
1674 /// Returns the original `Vec<T>` in the `Err` variant if
1675 /// `boxed_slice.len()` does not equal `N`.
1679 /// This can be used with [`vec!`] to create an array on the heap:
1682 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
1683 /// assert_eq!(state.len(), 100);
1685 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1687 let boxed_slice = vec.into_boxed_slice();
1688 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1695 impl<A: Allocator> Box<dyn Any, A> {
1696 /// Attempt to downcast the box to a concrete type.
1701 /// use std::any::Any;
1703 /// fn print_if_string(value: Box<dyn Any>) {
1704 /// if let Ok(string) = value.downcast::<String>() {
1705 /// println!("String ({}): {}", string.len(), string);
1709 /// let my_string = "Hello World".to_string();
1710 /// print_if_string(Box::new(my_string));
1711 /// print_if_string(Box::new(0i8));
1714 #[stable(feature = "rust1", since = "1.0.0")]
1715 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1716 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1719 /// Downcasts the box to a concrete type.
1721 /// For a safe alternative see [`downcast`].
1726 /// #![feature(downcast_unchecked)]
1728 /// use std::any::Any;
1730 /// let x: Box<dyn Any> = Box::new(1_usize);
1733 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1739 /// The contained value must be of type `T`. Calling this method
1740 /// with the incorrect type is *undefined behavior*.
1742 /// [`downcast`]: Self::downcast
1744 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1745 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1746 debug_assert!(self.is::<T>());
1748 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1749 Box::from_raw_in(raw as *mut T, alloc)
1754 impl<A: Allocator> Box<dyn Any + Send, A> {
1755 /// Attempt to downcast the box to a concrete type.
1760 /// use std::any::Any;
1762 /// fn print_if_string(value: Box<dyn Any + Send>) {
1763 /// if let Ok(string) = value.downcast::<String>() {
1764 /// println!("String ({}): {}", string.len(), string);
1768 /// let my_string = "Hello World".to_string();
1769 /// print_if_string(Box::new(my_string));
1770 /// print_if_string(Box::new(0i8));
1773 #[stable(feature = "rust1", since = "1.0.0")]
1774 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1775 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1778 /// Downcasts the box to a concrete type.
1780 /// For a safe alternative see [`downcast`].
1785 /// #![feature(downcast_unchecked)]
1787 /// use std::any::Any;
1789 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1792 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1798 /// The contained value must be of type `T`. Calling this method
1799 /// with the incorrect type is *undefined behavior*.
1801 /// [`downcast`]: Self::downcast
1803 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1804 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1805 debug_assert!(self.is::<T>());
1807 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1808 Box::from_raw_in(raw as *mut T, alloc)
1813 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1814 /// Attempt to downcast the box to a concrete type.
1819 /// use std::any::Any;
1821 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1822 /// if let Ok(string) = value.downcast::<String>() {
1823 /// println!("String ({}): {}", string.len(), string);
1827 /// let my_string = "Hello World".to_string();
1828 /// print_if_string(Box::new(my_string));
1829 /// print_if_string(Box::new(0i8));
1832 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1833 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1834 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1837 /// Downcasts the box to a concrete type.
1839 /// For a safe alternative see [`downcast`].
1844 /// #![feature(downcast_unchecked)]
1846 /// use std::any::Any;
1848 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1851 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1857 /// The contained value must be of type `T`. Calling this method
1858 /// with the incorrect type is *undefined behavior*.
1860 /// [`downcast`]: Self::downcast
1862 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1863 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1864 debug_assert!(self.is::<T>());
1866 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1867 Box::into_raw_with_allocator(self);
1868 Box::from_raw_in(raw as *mut T, alloc)
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1875 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1876 fmt::Display::fmt(&**self, f)
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1883 fmt::Debug::fmt(&**self, f)
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1889 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1890 // It's not possible to extract the inner Uniq directly from the Box,
1891 // instead we cast it to a *const which aliases the Unique
1892 let ptr: *const T = &**self;
1893 fmt::Pointer::fmt(&ptr, f)
1897 #[stable(feature = "rust1", since = "1.0.0")]
1898 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1899 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1902 fn deref(&self) -> &T {
1907 #[stable(feature = "rust1", since = "1.0.0")]
1908 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1909 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1910 fn deref_mut(&mut self) -> &mut T {
1915 #[unstable(feature = "receiver_trait", issue = "none")]
1916 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1920 type Item = I::Item;
1921 fn next(&mut self) -> Option<I::Item> {
1924 fn size_hint(&self) -> (usize, Option<usize>) {
1925 (**self).size_hint()
1927 fn nth(&mut self, n: usize) -> Option<I::Item> {
1930 fn last(self) -> Option<I::Item> {
1937 fn last(self) -> Option<Self::Item>;
1940 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1941 type Item = I::Item;
1942 default fn last(self) -> Option<I::Item> {
1944 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1948 self.fold(None, some)
1952 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1953 /// instead of the default.
1954 #[stable(feature = "rust1", since = "1.0.0")]
1955 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1956 fn last(self) -> Option<I::Item> {
1961 #[stable(feature = "rust1", since = "1.0.0")]
1962 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1963 fn next_back(&mut self) -> Option<I::Item> {
1964 (**self).next_back()
1966 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1967 (**self).nth_back(n)
1970 #[stable(feature = "rust1", since = "1.0.0")]
1971 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1972 fn len(&self) -> usize {
1975 fn is_empty(&self) -> bool {
1980 #[stable(feature = "fused", since = "1.26.0")]
1981 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1983 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1984 impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1985 type Output = <F as FnOnce<Args>>::Output;
1987 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1988 <F as FnOnce<Args>>::call_once(*self, args)
1992 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1993 impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1994 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1995 <F as FnMut<Args>>::call_mut(self, args)
1999 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2000 impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2001 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2002 <F as Fn<Args>>::call(self, args)
2006 #[unstable(feature = "coerce_unsized", issue = "18598")]
2007 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2009 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2010 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2012 #[cfg(not(no_global_oom_handling))]
2013 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
2014 impl<I> FromIterator<I> for Box<[I]> {
2015 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
2016 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
2020 #[cfg(not(no_global_oom_handling))]
2021 #[stable(feature = "box_slice_clone", since = "1.3.0")]
2022 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2023 fn clone(&self) -> Self {
2024 let alloc = Box::allocator(self).clone();
2025 self.to_vec_in(alloc).into_boxed_slice()
2028 fn clone_from(&mut self, other: &Self) {
2029 if self.len() == other.len() {
2030 self.clone_from_slice(&other);
2032 *self = other.clone();
2037 #[stable(feature = "box_borrow", since = "1.1.0")]
2038 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
2039 fn borrow(&self) -> &T {
2044 #[stable(feature = "box_borrow", since = "1.1.0")]
2045 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
2046 fn borrow_mut(&mut self) -> &mut T {
2051 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2052 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2053 fn as_ref(&self) -> &T {
2058 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2059 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2060 fn as_mut(&mut self) -> &mut T {
2067 * We could have chosen not to add this impl, and instead have written a
2068 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2069 * because Box<T> implements Unpin even when T does not, as a result of
2072 * We chose this API instead of the alternative for a few reasons:
2073 * - Logically, it is helpful to understand pinning in regard to the
2074 * memory region being pointed to. For this reason none of the
2075 * standard library pointer types support projecting through a pin
2076 * (Box<T> is the only pointer type in std for which this would be
2078 * - It is in practice very useful to have Box<T> be unconditionally
2079 * Unpin because of trait objects, for which the structural auto
2080 * trait functionality does not apply (e.g., Box<dyn Foo> would
2081 * otherwise not be Unpin).
2083 * Another type with the same semantics as Box but only a conditional
2084 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2085 * could have a method to project a Pin<T> from it.
2087 #[stable(feature = "pin", since = "1.33.0")]
2088 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
2090 #[unstable(feature = "generator_trait", issue = "43122")]
2091 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2095 type Yield = G::Yield;
2096 type Return = G::Return;
2098 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2099 G::resume(Pin::new(&mut *self), arg)
2103 #[unstable(feature = "generator_trait", issue = "43122")]
2104 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2108 type Yield = G::Yield;
2109 type Return = G::Return;
2111 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2112 G::resume((*self).as_mut(), arg)
2116 #[stable(feature = "futures_api", since = "1.36.0")]
2117 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2121 type Output = F::Output;
2123 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2124 F::poll(Pin::new(&mut *self), cx)
2128 #[unstable(feature = "async_iterator", issue = "79024")]
2129 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2130 type Item = S::Item;
2132 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2133 Pin::new(&mut **self).poll_next(cx)
2136 fn size_hint(&self) -> (usize, Option<usize>) {
2137 (**self).size_hint()
2143 #[stable(feature = "error_downcast", since = "1.3.0")]
2144 #[rustc_allow_incoherent_impl]
2145 /// Attempts to downcast the box to a concrete type.
2146 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
2149 let raw: *mut dyn Error = Box::into_raw(self);
2150 Ok(Box::from_raw(raw as *mut T))
2158 impl dyn Error + Send {
2160 #[stable(feature = "error_downcast", since = "1.3.0")]
2161 #[rustc_allow_incoherent_impl]
2162 /// Attempts to downcast the box to a concrete type.
2163 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
2164 let err: Box<dyn Error> = self;
2165 <dyn Error>::downcast(err).map_err(|s| unsafe {
2166 // Reapply the `Send` marker.
2167 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
2172 impl dyn Error + Send + Sync {
2174 #[stable(feature = "error_downcast", since = "1.3.0")]
2175 #[rustc_allow_incoherent_impl]
2176 /// Attempts to downcast the box to a concrete type.
2177 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
2178 let err: Box<dyn Error> = self;
2179 <dyn Error>::downcast(err).map_err(|s| unsafe {
2180 // Reapply the `Send + Sync` marker.
2181 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
2186 #[cfg(not(no_global_oom_handling))]
2187 #[stable(feature = "rust1", since = "1.0.0")]
2188 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
2189 /// Converts a type of [`Error`] into a box of dyn [`Error`].
2194 /// use std::error::Error;
2198 /// #[derive(Debug)]
2201 /// impl fmt::Display for AnError {
2202 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2203 /// write!(f, "An error")
2207 /// impl Error for AnError {}
2209 /// let an_error = AnError;
2210 /// assert!(0 == mem::size_of_val(&an_error));
2211 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
2212 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2214 fn from(err: E) -> Box<dyn Error + 'a> {
2219 #[cfg(not(no_global_oom_handling))]
2220 #[stable(feature = "rust1", since = "1.0.0")]
2221 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
2222 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
2223 /// dyn [`Error`] + [`Send`] + [`Sync`].
2228 /// use std::error::Error;
2232 /// #[derive(Debug)]
2235 /// impl fmt::Display for AnError {
2236 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2237 /// write!(f, "An error")
2241 /// impl Error for AnError {}
2243 /// unsafe impl Send for AnError {}
2245 /// unsafe impl Sync for AnError {}
2247 /// let an_error = AnError;
2248 /// assert!(0 == mem::size_of_val(&an_error));
2249 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
2251 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2253 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
2258 #[cfg(not(no_global_oom_handling))]
2259 #[stable(feature = "rust1", since = "1.0.0")]
2260 impl From<String> for Box<dyn Error + Send + Sync> {
2261 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2266 /// use std::error::Error;
2269 /// let a_string_error = "a string error".to_string();
2270 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
2272 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2275 fn from(err: String) -> Box<dyn Error + Send + Sync> {
2276 struct StringError(String);
2278 impl Error for StringError {
2279 #[allow(deprecated)]
2280 fn description(&self) -> &str {
2285 impl fmt::Display for StringError {
2286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2287 fmt::Display::fmt(&self.0, f)
2291 // Purposefully skip printing "StringError(..)"
2292 impl fmt::Debug for StringError {
2293 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2294 fmt::Debug::fmt(&self.0, f)
2298 Box::new(StringError(err))
2302 #[cfg(not(no_global_oom_handling))]
2303 #[stable(feature = "string_box_error", since = "1.6.0")]
2304 impl From<String> for Box<dyn Error> {
2305 /// Converts a [`String`] into a box of dyn [`Error`].
2310 /// use std::error::Error;
2313 /// let a_string_error = "a string error".to_string();
2314 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
2315 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2317 fn from(str_err: String) -> Box<dyn Error> {
2318 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
2319 let err2: Box<dyn Error> = err1;
2324 #[cfg(not(no_global_oom_handling))]
2325 #[stable(feature = "rust1", since = "1.0.0")]
2326 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
2327 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2329 /// [`str`]: prim@str
2334 /// use std::error::Error;
2337 /// let a_str_error = "a str error";
2338 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
2340 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2343 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
2344 From::from(String::from(err))
2348 #[cfg(not(no_global_oom_handling))]
2349 #[stable(feature = "string_box_error", since = "1.6.0")]
2350 impl From<&str> for Box<dyn Error> {
2351 /// Converts a [`str`] into a box of dyn [`Error`].
2353 /// [`str`]: prim@str
2358 /// use std::error::Error;
2361 /// let a_str_error = "a str error";
2362 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
2363 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2365 fn from(err: &str) -> Box<dyn Error> {
2366 From::from(String::from(err))
2370 #[cfg(not(no_global_oom_handling))]
2371 #[stable(feature = "cow_box_error", since = "1.22.0")]
2372 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
2373 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2378 /// use std::error::Error;
2380 /// use std::borrow::Cow;
2382 /// let a_cow_str_error = Cow::from("a str error");
2383 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
2385 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2387 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
2388 From::from(String::from(err))
2392 #[cfg(not(no_global_oom_handling))]
2393 #[stable(feature = "cow_box_error", since = "1.22.0")]
2394 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
2395 /// Converts a [`Cow`] into a box of dyn [`Error`].
2400 /// use std::error::Error;
2402 /// use std::borrow::Cow;
2404 /// let a_cow_str_error = Cow::from("a str error");
2405 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
2406 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2408 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
2409 From::from(String::from(err))
2413 #[stable(feature = "box_error", since = "1.8.0")]
2414 impl<T: core::error::Error> core::error::Error for Box<T> {
2415 #[allow(deprecated, deprecated_in_future)]
2416 fn description(&self) -> &str {
2417 core::error::Error::description(&**self)
2420 #[allow(deprecated)]
2421 fn cause(&self) -> Option<&dyn core::error::Error> {
2422 core::error::Error::cause(&**self)
2425 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
2426 core::error::Error::source(&**self)