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::{Destruct, Unpin, Unsize};
164 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
167 use core::ptr::{self, Unique};
168 use core::task::{Context, Poll};
170 #[cfg(not(no_global_oom_handling))]
171 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
172 use crate::alloc::{AllocError, Allocator, Global, Layout};
173 #[cfg(not(no_global_oom_handling))]
174 use crate::borrow::Cow;
175 use crate::raw_vec::RawVec;
176 #[cfg(not(no_global_oom_handling))]
177 use crate::str::from_boxed_utf8_unchecked;
178 #[cfg(not(no_global_oom_handling))]
179 use crate::string::String;
180 #[cfg(not(no_global_oom_handling))]
183 #[unstable(feature = "thin_box", issue = "92791")]
184 pub use thin::ThinBox;
188 /// A pointer type for heap allocation.
190 /// See the [module-level documentation](../../std/boxed/index.html) for more.
191 #[lang = "owned_box"]
193 #[stable(feature = "rust1", since = "1.0.0")]
194 // The declaration of the `Box` struct must be kept in sync with the
195 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
196 // on `box_free` for more details.
199 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
203 /// Allocates memory on the heap and then places `x` into it.
205 /// This doesn't actually allocate if `T` is zero-sized.
210 /// let five = Box::new(5);
212 #[cfg(all(not(no_global_oom_handling)))]
214 #[stable(feature = "rust1", since = "1.0.0")]
216 pub fn new(x: T) -> Self {
221 /// Constructs a new box with uninitialized contents.
226 /// #![feature(new_uninit)]
228 /// let mut five = Box::<u32>::new_uninit();
230 /// let five = unsafe {
231 /// // Deferred initialization:
232 /// five.as_mut_ptr().write(5);
234 /// five.assume_init()
237 /// assert_eq!(*five, 5)
239 #[cfg(not(no_global_oom_handling))]
240 #[unstable(feature = "new_uninit", issue = "63291")]
243 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
244 Self::new_uninit_in(Global)
247 /// Constructs a new `Box` with uninitialized contents, with the memory
248 /// being filled with `0` bytes.
250 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
256 /// #![feature(new_uninit)]
258 /// let zero = Box::<u32>::new_zeroed();
259 /// let zero = unsafe { zero.assume_init() };
261 /// assert_eq!(*zero, 0)
264 /// [zeroed]: mem::MaybeUninit::zeroed
265 #[cfg(not(no_global_oom_handling))]
267 #[unstable(feature = "new_uninit", issue = "63291")]
269 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
270 Self::new_zeroed_in(Global)
273 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
274 /// `x` will be pinned in memory and unable to be moved.
276 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
277 /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
278 /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
279 /// construct a (pinned) `Box` in a different way than with [`Box::new`].
280 #[cfg(not(no_global_oom_handling))]
281 #[stable(feature = "pin", since = "1.33.0")]
284 pub fn pin(x: T) -> Pin<Box<T>> {
290 /// Allocates memory on the heap then places `x` into it,
291 /// returning an error if the allocation fails
293 /// This doesn't actually allocate if `T` is zero-sized.
298 /// #![feature(allocator_api)]
300 /// let five = Box::try_new(5)?;
301 /// # Ok::<(), std::alloc::AllocError>(())
303 #[unstable(feature = "allocator_api", issue = "32838")]
305 pub fn try_new(x: T) -> Result<Self, AllocError> {
306 Self::try_new_in(x, Global)
309 /// Constructs a new box with uninitialized contents on the heap,
310 /// returning an error if the allocation fails
315 /// #![feature(allocator_api, new_uninit)]
317 /// let mut five = Box::<u32>::try_new_uninit()?;
319 /// let five = unsafe {
320 /// // Deferred initialization:
321 /// five.as_mut_ptr().write(5);
323 /// five.assume_init()
326 /// assert_eq!(*five, 5);
327 /// # Ok::<(), std::alloc::AllocError>(())
329 #[unstable(feature = "allocator_api", issue = "32838")]
330 // #[unstable(feature = "new_uninit", issue = "63291")]
332 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
333 Box::try_new_uninit_in(Global)
336 /// Constructs a new `Box` with uninitialized contents, with the memory
337 /// being filled with `0` bytes on the heap
339 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
345 /// #![feature(allocator_api, new_uninit)]
347 /// let zero = Box::<u32>::try_new_zeroed()?;
348 /// let zero = unsafe { zero.assume_init() };
350 /// assert_eq!(*zero, 0);
351 /// # Ok::<(), std::alloc::AllocError>(())
354 /// [zeroed]: mem::MaybeUninit::zeroed
355 #[unstable(feature = "allocator_api", issue = "32838")]
356 // #[unstable(feature = "new_uninit", issue = "63291")]
358 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
359 Box::try_new_zeroed_in(Global)
363 impl<T, A: Allocator> Box<T, A> {
364 /// Allocates memory in the given allocator then places `x` into it.
366 /// This doesn't actually allocate if `T` is zero-sized.
371 /// #![feature(allocator_api)]
373 /// use std::alloc::System;
375 /// let five = Box::new_in(5, System);
377 #[cfg(not(no_global_oom_handling))]
378 #[unstable(feature = "allocator_api", issue = "32838")]
379 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
382 pub const fn new_in(x: T, alloc: A) -> Self
384 A: ~const Allocator + ~const Destruct,
386 let mut boxed = Self::new_uninit_in(alloc);
388 boxed.as_mut_ptr().write(x);
393 /// Allocates memory in the given allocator then places `x` into it,
394 /// returning an error if the allocation fails
396 /// This doesn't actually allocate if `T` is zero-sized.
401 /// #![feature(allocator_api)]
403 /// use std::alloc::System;
405 /// let five = Box::try_new_in(5, System)?;
406 /// # Ok::<(), std::alloc::AllocError>(())
408 #[unstable(feature = "allocator_api", issue = "32838")]
409 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
411 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
414 A: ~const Allocator + ~const Destruct,
416 let mut boxed = Self::try_new_uninit_in(alloc)?;
418 boxed.as_mut_ptr().write(x);
419 Ok(boxed.assume_init())
423 /// Constructs a new box with uninitialized contents in the provided allocator.
428 /// #![feature(allocator_api, new_uninit)]
430 /// use std::alloc::System;
432 /// let mut five = Box::<u32, _>::new_uninit_in(System);
434 /// let five = unsafe {
435 /// // Deferred initialization:
436 /// five.as_mut_ptr().write(5);
438 /// five.assume_init()
441 /// assert_eq!(*five, 5)
443 #[unstable(feature = "allocator_api", issue = "32838")]
444 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
445 #[cfg(not(no_global_oom_handling))]
447 // #[unstable(feature = "new_uninit", issue = "63291")]
448 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
450 A: ~const Allocator + ~const Destruct,
452 let layout = Layout::new::<mem::MaybeUninit<T>>();
453 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
454 // That would make code size bigger.
455 match Box::try_new_uninit_in(alloc) {
457 Err(_) => handle_alloc_error(layout),
461 /// Constructs a new box with uninitialized contents in the provided allocator,
462 /// returning an error if the allocation fails
467 /// #![feature(allocator_api, new_uninit)]
469 /// use std::alloc::System;
471 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
473 /// let five = unsafe {
474 /// // Deferred initialization:
475 /// five.as_mut_ptr().write(5);
477 /// five.assume_init()
480 /// assert_eq!(*five, 5);
481 /// # Ok::<(), std::alloc::AllocError>(())
483 #[unstable(feature = "allocator_api", issue = "32838")]
484 // #[unstable(feature = "new_uninit", issue = "63291")]
485 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
486 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
488 A: ~const Allocator + ~const Destruct,
490 let layout = Layout::new::<mem::MaybeUninit<T>>();
491 let ptr = alloc.allocate(layout)?.cast();
492 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
495 /// Constructs a new `Box` with uninitialized contents, with the memory
496 /// being filled with `0` bytes in the provided allocator.
498 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
504 /// #![feature(allocator_api, new_uninit)]
506 /// use std::alloc::System;
508 /// let zero = Box::<u32, _>::new_zeroed_in(System);
509 /// let zero = unsafe { zero.assume_init() };
511 /// assert_eq!(*zero, 0)
514 /// [zeroed]: mem::MaybeUninit::zeroed
515 #[unstable(feature = "allocator_api", issue = "32838")]
516 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
517 #[cfg(not(no_global_oom_handling))]
518 // #[unstable(feature = "new_uninit", issue = "63291")]
520 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
522 A: ~const Allocator + ~const Destruct,
524 let layout = Layout::new::<mem::MaybeUninit<T>>();
525 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
526 // That would make code size bigger.
527 match Box::try_new_zeroed_in(alloc) {
529 Err(_) => handle_alloc_error(layout),
533 /// Constructs a new `Box` with uninitialized contents, with the memory
534 /// being filled with `0` bytes in the provided allocator,
535 /// returning an error if the allocation fails,
537 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
543 /// #![feature(allocator_api, new_uninit)]
545 /// use std::alloc::System;
547 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
548 /// let zero = unsafe { zero.assume_init() };
550 /// assert_eq!(*zero, 0);
551 /// # Ok::<(), std::alloc::AllocError>(())
554 /// [zeroed]: mem::MaybeUninit::zeroed
555 #[unstable(feature = "allocator_api", issue = "32838")]
556 // #[unstable(feature = "new_uninit", issue = "63291")]
557 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
558 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
560 A: ~const Allocator + ~const Destruct,
562 let layout = Layout::new::<mem::MaybeUninit<T>>();
563 let ptr = alloc.allocate_zeroed(layout)?.cast();
564 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
567 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
568 /// `x` will be pinned in memory and unable to be moved.
570 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin_in(x, alloc)`
571 /// does the same as <code>[Box::into_pin]\([Box::new_in]\(x, alloc))</code>. Consider using
572 /// [`into_pin`](Box::into_pin) if you already have a `Box<T, A>`, or if you want to
573 /// construct a (pinned) `Box` in a different way than with [`Box::new_in`].
574 #[cfg(not(no_global_oom_handling))]
575 #[unstable(feature = "allocator_api", issue = "32838")]
576 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
579 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
581 A: 'static + ~const Allocator + ~const Destruct,
583 Self::into_pin(Self::new_in(x, alloc))
586 /// Converts a `Box<T>` into a `Box<[T]>`
588 /// This conversion does not allocate on the heap and happens in place.
589 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
590 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
591 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
592 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
593 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
596 /// Consumes the `Box`, returning the wrapped value.
601 /// #![feature(box_into_inner)]
603 /// let c = Box::new(5);
605 /// assert_eq!(Box::into_inner(c), 5);
607 #[unstable(feature = "box_into_inner", issue = "80437")]
608 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
610 pub const fn into_inner(boxed: Self) -> T
612 Self: ~const Destruct,
619 /// Constructs a new boxed slice with uninitialized contents.
624 /// #![feature(new_uninit)]
626 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
628 /// let values = unsafe {
629 /// // Deferred initialization:
630 /// values[0].as_mut_ptr().write(1);
631 /// values[1].as_mut_ptr().write(2);
632 /// values[2].as_mut_ptr().write(3);
634 /// values.assume_init()
637 /// assert_eq!(*values, [1, 2, 3])
639 #[cfg(not(no_global_oom_handling))]
640 #[unstable(feature = "new_uninit", issue = "63291")]
642 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
643 unsafe { RawVec::with_capacity(len).into_box(len) }
646 /// Constructs a new boxed slice with uninitialized contents, with the memory
647 /// being filled with `0` bytes.
649 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
655 /// #![feature(new_uninit)]
657 /// let values = Box::<[u32]>::new_zeroed_slice(3);
658 /// let values = unsafe { values.assume_init() };
660 /// assert_eq!(*values, [0, 0, 0])
663 /// [zeroed]: mem::MaybeUninit::zeroed
664 #[cfg(not(no_global_oom_handling))]
665 #[unstable(feature = "new_uninit", issue = "63291")]
667 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
668 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
671 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
672 /// the allocation fails
677 /// #![feature(allocator_api, new_uninit)]
679 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
680 /// let values = unsafe {
681 /// // Deferred initialization:
682 /// values[0].as_mut_ptr().write(1);
683 /// values[1].as_mut_ptr().write(2);
684 /// values[2].as_mut_ptr().write(3);
685 /// values.assume_init()
688 /// assert_eq!(*values, [1, 2, 3]);
689 /// # Ok::<(), std::alloc::AllocError>(())
691 #[unstable(feature = "allocator_api", issue = "32838")]
693 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
695 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
697 Err(_) => return Err(AllocError),
699 let ptr = Global.allocate(layout)?;
700 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
704 /// Constructs a new boxed slice with uninitialized contents, with the memory
705 /// being filled with `0` bytes. Returns an error if the allocation fails
707 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
713 /// #![feature(allocator_api, new_uninit)]
715 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
716 /// let values = unsafe { values.assume_init() };
718 /// assert_eq!(*values, [0, 0, 0]);
719 /// # Ok::<(), std::alloc::AllocError>(())
722 /// [zeroed]: mem::MaybeUninit::zeroed
723 #[unstable(feature = "allocator_api", issue = "32838")]
725 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
727 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
729 Err(_) => return Err(AllocError),
731 let ptr = Global.allocate_zeroed(layout)?;
732 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
737 impl<T, A: Allocator> Box<[T], A> {
738 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
743 /// #![feature(allocator_api, new_uninit)]
745 /// use std::alloc::System;
747 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
749 /// let values = unsafe {
750 /// // Deferred initialization:
751 /// values[0].as_mut_ptr().write(1);
752 /// values[1].as_mut_ptr().write(2);
753 /// values[2].as_mut_ptr().write(3);
755 /// values.assume_init()
758 /// assert_eq!(*values, [1, 2, 3])
760 #[cfg(not(no_global_oom_handling))]
761 #[unstable(feature = "allocator_api", issue = "32838")]
762 // #[unstable(feature = "new_uninit", issue = "63291")]
764 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
765 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
768 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
769 /// with the memory being filled with `0` bytes.
771 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
777 /// #![feature(allocator_api, new_uninit)]
779 /// use std::alloc::System;
781 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
782 /// let values = unsafe { values.assume_init() };
784 /// assert_eq!(*values, [0, 0, 0])
787 /// [zeroed]: mem::MaybeUninit::zeroed
788 #[cfg(not(no_global_oom_handling))]
789 #[unstable(feature = "allocator_api", issue = "32838")]
790 // #[unstable(feature = "new_uninit", issue = "63291")]
792 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
793 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
797 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
798 /// Converts to `Box<T, A>`.
802 /// As with [`MaybeUninit::assume_init`],
803 /// it is up to the caller to guarantee that the value
804 /// really is in an initialized state.
805 /// Calling this when the content is not yet fully initialized
806 /// causes immediate undefined behavior.
808 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
813 /// #![feature(new_uninit)]
815 /// let mut five = Box::<u32>::new_uninit();
817 /// let five: Box<u32> = unsafe {
818 /// // Deferred initialization:
819 /// five.as_mut_ptr().write(5);
821 /// five.assume_init()
824 /// assert_eq!(*five, 5)
826 #[unstable(feature = "new_uninit", issue = "63291")]
827 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
829 pub const unsafe fn assume_init(self) -> Box<T, A> {
830 let (raw, alloc) = Box::into_raw_with_allocator(self);
831 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
834 /// Writes the value and converts to `Box<T, A>`.
836 /// This method converts the box similarly to [`Box::assume_init`] but
837 /// writes `value` into it before conversion thus guaranteeing safety.
838 /// In some scenarios use of this method may improve performance because
839 /// the compiler may be able to optimize copying from stack.
844 /// #![feature(new_uninit)]
846 /// let big_box = Box::<[usize; 1024]>::new_uninit();
848 /// let mut array = [0; 1024];
849 /// for (i, place) in array.iter_mut().enumerate() {
853 /// // The optimizer may be able to elide this copy, so previous code writes
854 /// // to heap directly.
855 /// let big_box = Box::write(big_box, array);
857 /// for (i, x) in big_box.iter().enumerate() {
858 /// assert_eq!(*x, i);
861 #[unstable(feature = "new_uninit", issue = "63291")]
862 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
864 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
866 (*boxed).write(value);
872 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
873 /// Converts to `Box<[T], A>`.
877 /// As with [`MaybeUninit::assume_init`],
878 /// it is up to the caller to guarantee that the values
879 /// really are in an initialized state.
880 /// Calling this when the content is not yet fully initialized
881 /// causes immediate undefined behavior.
883 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
888 /// #![feature(new_uninit)]
890 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
892 /// let values = unsafe {
893 /// // Deferred initialization:
894 /// values[0].as_mut_ptr().write(1);
895 /// values[1].as_mut_ptr().write(2);
896 /// values[2].as_mut_ptr().write(3);
898 /// values.assume_init()
901 /// assert_eq!(*values, [1, 2, 3])
903 #[unstable(feature = "new_uninit", issue = "63291")]
905 pub unsafe fn assume_init(self) -> Box<[T], A> {
906 let (raw, alloc) = Box::into_raw_with_allocator(self);
907 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
911 impl<T: ?Sized> Box<T> {
912 /// Constructs a box from a raw pointer.
914 /// After calling this function, the raw pointer is owned by the
915 /// resulting `Box`. Specifically, the `Box` destructor will call
916 /// the destructor of `T` and free the allocated memory. For this
917 /// to be safe, the memory must have been allocated in accordance
918 /// with the [memory layout] used by `Box` .
922 /// This function is unsafe because improper use may lead to
923 /// memory problems. For example, a double-free may occur if the
924 /// function is called twice on the same raw pointer.
926 /// The safety conditions are described in the [memory layout] section.
930 /// Recreate a `Box` which was previously converted to a raw pointer
931 /// using [`Box::into_raw`]:
933 /// let x = Box::new(5);
934 /// let ptr = Box::into_raw(x);
935 /// let x = unsafe { Box::from_raw(ptr) };
937 /// Manually create a `Box` from scratch by using the global allocator:
939 /// use std::alloc::{alloc, Layout};
942 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
943 /// // In general .write is required to avoid attempting to destruct
944 /// // the (uninitialized) previous contents of `ptr`, though for this
945 /// // simple example `*ptr = 5` would have worked as well.
947 /// let x = Box::from_raw(ptr);
951 /// [memory layout]: self#memory-layout
952 /// [`Layout`]: crate::Layout
953 #[stable(feature = "box_raw", since = "1.4.0")]
955 #[must_use = "call `drop(from_raw(ptr))` if you intend to drop the `Box`"]
956 pub unsafe fn from_raw(raw: *mut T) -> Self {
957 unsafe { Self::from_raw_in(raw, Global) }
961 impl<T: ?Sized, A: Allocator> Box<T, A> {
962 /// Constructs a box from a raw pointer in the given allocator.
964 /// After calling this function, the raw pointer is owned by the
965 /// resulting `Box`. Specifically, the `Box` destructor will call
966 /// the destructor of `T` and free the allocated memory. For this
967 /// to be safe, the memory must have been allocated in accordance
968 /// with the [memory layout] used by `Box` .
972 /// This function is unsafe because improper use may lead to
973 /// memory problems. For example, a double-free may occur if the
974 /// function is called twice on the same raw pointer.
979 /// Recreate a `Box` which was previously converted to a raw pointer
980 /// using [`Box::into_raw_with_allocator`]:
982 /// #![feature(allocator_api)]
984 /// use std::alloc::System;
986 /// let x = Box::new_in(5, System);
987 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
988 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
990 /// Manually create a `Box` from scratch by using the system allocator:
992 /// #![feature(allocator_api, slice_ptr_get)]
994 /// use std::alloc::{Allocator, Layout, System};
997 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
998 /// // In general .write is required to avoid attempting to destruct
999 /// // the (uninitialized) previous contents of `ptr`, though for this
1000 /// // simple example `*ptr = 5` would have worked as well.
1002 /// let x = Box::from_raw_in(ptr, System);
1004 /// # Ok::<(), std::alloc::AllocError>(())
1007 /// [memory layout]: self#memory-layout
1008 /// [`Layout`]: crate::Layout
1009 #[unstable(feature = "allocator_api", issue = "32838")]
1010 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1012 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1013 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1016 /// Consumes the `Box`, returning a wrapped raw pointer.
1018 /// The pointer will be properly aligned and non-null.
1020 /// After calling this function, the caller is responsible for the
1021 /// memory previously managed by the `Box`. In particular, the
1022 /// caller should properly destroy `T` and release the memory, taking
1023 /// into account the [memory layout] used by `Box`. The easiest way to
1024 /// do this is to convert the raw pointer back into a `Box` with the
1025 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1028 /// Note: this is an associated function, which means that you have
1029 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1030 /// is so that there is no conflict with a method on the inner type.
1033 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1034 /// for automatic cleanup:
1036 /// let x = Box::new(String::from("Hello"));
1037 /// let ptr = Box::into_raw(x);
1038 /// let x = unsafe { Box::from_raw(ptr) };
1040 /// Manual cleanup by explicitly running the destructor and deallocating
1043 /// use std::alloc::{dealloc, Layout};
1046 /// let x = Box::new(String::from("Hello"));
1047 /// let p = Box::into_raw(x);
1049 /// ptr::drop_in_place(p);
1050 /// dealloc(p as *mut u8, Layout::new::<String>());
1054 /// [memory layout]: self#memory-layout
1055 #[stable(feature = "box_raw", since = "1.4.0")]
1057 pub fn into_raw(b: Self) -> *mut T {
1058 Self::into_raw_with_allocator(b).0
1061 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1063 /// The pointer will be properly aligned and non-null.
1065 /// After calling this function, the caller is responsible for the
1066 /// memory previously managed by the `Box`. In particular, the
1067 /// caller should properly destroy `T` and release the memory, taking
1068 /// into account the [memory layout] used by `Box`. The easiest way to
1069 /// do this is to convert the raw pointer back into a `Box` with the
1070 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1073 /// Note: this is an associated function, which means that you have
1074 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1075 /// is so that there is no conflict with a method on the inner type.
1078 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1079 /// for automatic cleanup:
1081 /// #![feature(allocator_api)]
1083 /// use std::alloc::System;
1085 /// let x = Box::new_in(String::from("Hello"), System);
1086 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1087 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1089 /// Manual cleanup by explicitly running the destructor and deallocating
1092 /// #![feature(allocator_api)]
1094 /// use std::alloc::{Allocator, Layout, System};
1095 /// use std::ptr::{self, NonNull};
1097 /// let x = Box::new_in(String::from("Hello"), System);
1098 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1100 /// ptr::drop_in_place(ptr);
1101 /// let non_null = NonNull::new_unchecked(ptr);
1102 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1106 /// [memory layout]: self#memory-layout
1107 #[unstable(feature = "allocator_api", issue = "32838")]
1108 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1110 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1111 let (leaked, alloc) = Box::into_unique(b);
1112 (leaked.as_ptr(), alloc)
1116 feature = "ptr_internals",
1118 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1120 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1123 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1124 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1125 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1126 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1127 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1128 // behaves correctly.
1129 let alloc = unsafe { ptr::read(&b.1) };
1130 (Unique::from(Box::leak(b)), alloc)
1133 /// Returns a reference to the underlying allocator.
1135 /// Note: this is an associated function, which means that you have
1136 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1137 /// is so that there is no conflict with a method on the inner type.
1138 #[unstable(feature = "allocator_api", issue = "32838")]
1139 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1141 pub const fn allocator(b: &Self) -> &A {
1145 /// Consumes and leaks the `Box`, returning a mutable reference,
1146 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1147 /// `'a`. If the type has only static references, or none at all, then this
1148 /// may be chosen to be `'static`.
1150 /// This function is mainly useful for data that lives for the remainder of
1151 /// the program's life. Dropping the returned reference will cause a memory
1152 /// leak. If this is not acceptable, the reference should first be wrapped
1153 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1154 /// then be dropped which will properly destroy `T` and release the
1155 /// allocated memory.
1157 /// Note: this is an associated function, which means that you have
1158 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1159 /// is so that there is no conflict with a method on the inner type.
1166 /// let x = Box::new(41);
1167 /// let static_ref: &'static mut usize = Box::leak(x);
1168 /// *static_ref += 1;
1169 /// assert_eq!(*static_ref, 42);
1175 /// let x = vec![1, 2, 3].into_boxed_slice();
1176 /// let static_ref = Box::leak(x);
1177 /// static_ref[0] = 4;
1178 /// assert_eq!(*static_ref, [4, 2, 3]);
1180 #[stable(feature = "box_leak", since = "1.26.0")]
1181 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1183 pub const fn leak<'a>(b: Self) -> &'a mut T
1187 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1190 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1191 /// `*boxed` will be pinned in memory and unable to be moved.
1193 /// This conversion does not allocate on the heap and happens in place.
1195 /// This is also available via [`From`].
1197 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1198 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1199 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1200 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1204 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1205 /// as it'll introduce an ambiguity when calling `Pin::from`.
1206 /// A demonstration of such a poor impl is shown below.
1209 /// # use std::pin::Pin;
1210 /// struct Foo; // A type defined in this crate.
1211 /// impl From<Box<()>> for Pin<Foo> {
1212 /// fn from(_: Box<()>) -> Pin<Foo> {
1217 /// let foo = Box::new(());
1218 /// let bar = Pin::from(foo);
1220 #[stable(feature = "box_into_pin", since = "1.63.0")]
1221 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1222 pub const fn into_pin(boxed: Self) -> Pin<Self>
1226 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1227 // when `T: !Unpin`, so it's safe to pin it directly without any
1228 // additional requirements.
1229 unsafe { Pin::new_unchecked(boxed) }
1233 #[stable(feature = "rust1", since = "1.0.0")]
1234 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1235 fn drop(&mut self) {
1236 // FIXME: Do nothing, drop is currently performed by compiler.
1240 #[cfg(not(no_global_oom_handling))]
1241 #[stable(feature = "rust1", since = "1.0.0")]
1242 impl<T: Default> Default for Box<T> {
1243 /// Creates a `Box<T>`, with the `Default` value for T.
1244 fn default() -> Self {
1246 Box::new(T::default())
1250 #[cfg(not(no_global_oom_handling))]
1251 #[stable(feature = "rust1", since = "1.0.0")]
1252 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1253 impl<T> const Default for Box<[T]> {
1254 fn default() -> Self {
1255 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1260 #[cfg(not(no_global_oom_handling))]
1261 #[stable(feature = "default_box_extra", since = "1.17.0")]
1262 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1263 impl const Default for Box<str> {
1264 fn default() -> Self {
1265 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1266 let ptr: Unique<str> = unsafe {
1267 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1268 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1274 #[cfg(not(no_global_oom_handling))]
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1277 /// Returns a new box with a `clone()` of this box's contents.
1282 /// let x = Box::new(5);
1283 /// let y = x.clone();
1285 /// // The value is the same
1286 /// assert_eq!(x, y);
1288 /// // But they are unique objects
1289 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1292 fn clone(&self) -> Self {
1293 // Pre-allocate memory to allow writing the cloned value directly.
1294 let mut boxed = Self::new_uninit_in(self.1.clone());
1296 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1301 /// Copies `source`'s contents into `self` without creating a new allocation.
1306 /// let x = Box::new(5);
1307 /// let mut y = Box::new(10);
1308 /// let yp: *const i32 = &*y;
1310 /// y.clone_from(&x);
1312 /// // The value is the same
1313 /// assert_eq!(x, y);
1315 /// // And no allocation occurred
1316 /// assert_eq!(yp, &*y);
1319 fn clone_from(&mut self, source: &Self) {
1320 (**self).clone_from(&(**source));
1324 #[cfg(not(no_global_oom_handling))]
1325 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1326 impl Clone for Box<str> {
1327 fn clone(&self) -> Self {
1328 // this makes a copy of the data
1329 let buf: Box<[u8]> = self.as_bytes().into();
1330 unsafe { from_boxed_utf8_unchecked(buf) }
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1337 fn eq(&self, other: &Self) -> bool {
1338 PartialEq::eq(&**self, &**other)
1341 fn ne(&self, other: &Self) -> bool {
1342 PartialEq::ne(&**self, &**other)
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1348 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1349 PartialOrd::partial_cmp(&**self, &**other)
1352 fn lt(&self, other: &Self) -> bool {
1353 PartialOrd::lt(&**self, &**other)
1356 fn le(&self, other: &Self) -> bool {
1357 PartialOrd::le(&**self, &**other)
1360 fn ge(&self, other: &Self) -> bool {
1361 PartialOrd::ge(&**self, &**other)
1364 fn gt(&self, other: &Self) -> bool {
1365 PartialOrd::gt(&**self, &**other)
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1371 fn cmp(&self, other: &Self) -> Ordering {
1372 Ord::cmp(&**self, &**other)
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1378 #[stable(feature = "rust1", since = "1.0.0")]
1379 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1380 fn hash<H: Hasher>(&self, state: &mut H) {
1381 (**self).hash(state);
1385 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1386 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1387 fn finish(&self) -> u64 {
1390 fn write(&mut self, bytes: &[u8]) {
1391 (**self).write(bytes)
1393 fn write_u8(&mut self, i: u8) {
1394 (**self).write_u8(i)
1396 fn write_u16(&mut self, i: u16) {
1397 (**self).write_u16(i)
1399 fn write_u32(&mut self, i: u32) {
1400 (**self).write_u32(i)
1402 fn write_u64(&mut self, i: u64) {
1403 (**self).write_u64(i)
1405 fn write_u128(&mut self, i: u128) {
1406 (**self).write_u128(i)
1408 fn write_usize(&mut self, i: usize) {
1409 (**self).write_usize(i)
1411 fn write_i8(&mut self, i: i8) {
1412 (**self).write_i8(i)
1414 fn write_i16(&mut self, i: i16) {
1415 (**self).write_i16(i)
1417 fn write_i32(&mut self, i: i32) {
1418 (**self).write_i32(i)
1420 fn write_i64(&mut self, i: i64) {
1421 (**self).write_i64(i)
1423 fn write_i128(&mut self, i: i128) {
1424 (**self).write_i128(i)
1426 fn write_isize(&mut self, i: isize) {
1427 (**self).write_isize(i)
1429 fn write_length_prefix(&mut self, len: usize) {
1430 (**self).write_length_prefix(len)
1432 fn write_str(&mut self, s: &str) {
1433 (**self).write_str(s)
1437 #[cfg(not(no_global_oom_handling))]
1438 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1439 impl<T> From<T> for Box<T> {
1440 /// Converts a `T` into a `Box<T>`
1442 /// The conversion allocates on the heap and moves `t`
1443 /// from the stack into it.
1449 /// let boxed = Box::new(5);
1451 /// assert_eq!(Box::from(x), boxed);
1453 fn from(t: T) -> Self {
1458 #[stable(feature = "pin", since = "1.33.0")]
1459 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1460 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1464 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1465 /// `*boxed` will be pinned in memory and unable to be moved.
1467 /// This conversion does not allocate on the heap and happens in place.
1469 /// This is also available via [`Box::into_pin`].
1471 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
1472 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1473 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
1474 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1475 fn from(boxed: Box<T, A>) -> Self {
1476 Box::into_pin(boxed)
1480 #[cfg(not(no_global_oom_handling))]
1481 #[stable(feature = "box_from_slice", since = "1.17.0")]
1482 impl<T: Copy> From<&[T]> for Box<[T]> {
1483 /// Converts a `&[T]` into a `Box<[T]>`
1485 /// This conversion allocates on the heap
1486 /// and performs a copy of `slice` and its contents.
1490 /// // create a &[u8] which will be used to create a Box<[u8]>
1491 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1492 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1494 /// println!("{boxed_slice:?}");
1496 fn from(slice: &[T]) -> Box<[T]> {
1497 let len = slice.len();
1498 let buf = RawVec::with_capacity(len);
1500 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1501 buf.into_box(slice.len()).assume_init()
1506 #[cfg(not(no_global_oom_handling))]
1507 #[stable(feature = "box_from_cow", since = "1.45.0")]
1508 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1509 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1511 /// When `cow` is the `Cow::Borrowed` variant, this
1512 /// conversion allocates on the heap and copies the
1513 /// underlying slice. Otherwise, it will try to reuse the owned
1514 /// `Vec`'s allocation.
1516 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1518 Cow::Borrowed(slice) => Box::from(slice),
1519 Cow::Owned(slice) => Box::from(slice),
1524 #[cfg(not(no_global_oom_handling))]
1525 #[stable(feature = "box_from_slice", since = "1.17.0")]
1526 impl From<&str> for Box<str> {
1527 /// Converts a `&str` into a `Box<str>`
1529 /// This conversion allocates on the heap
1530 /// and performs a copy of `s`.
1535 /// let boxed: Box<str> = Box::from("hello");
1536 /// println!("{boxed}");
1539 fn from(s: &str) -> Box<str> {
1540 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1544 #[cfg(not(no_global_oom_handling))]
1545 #[stable(feature = "box_from_cow", since = "1.45.0")]
1546 impl From<Cow<'_, str>> for Box<str> {
1547 /// Converts a `Cow<'_, str>` into a `Box<str>`
1549 /// When `cow` is the `Cow::Borrowed` variant, this
1550 /// conversion allocates on the heap and copies the
1551 /// underlying `str`. Otherwise, it will try to reuse the owned
1552 /// `String`'s allocation.
1557 /// use std::borrow::Cow;
1559 /// let unboxed = Cow::Borrowed("hello");
1560 /// let boxed: Box<str> = Box::from(unboxed);
1561 /// println!("{boxed}");
1565 /// # use std::borrow::Cow;
1566 /// let unboxed = Cow::Owned("hello".to_string());
1567 /// let boxed: Box<str> = Box::from(unboxed);
1568 /// println!("{boxed}");
1571 fn from(cow: Cow<'_, str>) -> Box<str> {
1573 Cow::Borrowed(s) => Box::from(s),
1574 Cow::Owned(s) => Box::from(s),
1579 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1580 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1581 /// Converts a `Box<str>` into a `Box<[u8]>`
1583 /// This conversion does not allocate on the heap and happens in place.
1587 /// // create a Box<str> which will be used to create a Box<[u8]>
1588 /// let boxed: Box<str> = Box::from("hello");
1589 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1591 /// // create a &[u8] which will be used to create a Box<[u8]>
1592 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1593 /// let boxed_slice = Box::from(slice);
1595 /// assert_eq!(boxed_slice, boxed_str);
1598 fn from(s: Box<str, A>) -> Self {
1599 let (raw, alloc) = Box::into_raw_with_allocator(s);
1600 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1604 #[cfg(not(no_global_oom_handling))]
1605 #[stable(feature = "box_from_array", since = "1.45.0")]
1606 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1607 /// Converts a `[T; N]` into a `Box<[T]>`
1609 /// This conversion moves the array to newly heap-allocated memory.
1614 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1615 /// println!("{boxed:?}");
1617 fn from(array: [T; N]) -> Box<[T]> {
1623 /// Casts a boxed slice to a boxed array.
1627 /// `boxed_slice.len()` must be exactly `N`.
1628 unsafe fn boxed_slice_as_array_unchecked<T, A: Allocator, const N: usize>(
1629 boxed_slice: Box<[T], A>,
1630 ) -> Box<[T; N], A> {
1631 debug_assert_eq!(boxed_slice.len(), N);
1633 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
1634 // SAFETY: Pointer and allocator came from an existing box,
1635 // and our safety condition requires that the length is exactly `N`
1636 unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) }
1639 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1640 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1641 type Error = Box<[T]>;
1643 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1645 /// The conversion occurs in-place and does not require a
1646 /// new memory allocation.
1650 /// Returns the old `Box<[T]>` in the `Err` variant if
1651 /// `boxed_slice.len()` does not equal `N`.
1652 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1653 if boxed_slice.len() == N {
1654 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1661 #[cfg(not(no_global_oom_handling))]
1662 #[stable(feature = "boxed_array_try_from_vec", since = "CURRENT_RUSTC_VERSION")]
1663 impl<T, const N: usize> TryFrom<Vec<T>> for Box<[T; N]> {
1664 type Error = Vec<T>;
1666 /// Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.
1668 /// Like [`Vec::into_boxed_slice`], this is in-place if `vec.capacity() == N`,
1669 /// but will require a reallocation otherwise.
1673 /// Returns the original `Vec<T>` in the `Err` variant if
1674 /// `boxed_slice.len()` does not equal `N`.
1678 /// This can be used with [`vec!`] to create an array on the heap:
1681 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
1682 /// assert_eq!(state.len(), 100);
1684 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1686 let boxed_slice = vec.into_boxed_slice();
1687 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1694 impl<A: Allocator> Box<dyn Any, A> {
1695 /// Attempt to downcast the box to a concrete type.
1700 /// use std::any::Any;
1702 /// fn print_if_string(value: Box<dyn Any>) {
1703 /// if let Ok(string) = value.downcast::<String>() {
1704 /// println!("String ({}): {}", string.len(), string);
1708 /// let my_string = "Hello World".to_string();
1709 /// print_if_string(Box::new(my_string));
1710 /// print_if_string(Box::new(0i8));
1713 #[stable(feature = "rust1", since = "1.0.0")]
1714 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1715 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1718 /// Downcasts the box to a concrete type.
1720 /// For a safe alternative see [`downcast`].
1725 /// #![feature(downcast_unchecked)]
1727 /// use std::any::Any;
1729 /// let x: Box<dyn Any> = Box::new(1_usize);
1732 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1738 /// The contained value must be of type `T`. Calling this method
1739 /// with the incorrect type is *undefined behavior*.
1741 /// [`downcast`]: Self::downcast
1743 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1744 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1745 debug_assert!(self.is::<T>());
1747 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1748 Box::from_raw_in(raw as *mut T, alloc)
1753 impl<A: Allocator> Box<dyn Any + Send, A> {
1754 /// Attempt to downcast the box to a concrete type.
1759 /// use std::any::Any;
1761 /// fn print_if_string(value: Box<dyn Any + Send>) {
1762 /// if let Ok(string) = value.downcast::<String>() {
1763 /// println!("String ({}): {}", string.len(), string);
1767 /// let my_string = "Hello World".to_string();
1768 /// print_if_string(Box::new(my_string));
1769 /// print_if_string(Box::new(0i8));
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1774 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1777 /// Downcasts the box to a concrete type.
1779 /// For a safe alternative see [`downcast`].
1784 /// #![feature(downcast_unchecked)]
1786 /// use std::any::Any;
1788 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1791 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1797 /// The contained value must be of type `T`. Calling this method
1798 /// with the incorrect type is *undefined behavior*.
1800 /// [`downcast`]: Self::downcast
1802 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1803 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1804 debug_assert!(self.is::<T>());
1806 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1807 Box::from_raw_in(raw as *mut T, alloc)
1812 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1813 /// Attempt to downcast the box to a concrete type.
1818 /// use std::any::Any;
1820 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1821 /// if let Ok(string) = value.downcast::<String>() {
1822 /// println!("String ({}): {}", string.len(), string);
1826 /// let my_string = "Hello World".to_string();
1827 /// print_if_string(Box::new(my_string));
1828 /// print_if_string(Box::new(0i8));
1831 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1832 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1833 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1836 /// Downcasts the box to a concrete type.
1838 /// For a safe alternative see [`downcast`].
1843 /// #![feature(downcast_unchecked)]
1845 /// use std::any::Any;
1847 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1850 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1856 /// The contained value must be of type `T`. Calling this method
1857 /// with the incorrect type is *undefined behavior*.
1859 /// [`downcast`]: Self::downcast
1861 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1862 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1863 debug_assert!(self.is::<T>());
1865 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1866 Box::into_raw_with_allocator(self);
1867 Box::from_raw_in(raw as *mut T, alloc)
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1874 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1875 fmt::Display::fmt(&**self, f)
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1882 fmt::Debug::fmt(&**self, f)
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1888 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1889 // It's not possible to extract the inner Uniq directly from the Box,
1890 // instead we cast it to a *const which aliases the Unique
1891 let ptr: *const T = &**self;
1892 fmt::Pointer::fmt(&ptr, f)
1896 #[stable(feature = "rust1", since = "1.0.0")]
1897 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1898 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1901 fn deref(&self) -> &T {
1906 #[stable(feature = "rust1", since = "1.0.0")]
1907 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1908 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1909 fn deref_mut(&mut self) -> &mut T {
1914 #[unstable(feature = "receiver_trait", issue = "none")]
1915 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1917 #[stable(feature = "rust1", since = "1.0.0")]
1918 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1919 type Item = I::Item;
1920 fn next(&mut self) -> Option<I::Item> {
1923 fn size_hint(&self) -> (usize, Option<usize>) {
1924 (**self).size_hint()
1926 fn nth(&mut self, n: usize) -> Option<I::Item> {
1929 fn last(self) -> Option<I::Item> {
1936 fn last(self) -> Option<Self::Item>;
1939 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1940 type Item = I::Item;
1941 default fn last(self) -> Option<I::Item> {
1943 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1947 self.fold(None, some)
1951 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1952 /// instead of the default.
1953 #[stable(feature = "rust1", since = "1.0.0")]
1954 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1955 fn last(self) -> Option<I::Item> {
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1962 fn next_back(&mut self) -> Option<I::Item> {
1963 (**self).next_back()
1965 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1966 (**self).nth_back(n)
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1971 fn len(&self) -> usize {
1974 fn is_empty(&self) -> bool {
1979 #[stable(feature = "fused", since = "1.26.0")]
1980 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1982 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1983 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1984 type Output = <F as FnOnce<Args>>::Output;
1986 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1987 <F as FnOnce<Args>>::call_once(*self, args)
1991 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1992 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1993 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1994 <F as FnMut<Args>>::call_mut(self, args)
1998 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1999 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2000 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2001 <F as Fn<Args>>::call(self, args)
2005 #[unstable(feature = "coerce_unsized", issue = "27732")]
2006 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2008 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
2009 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2011 #[cfg(not(no_global_oom_handling))]
2012 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
2013 impl<I> FromIterator<I> for Box<[I]> {
2014 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
2015 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
2019 #[cfg(not(no_global_oom_handling))]
2020 #[stable(feature = "box_slice_clone", since = "1.3.0")]
2021 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2022 fn clone(&self) -> Self {
2023 let alloc = Box::allocator(self).clone();
2024 self.to_vec_in(alloc).into_boxed_slice()
2027 fn clone_from(&mut self, other: &Self) {
2028 if self.len() == other.len() {
2029 self.clone_from_slice(&other);
2031 *self = other.clone();
2036 #[stable(feature = "box_borrow", since = "1.1.0")]
2037 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
2038 fn borrow(&self) -> &T {
2043 #[stable(feature = "box_borrow", since = "1.1.0")]
2044 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
2045 fn borrow_mut(&mut self) -> &mut T {
2050 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2051 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2052 fn as_ref(&self) -> &T {
2057 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2058 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2059 fn as_mut(&mut self) -> &mut T {
2066 * We could have chosen not to add this impl, and instead have written a
2067 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2068 * because Box<T> implements Unpin even when T does not, as a result of
2071 * We chose this API instead of the alternative for a few reasons:
2072 * - Logically, it is helpful to understand pinning in regard to the
2073 * memory region being pointed to. For this reason none of the
2074 * standard library pointer types support projecting through a pin
2075 * (Box<T> is the only pointer type in std for which this would be
2077 * - It is in practice very useful to have Box<T> be unconditionally
2078 * Unpin because of trait objects, for which the structural auto
2079 * trait functionality does not apply (e.g., Box<dyn Foo> would
2080 * otherwise not be Unpin).
2082 * Another type with the same semantics as Box but only a conditional
2083 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2084 * could have a method to project a Pin<T> from it.
2086 #[stable(feature = "pin", since = "1.33.0")]
2087 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
2089 #[unstable(feature = "generator_trait", issue = "43122")]
2090 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2094 type Yield = G::Yield;
2095 type Return = G::Return;
2097 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2098 G::resume(Pin::new(&mut *self), arg)
2102 #[unstable(feature = "generator_trait", issue = "43122")]
2103 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2107 type Yield = G::Yield;
2108 type Return = G::Return;
2110 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2111 G::resume((*self).as_mut(), arg)
2115 #[stable(feature = "futures_api", since = "1.36.0")]
2116 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2120 type Output = F::Output;
2122 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2123 F::poll(Pin::new(&mut *self), cx)
2127 #[unstable(feature = "async_iterator", issue = "79024")]
2128 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2129 type Item = S::Item;
2131 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2132 Pin::new(&mut **self).poll_next(cx)
2135 fn size_hint(&self) -> (usize, Option<usize>) {
2136 (**self).size_hint()
2142 #[stable(feature = "error_downcast", since = "1.3.0")]
2143 #[rustc_allow_incoherent_impl]
2144 /// Attempts to downcast the box to a concrete type.
2145 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
2148 let raw: *mut dyn Error = Box::into_raw(self);
2149 Ok(Box::from_raw(raw as *mut T))
2157 impl dyn Error + Send {
2159 #[stable(feature = "error_downcast", since = "1.3.0")]
2160 #[rustc_allow_incoherent_impl]
2161 /// Attempts to downcast the box to a concrete type.
2162 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
2163 let err: Box<dyn Error> = self;
2164 <dyn Error>::downcast(err).map_err(|s| unsafe {
2165 // Reapply the `Send` marker.
2166 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
2171 impl dyn Error + Send + Sync {
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<Self>> {
2177 let err: Box<dyn Error> = self;
2178 <dyn Error>::downcast(err).map_err(|s| unsafe {
2179 // Reapply the `Send + Sync` marker.
2180 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
2185 #[cfg(not(no_global_oom_handling))]
2186 #[stable(feature = "rust1", since = "1.0.0")]
2187 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
2188 /// Converts a type of [`Error`] into a box of dyn [`Error`].
2193 /// use std::error::Error;
2197 /// #[derive(Debug)]
2200 /// impl fmt::Display for AnError {
2201 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2202 /// write!(f, "An error")
2206 /// impl Error for AnError {}
2208 /// let an_error = AnError;
2209 /// assert!(0 == mem::size_of_val(&an_error));
2210 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
2211 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2213 fn from(err: E) -> Box<dyn Error + 'a> {
2218 #[cfg(not(no_global_oom_handling))]
2219 #[stable(feature = "rust1", since = "1.0.0")]
2220 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
2221 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
2222 /// dyn [`Error`] + [`Send`] + [`Sync`].
2227 /// use std::error::Error;
2231 /// #[derive(Debug)]
2234 /// impl fmt::Display for AnError {
2235 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2236 /// write!(f, "An error")
2240 /// impl Error for AnError {}
2242 /// unsafe impl Send for AnError {}
2244 /// unsafe impl Sync for AnError {}
2246 /// let an_error = AnError;
2247 /// assert!(0 == mem::size_of_val(&an_error));
2248 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
2250 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2252 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
2257 #[cfg(not(no_global_oom_handling))]
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 impl From<String> for Box<dyn Error + Send + Sync> {
2260 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2265 /// use std::error::Error;
2268 /// let a_string_error = "a string error".to_string();
2269 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
2271 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2274 fn from(err: String) -> Box<dyn Error + Send + Sync> {
2275 struct StringError(String);
2277 impl Error for StringError {
2278 #[allow(deprecated)]
2279 fn description(&self) -> &str {
2284 impl fmt::Display for StringError {
2285 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2286 fmt::Display::fmt(&self.0, f)
2290 // Purposefully skip printing "StringError(..)"
2291 impl fmt::Debug for StringError {
2292 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2293 fmt::Debug::fmt(&self.0, f)
2297 Box::new(StringError(err))
2301 #[cfg(not(no_global_oom_handling))]
2302 #[stable(feature = "string_box_error", since = "1.6.0")]
2303 impl From<String> for Box<dyn Error> {
2304 /// Converts a [`String`] into a box of dyn [`Error`].
2309 /// use std::error::Error;
2312 /// let a_string_error = "a string error".to_string();
2313 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
2314 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2316 fn from(str_err: String) -> Box<dyn Error> {
2317 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
2318 let err2: Box<dyn Error> = err1;
2323 #[cfg(not(no_global_oom_handling))]
2324 #[stable(feature = "rust1", since = "1.0.0")]
2325 impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
2326 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2328 /// [`str`]: prim@str
2333 /// use std::error::Error;
2336 /// let a_str_error = "a str error";
2337 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
2339 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2342 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
2343 From::from(String::from(err))
2347 #[cfg(not(no_global_oom_handling))]
2348 #[stable(feature = "string_box_error", since = "1.6.0")]
2349 impl From<&str> for Box<dyn Error> {
2350 /// Converts a [`str`] into a box of dyn [`Error`].
2352 /// [`str`]: prim@str
2357 /// use std::error::Error;
2360 /// let a_str_error = "a str error";
2361 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
2362 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2364 fn from(err: &str) -> Box<dyn Error> {
2365 From::from(String::from(err))
2369 #[cfg(not(no_global_oom_handling))]
2370 #[stable(feature = "cow_box_error", since = "1.22.0")]
2371 impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
2372 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2377 /// use std::error::Error;
2379 /// use std::borrow::Cow;
2381 /// let a_cow_str_error = Cow::from("a str error");
2382 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
2384 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2386 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
2387 From::from(String::from(err))
2391 #[cfg(not(no_global_oom_handling))]
2392 #[stable(feature = "cow_box_error", since = "1.22.0")]
2393 impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
2394 /// Converts a [`Cow`] into a box of dyn [`Error`].
2399 /// use std::error::Error;
2401 /// use std::borrow::Cow;
2403 /// let a_cow_str_error = Cow::from("a str error");
2404 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
2405 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2407 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
2408 From::from(String::from(err))
2412 #[stable(feature = "box_error", since = "1.8.0")]
2413 impl<T: core::error::Error> core::error::Error for Box<T> {
2414 #[allow(deprecated, deprecated_in_future)]
2415 fn description(&self) -> &str {
2416 core::error::Error::description(&**self)
2419 #[allow(deprecated)]
2420 fn cause(&self) -> Option<&dyn core::error::Error> {
2421 core::error::Error::cause(&**self)
2424 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
2425 core::error::Error::source(&**self)