1 //! A pointer type for heap allocation.
3 //! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
4 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
5 //! drop their contents when they go out of scope. Boxes also ensure that they
6 //! never allocate more than `isize::MAX` bytes.
10 //! Move a value from the stack to the heap by creating a [`Box`]:
14 //! let boxed: Box<u8> = Box::new(val);
17 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
20 //! let boxed: Box<u8> = Box::new(5);
21 //! let val: u8 = *boxed;
24 //! Creating a recursive data structure:
29 //! Cons(T, Box<List<T>>),
33 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //! println!("{list:?}");
37 //! This will print `Cons(1, Cons(2, Nil))`.
39 //! Recursive structures must be boxed, because if the definition of `Cons`
42 //! ```compile_fail,E0072
48 //! It wouldn't work. This is because the size of a `List` depends on how many
49 //! elements are in the list, and so we don't know how much memory to allocate
50 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
51 //! big `Cons` needs to be.
55 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
56 //! its allocation. It is valid to convert both ways between a [`Box`] and a
57 //! raw pointer allocated with the [`Global`] allocator, given that the
58 //! [`Layout`] used with the allocator is correct for the type. More precisely,
59 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
60 //! with `Layout::for_value(&*value)` may be converted into a box using
61 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
62 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
63 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
65 //! For zero-sized values, the `Box` pointer still has to be [valid] for reads
66 //! and writes and sufficiently aligned. In particular, casting any aligned
67 //! non-zero integer literal to a raw pointer produces a valid pointer, but a
68 //! pointer pointing into previously allocated memory that since got freed is
69 //! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
70 //! be used is to use [`ptr::NonNull::dangling`].
72 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
73 //! as a single pointer and is also ABI-compatible with C pointers
74 //! (i.e. the C type `T*`). This means that if you have extern "C"
75 //! Rust functions that will be called from C, you can define those
76 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
77 //! type on the C side. As an example, consider this C header which
78 //! declares functions that create and destroy some kind of `Foo`
84 //! /* Returns ownership to the caller */
85 //! struct Foo* foo_new(void);
87 //! /* Takes ownership from the caller; no-op when invoked with null */
88 //! void foo_delete(struct Foo*);
91 //! These two functions might be implemented in Rust as follows. Here, the
92 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
93 //! the ownership constraints. Note also that the nullable argument to
94 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
102 //! pub extern "C" fn foo_new() -> Box<Foo> {
107 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
110 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
111 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
112 //! and expect things to work. `Box<T>` values will always be fully aligned,
113 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
114 //! free the value with the global allocator. In general, the best practice
115 //! is to only use `Box<T>` for pointers that originated from the global
118 //! **Important.** At least at present, you should avoid using
119 //! `Box<T>` types for functions that are defined in C but invoked
120 //! from Rust. In those cases, you should directly mirror the C types
121 //! as closely as possible. Using types like `Box<T>` where the C
122 //! definition is just using `T*` can lead to undefined behavior, as
123 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
125 //! # 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};
155 use core::future::Future;
156 use core::hash::{Hash, Hasher};
157 #[cfg(not(no_global_oom_handling))]
158 use core::iter::FromIterator;
159 use core::iter::{FusedIterator, Iterator};
160 use core::marker::{Destruct, Unpin, Unsize};
163 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
166 use core::ptr::{self, Unique};
167 use core::task::{Context, Poll};
169 #[cfg(not(no_global_oom_handling))]
170 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
171 use crate::alloc::{AllocError, Allocator, Global, Layout};
172 #[cfg(not(no_global_oom_handling))]
173 use crate::borrow::Cow;
174 use crate::raw_vec::RawVec;
175 #[cfg(not(no_global_oom_handling))]
176 use crate::str::from_boxed_utf8_unchecked;
177 #[cfg(not(no_global_oom_handling))]
180 #[unstable(feature = "thin_box", issue = "92791")]
181 pub use thin::ThinBox;
185 /// A pointer type for heap allocation.
187 /// See the [module-level documentation](../../std/boxed/index.html) for more.
188 #[lang = "owned_box"]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 // The declaration of the `Box` struct must be kept in sync with the
192 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
193 // on `box_free` for more details.
196 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
200 /// Allocates memory on the heap and then places `x` into it.
202 /// This doesn't actually allocate if `T` is zero-sized.
207 /// let five = Box::new(5);
209 #[cfg(not(no_global_oom_handling))]
211 #[stable(feature = "rust1", since = "1.0.0")]
213 pub fn new(x: T) -> Self {
217 /// Constructs a new box with uninitialized contents.
222 /// #![feature(new_uninit)]
224 /// let mut five = Box::<u32>::new_uninit();
226 /// let five = unsafe {
227 /// // Deferred initialization:
228 /// five.as_mut_ptr().write(5);
230 /// five.assume_init()
233 /// assert_eq!(*five, 5)
235 #[cfg(not(no_global_oom_handling))]
236 #[unstable(feature = "new_uninit", issue = "63291")]
239 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
240 Self::new_uninit_in(Global)
243 /// Constructs a new `Box` with uninitialized contents, with the memory
244 /// being filled with `0` bytes.
246 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
252 /// #![feature(new_uninit)]
254 /// let zero = Box::<u32>::new_zeroed();
255 /// let zero = unsafe { zero.assume_init() };
257 /// assert_eq!(*zero, 0)
260 /// [zeroed]: mem::MaybeUninit::zeroed
261 #[cfg(not(no_global_oom_handling))]
263 #[unstable(feature = "new_uninit", issue = "63291")]
265 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
266 Self::new_zeroed_in(Global)
269 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
270 /// `x` will be pinned in memory and unable to be moved.
271 #[cfg(not(no_global_oom_handling))]
272 #[stable(feature = "pin", since = "1.33.0")]
275 pub fn pin(x: T) -> Pin<Box<T>> {
279 /// Allocates memory on the heap then places `x` into it,
280 /// returning an error if the allocation fails
282 /// This doesn't actually allocate if `T` is zero-sized.
287 /// #![feature(allocator_api)]
289 /// let five = Box::try_new(5)?;
290 /// # Ok::<(), std::alloc::AllocError>(())
292 #[unstable(feature = "allocator_api", issue = "32838")]
294 pub fn try_new(x: T) -> Result<Self, AllocError> {
295 Self::try_new_in(x, Global)
298 /// Constructs a new box with uninitialized contents on the heap,
299 /// returning an error if the allocation fails
304 /// #![feature(allocator_api, new_uninit)]
306 /// let mut five = Box::<u32>::try_new_uninit()?;
308 /// let five = unsafe {
309 /// // Deferred initialization:
310 /// five.as_mut_ptr().write(5);
312 /// five.assume_init()
315 /// assert_eq!(*five, 5);
316 /// # Ok::<(), std::alloc::AllocError>(())
318 #[unstable(feature = "allocator_api", issue = "32838")]
319 // #[unstable(feature = "new_uninit", issue = "63291")]
321 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
322 Box::try_new_uninit_in(Global)
325 /// Constructs a new `Box` with uninitialized contents, with the memory
326 /// being filled with `0` bytes on the heap
328 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
334 /// #![feature(allocator_api, new_uninit)]
336 /// let zero = Box::<u32>::try_new_zeroed()?;
337 /// let zero = unsafe { zero.assume_init() };
339 /// assert_eq!(*zero, 0);
340 /// # Ok::<(), std::alloc::AllocError>(())
343 /// [zeroed]: mem::MaybeUninit::zeroed
344 #[unstable(feature = "allocator_api", issue = "32838")]
345 // #[unstable(feature = "new_uninit", issue = "63291")]
347 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
348 Box::try_new_zeroed_in(Global)
352 impl<T, A: Allocator> Box<T, A> {
353 /// Allocates memory in the given allocator then places `x` into it.
355 /// This doesn't actually allocate if `T` is zero-sized.
360 /// #![feature(allocator_api)]
362 /// use std::alloc::System;
364 /// let five = Box::new_in(5, System);
366 #[cfg(not(no_global_oom_handling))]
367 #[unstable(feature = "allocator_api", issue = "32838")]
368 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
371 pub const fn new_in(x: T, alloc: A) -> Self
373 A: ~const Allocator + ~const Destruct,
375 let mut boxed = Self::new_uninit_in(alloc);
377 boxed.as_mut_ptr().write(x);
382 /// Allocates memory in the given allocator then places `x` into it,
383 /// returning an error if the allocation fails
385 /// This doesn't actually allocate if `T` is zero-sized.
390 /// #![feature(allocator_api)]
392 /// use std::alloc::System;
394 /// let five = Box::try_new_in(5, System)?;
395 /// # Ok::<(), std::alloc::AllocError>(())
397 #[unstable(feature = "allocator_api", issue = "32838")]
398 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
400 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
403 A: ~const Allocator + ~const Destruct,
405 let mut boxed = Self::try_new_uninit_in(alloc)?;
407 boxed.as_mut_ptr().write(x);
408 Ok(boxed.assume_init())
412 /// Constructs a new box with uninitialized contents in the provided allocator.
417 /// #![feature(allocator_api, new_uninit)]
419 /// use std::alloc::System;
421 /// let mut five = Box::<u32, _>::new_uninit_in(System);
423 /// let five = unsafe {
424 /// // Deferred initialization:
425 /// five.as_mut_ptr().write(5);
427 /// five.assume_init()
430 /// assert_eq!(*five, 5)
432 #[unstable(feature = "allocator_api", issue = "32838")]
433 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
434 #[cfg(not(no_global_oom_handling))]
436 // #[unstable(feature = "new_uninit", issue = "63291")]
437 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
439 A: ~const Allocator + ~const Destruct,
441 let layout = Layout::new::<mem::MaybeUninit<T>>();
442 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
443 // That would make code size bigger.
444 match Box::try_new_uninit_in(alloc) {
446 Err(_) => handle_alloc_error(layout),
450 /// Constructs a new box with uninitialized contents in the provided allocator,
451 /// returning an error if the allocation fails
456 /// #![feature(allocator_api, new_uninit)]
458 /// use std::alloc::System;
460 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
462 /// let five = unsafe {
463 /// // Deferred initialization:
464 /// five.as_mut_ptr().write(5);
466 /// five.assume_init()
469 /// assert_eq!(*five, 5);
470 /// # Ok::<(), std::alloc::AllocError>(())
472 #[unstable(feature = "allocator_api", issue = "32838")]
473 // #[unstable(feature = "new_uninit", issue = "63291")]
474 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
475 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
477 A: ~const Allocator + ~const Destruct,
479 let layout = Layout::new::<mem::MaybeUninit<T>>();
480 let ptr = alloc.allocate(layout)?.cast();
481 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
484 /// Constructs a new `Box` with uninitialized contents, with the memory
485 /// being filled with `0` bytes in the provided allocator.
487 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
493 /// #![feature(allocator_api, new_uninit)]
495 /// use std::alloc::System;
497 /// let zero = Box::<u32, _>::new_zeroed_in(System);
498 /// let zero = unsafe { zero.assume_init() };
500 /// assert_eq!(*zero, 0)
503 /// [zeroed]: mem::MaybeUninit::zeroed
504 #[unstable(feature = "allocator_api", issue = "32838")]
505 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
506 #[cfg(not(no_global_oom_handling))]
507 // #[unstable(feature = "new_uninit", issue = "63291")]
509 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
511 A: ~const Allocator + ~const Destruct,
513 let layout = Layout::new::<mem::MaybeUninit<T>>();
514 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
515 // That would make code size bigger.
516 match Box::try_new_zeroed_in(alloc) {
518 Err(_) => handle_alloc_error(layout),
522 /// Constructs a new `Box` with uninitialized contents, with the memory
523 /// being filled with `0` bytes in the provided allocator,
524 /// returning an error if the allocation fails,
526 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
532 /// #![feature(allocator_api, new_uninit)]
534 /// use std::alloc::System;
536 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
537 /// let zero = unsafe { zero.assume_init() };
539 /// assert_eq!(*zero, 0);
540 /// # Ok::<(), std::alloc::AllocError>(())
543 /// [zeroed]: mem::MaybeUninit::zeroed
544 #[unstable(feature = "allocator_api", issue = "32838")]
545 // #[unstable(feature = "new_uninit", issue = "63291")]
546 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
547 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
549 A: ~const Allocator + ~const Destruct,
551 let layout = Layout::new::<mem::MaybeUninit<T>>();
552 let ptr = alloc.allocate_zeroed(layout)?.cast();
553 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
556 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
557 /// `x` will be pinned in memory and unable to be moved.
558 #[cfg(not(no_global_oom_handling))]
559 #[unstable(feature = "allocator_api", issue = "32838")]
560 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
563 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
565 A: 'static + ~const Allocator + ~const Destruct,
567 Self::into_pin(Self::new_in(x, alloc))
570 /// Converts a `Box<T>` into a `Box<[T]>`
572 /// This conversion does not allocate on the heap and happens in place.
573 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
574 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
575 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
576 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
577 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
580 /// Consumes the `Box`, returning the wrapped value.
585 /// #![feature(box_into_inner)]
587 /// let c = Box::new(5);
589 /// assert_eq!(Box::into_inner(c), 5);
591 #[unstable(feature = "box_into_inner", issue = "80437")]
592 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
594 pub const fn into_inner(boxed: Self) -> T
596 Self: ~const Destruct,
603 /// Constructs a new boxed slice with uninitialized contents.
608 /// #![feature(new_uninit)]
610 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
612 /// let values = unsafe {
613 /// // Deferred initialization:
614 /// values[0].as_mut_ptr().write(1);
615 /// values[1].as_mut_ptr().write(2);
616 /// values[2].as_mut_ptr().write(3);
618 /// values.assume_init()
621 /// assert_eq!(*values, [1, 2, 3])
623 #[cfg(not(no_global_oom_handling))]
624 #[unstable(feature = "new_uninit", issue = "63291")]
626 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
627 unsafe { RawVec::with_capacity(len).into_box(len) }
630 /// Constructs a new boxed slice with uninitialized contents, with the memory
631 /// being filled with `0` bytes.
633 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
639 /// #![feature(new_uninit)]
641 /// let values = Box::<[u32]>::new_zeroed_slice(3);
642 /// let values = unsafe { values.assume_init() };
644 /// assert_eq!(*values, [0, 0, 0])
647 /// [zeroed]: mem::MaybeUninit::zeroed
648 #[cfg(not(no_global_oom_handling))]
649 #[unstable(feature = "new_uninit", issue = "63291")]
651 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
652 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
655 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
656 /// the allocation fails
661 /// #![feature(allocator_api, new_uninit)]
663 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
664 /// let values = unsafe {
665 /// // Deferred initialization:
666 /// values[0].as_mut_ptr().write(1);
667 /// values[1].as_mut_ptr().write(2);
668 /// values[2].as_mut_ptr().write(3);
669 /// values.assume_init()
672 /// assert_eq!(*values, [1, 2, 3]);
673 /// # Ok::<(), std::alloc::AllocError>(())
675 #[unstable(feature = "allocator_api", issue = "32838")]
677 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
679 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
681 Err(_) => return Err(AllocError),
683 let ptr = Global.allocate(layout)?;
684 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
688 /// Constructs a new boxed slice with uninitialized contents, with the memory
689 /// being filled with `0` bytes. Returns an error if the allocation fails
691 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
697 /// #![feature(allocator_api, new_uninit)]
699 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
700 /// let values = unsafe { values.assume_init() };
702 /// assert_eq!(*values, [0, 0, 0]);
703 /// # Ok::<(), std::alloc::AllocError>(())
706 /// [zeroed]: mem::MaybeUninit::zeroed
707 #[unstable(feature = "allocator_api", issue = "32838")]
709 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
711 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
713 Err(_) => return Err(AllocError),
715 let ptr = Global.allocate_zeroed(layout)?;
716 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
721 impl<T, A: Allocator> Box<[T], A> {
722 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
727 /// #![feature(allocator_api, new_uninit)]
729 /// use std::alloc::System;
731 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
733 /// let values = unsafe {
734 /// // Deferred initialization:
735 /// values[0].as_mut_ptr().write(1);
736 /// values[1].as_mut_ptr().write(2);
737 /// values[2].as_mut_ptr().write(3);
739 /// values.assume_init()
742 /// assert_eq!(*values, [1, 2, 3])
744 #[cfg(not(no_global_oom_handling))]
745 #[unstable(feature = "allocator_api", issue = "32838")]
746 // #[unstable(feature = "new_uninit", issue = "63291")]
748 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
749 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
752 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
753 /// with the memory being filled with `0` bytes.
755 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
761 /// #![feature(allocator_api, new_uninit)]
763 /// use std::alloc::System;
765 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
766 /// let values = unsafe { values.assume_init() };
768 /// assert_eq!(*values, [0, 0, 0])
771 /// [zeroed]: mem::MaybeUninit::zeroed
772 #[cfg(not(no_global_oom_handling))]
773 #[unstable(feature = "allocator_api", issue = "32838")]
774 // #[unstable(feature = "new_uninit", issue = "63291")]
776 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
777 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
781 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
782 /// Converts to `Box<T, A>`.
786 /// As with [`MaybeUninit::assume_init`],
787 /// it is up to the caller to guarantee that the value
788 /// really is in an initialized state.
789 /// Calling this when the content is not yet fully initialized
790 /// causes immediate undefined behavior.
792 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
797 /// #![feature(new_uninit)]
799 /// let mut five = Box::<u32>::new_uninit();
801 /// let five: Box<u32> = unsafe {
802 /// // Deferred initialization:
803 /// five.as_mut_ptr().write(5);
805 /// five.assume_init()
808 /// assert_eq!(*five, 5)
810 #[unstable(feature = "new_uninit", issue = "63291")]
811 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
813 pub const unsafe fn assume_init(self) -> Box<T, A> {
814 let (raw, alloc) = Box::into_raw_with_allocator(self);
815 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
818 /// Writes the value and converts to `Box<T, A>`.
820 /// This method converts the box similarly to [`Box::assume_init`] but
821 /// writes `value` into it before conversion thus guaranteeing safety.
822 /// In some scenarios use of this method may improve performance because
823 /// the compiler may be able to optimize copying from stack.
828 /// #![feature(new_uninit)]
830 /// let big_box = Box::<[usize; 1024]>::new_uninit();
832 /// let mut array = [0; 1024];
833 /// for (i, place) in array.iter_mut().enumerate() {
837 /// // The optimizer may be able to elide this copy, so previous code writes
838 /// // to heap directly.
839 /// let big_box = Box::write(big_box, array);
841 /// for (i, x) in big_box.iter().enumerate() {
842 /// assert_eq!(*x, i);
845 #[unstable(feature = "new_uninit", issue = "63291")]
846 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
848 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
850 (*boxed).write(value);
856 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
857 /// Converts to `Box<[T], A>`.
861 /// As with [`MaybeUninit::assume_init`],
862 /// it is up to the caller to guarantee that the values
863 /// really are in an initialized state.
864 /// Calling this when the content is not yet fully initialized
865 /// causes immediate undefined behavior.
867 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
872 /// #![feature(new_uninit)]
874 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
876 /// let values = unsafe {
877 /// // Deferred initialization:
878 /// values[0].as_mut_ptr().write(1);
879 /// values[1].as_mut_ptr().write(2);
880 /// values[2].as_mut_ptr().write(3);
882 /// values.assume_init()
885 /// assert_eq!(*values, [1, 2, 3])
887 #[unstable(feature = "new_uninit", issue = "63291")]
889 pub unsafe fn assume_init(self) -> Box<[T], A> {
890 let (raw, alloc) = Box::into_raw_with_allocator(self);
891 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
895 impl<T: ?Sized> Box<T> {
896 /// Constructs a box from a raw pointer.
898 /// After calling this function, the raw pointer is owned by the
899 /// resulting `Box`. Specifically, the `Box` destructor will call
900 /// the destructor of `T` and free the allocated memory. For this
901 /// to be safe, the memory must have been allocated in accordance
902 /// with the [memory layout] used by `Box` .
906 /// This function is unsafe because improper use may lead to
907 /// memory problems. For example, a double-free may occur if the
908 /// function is called twice on the same raw pointer.
910 /// The safety conditions are described in the [memory layout] section.
914 /// Recreate a `Box` which was previously converted to a raw pointer
915 /// using [`Box::into_raw`]:
917 /// let x = Box::new(5);
918 /// let ptr = Box::into_raw(x);
919 /// let x = unsafe { Box::from_raw(ptr) };
921 /// Manually create a `Box` from scratch by using the global allocator:
923 /// use std::alloc::{alloc, Layout};
926 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
927 /// // In general .write is required to avoid attempting to destruct
928 /// // the (uninitialized) previous contents of `ptr`, though for this
929 /// // simple example `*ptr = 5` would have worked as well.
931 /// let x = Box::from_raw(ptr);
935 /// [memory layout]: self#memory-layout
936 /// [`Layout`]: crate::Layout
937 #[stable(feature = "box_raw", since = "1.4.0")]
939 pub unsafe fn from_raw(raw: *mut T) -> Self {
940 unsafe { Self::from_raw_in(raw, Global) }
944 impl<T: ?Sized, A: Allocator> Box<T, A> {
945 /// Constructs a box from a raw pointer in the given allocator.
947 /// After calling this function, the raw pointer is owned by the
948 /// resulting `Box`. Specifically, the `Box` destructor will call
949 /// the destructor of `T` and free the allocated memory. For this
950 /// to be safe, the memory must have been allocated in accordance
951 /// with the [memory layout] used by `Box` .
955 /// This function is unsafe because improper use may lead to
956 /// memory problems. For example, a double-free may occur if the
957 /// function is called twice on the same raw pointer.
962 /// Recreate a `Box` which was previously converted to a raw pointer
963 /// using [`Box::into_raw_with_allocator`]:
965 /// #![feature(allocator_api)]
967 /// use std::alloc::System;
969 /// let x = Box::new_in(5, System);
970 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
971 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
973 /// Manually create a `Box` from scratch by using the system allocator:
975 /// #![feature(allocator_api, slice_ptr_get)]
977 /// use std::alloc::{Allocator, Layout, System};
980 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
981 /// // In general .write is required to avoid attempting to destruct
982 /// // the (uninitialized) previous contents of `ptr`, though for this
983 /// // simple example `*ptr = 5` would have worked as well.
985 /// let x = Box::from_raw_in(ptr, System);
987 /// # Ok::<(), std::alloc::AllocError>(())
990 /// [memory layout]: self#memory-layout
991 /// [`Layout`]: crate::Layout
992 #[unstable(feature = "allocator_api", issue = "32838")]
993 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
995 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
996 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
999 /// Consumes the `Box`, returning a wrapped raw pointer.
1001 /// The pointer will be properly aligned and non-null.
1003 /// After calling this function, the caller is responsible for the
1004 /// memory previously managed by the `Box`. In particular, the
1005 /// caller should properly destroy `T` and release the memory, taking
1006 /// into account the [memory layout] used by `Box`. The easiest way to
1007 /// do this is to convert the raw pointer back into a `Box` with the
1008 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1011 /// Note: this is an associated function, which means that you have
1012 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1013 /// is so that there is no conflict with a method on the inner type.
1016 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1017 /// for automatic cleanup:
1019 /// let x = Box::new(String::from("Hello"));
1020 /// let ptr = Box::into_raw(x);
1021 /// let x = unsafe { Box::from_raw(ptr) };
1023 /// Manual cleanup by explicitly running the destructor and deallocating
1026 /// use std::alloc::{dealloc, Layout};
1029 /// let x = Box::new(String::from("Hello"));
1030 /// let p = Box::into_raw(x);
1032 /// ptr::drop_in_place(p);
1033 /// dealloc(p as *mut u8, Layout::new::<String>());
1037 /// [memory layout]: self#memory-layout
1038 #[stable(feature = "box_raw", since = "1.4.0")]
1040 pub fn into_raw(b: Self) -> *mut T {
1041 Self::into_raw_with_allocator(b).0
1044 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1046 /// The pointer will be properly aligned and non-null.
1048 /// After calling this function, the caller is responsible for the
1049 /// memory previously managed by the `Box`. In particular, the
1050 /// caller should properly destroy `T` and release the memory, taking
1051 /// into account the [memory layout] used by `Box`. The easiest way to
1052 /// do this is to convert the raw pointer back into a `Box` with the
1053 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1056 /// Note: this is an associated function, which means that you have
1057 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1058 /// is so that there is no conflict with a method on the inner type.
1061 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1062 /// for automatic cleanup:
1064 /// #![feature(allocator_api)]
1066 /// use std::alloc::System;
1068 /// let x = Box::new_in(String::from("Hello"), System);
1069 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1070 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1072 /// Manual cleanup by explicitly running the destructor and deallocating
1075 /// #![feature(allocator_api)]
1077 /// use std::alloc::{Allocator, Layout, System};
1078 /// use std::ptr::{self, NonNull};
1080 /// let x = Box::new_in(String::from("Hello"), System);
1081 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1083 /// ptr::drop_in_place(ptr);
1084 /// let non_null = NonNull::new_unchecked(ptr);
1085 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1089 /// [memory layout]: self#memory-layout
1090 #[unstable(feature = "allocator_api", issue = "32838")]
1091 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1093 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1094 let (leaked, alloc) = Box::into_unique(b);
1095 (leaked.as_ptr(), alloc)
1099 feature = "ptr_internals",
1101 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1103 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1106 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1107 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1108 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1109 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1110 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1111 // behaves correctly.
1112 let alloc = unsafe { ptr::read(&b.1) };
1113 (Unique::from(Box::leak(b)), alloc)
1116 /// Returns a reference to the underlying allocator.
1118 /// Note: this is an associated function, which means that you have
1119 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1120 /// is so that there is no conflict with a method on the inner type.
1121 #[unstable(feature = "allocator_api", issue = "32838")]
1122 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1124 pub const fn allocator(b: &Self) -> &A {
1128 /// Consumes and leaks the `Box`, returning a mutable reference,
1129 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1130 /// `'a`. If the type has only static references, or none at all, then this
1131 /// may be chosen to be `'static`.
1133 /// This function is mainly useful for data that lives for the remainder of
1134 /// the program's life. Dropping the returned reference will cause a memory
1135 /// leak. If this is not acceptable, the reference should first be wrapped
1136 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1137 /// then be dropped which will properly destroy `T` and release the
1138 /// allocated memory.
1140 /// Note: this is an associated function, which means that you have
1141 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1142 /// is so that there is no conflict with a method on the inner type.
1149 /// let x = Box::new(41);
1150 /// let static_ref: &'static mut usize = Box::leak(x);
1151 /// *static_ref += 1;
1152 /// assert_eq!(*static_ref, 42);
1158 /// let x = vec![1, 2, 3].into_boxed_slice();
1159 /// let static_ref = Box::leak(x);
1160 /// static_ref[0] = 4;
1161 /// assert_eq!(*static_ref, [4, 2, 3]);
1163 #[stable(feature = "box_leak", since = "1.26.0")]
1164 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1166 pub const fn leak<'a>(b: Self) -> &'a mut T
1170 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1173 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1175 /// This conversion does not allocate on the heap and happens in place.
1177 /// This is also available via [`From`].
1178 #[unstable(feature = "box_into_pin", issue = "62370")]
1179 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1180 pub const fn into_pin(boxed: Self) -> Pin<Self>
1184 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1185 // when `T: !Unpin`, so it's safe to pin it directly without any
1186 // additional requirements.
1187 unsafe { Pin::new_unchecked(boxed) }
1191 #[stable(feature = "rust1", since = "1.0.0")]
1192 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1193 fn drop(&mut self) {
1194 // FIXME: Do nothing, drop is currently performed by compiler.
1198 #[cfg(not(no_global_oom_handling))]
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T: Default> Default for Box<T> {
1201 /// Creates a `Box<T>`, with the `Default` value for T.
1202 fn default() -> Self {
1207 #[cfg(not(no_global_oom_handling))]
1208 #[stable(feature = "rust1", since = "1.0.0")]
1209 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1210 impl<T> const Default for Box<[T]> {
1211 fn default() -> Self {
1212 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1217 #[cfg(not(no_global_oom_handling))]
1218 #[stable(feature = "default_box_extra", since = "1.17.0")]
1219 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1220 impl const Default for Box<str> {
1221 fn default() -> Self {
1222 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1223 let ptr: Unique<str> = unsafe {
1224 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1225 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1231 #[cfg(not(no_global_oom_handling))]
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1234 /// Returns a new box with a `clone()` of this box's contents.
1239 /// let x = Box::new(5);
1240 /// let y = x.clone();
1242 /// // The value is the same
1243 /// assert_eq!(x, y);
1245 /// // But they are unique objects
1246 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1249 fn clone(&self) -> Self {
1250 // Pre-allocate memory to allow writing the cloned value directly.
1251 let mut boxed = Self::new_uninit_in(self.1.clone());
1253 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1258 /// Copies `source`'s contents into `self` without creating a new allocation.
1263 /// let x = Box::new(5);
1264 /// let mut y = Box::new(10);
1265 /// let yp: *const i32 = &*y;
1267 /// y.clone_from(&x);
1269 /// // The value is the same
1270 /// assert_eq!(x, y);
1272 /// // And no allocation occurred
1273 /// assert_eq!(yp, &*y);
1276 fn clone_from(&mut self, source: &Self) {
1277 (**self).clone_from(&(**source));
1281 #[cfg(not(no_global_oom_handling))]
1282 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1283 impl Clone for Box<str> {
1284 fn clone(&self) -> Self {
1285 // this makes a copy of the data
1286 let buf: Box<[u8]> = self.as_bytes().into();
1287 unsafe { from_boxed_utf8_unchecked(buf) }
1291 #[stable(feature = "rust1", since = "1.0.0")]
1292 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1294 fn eq(&self, other: &Self) -> bool {
1295 PartialEq::eq(&**self, &**other)
1298 fn ne(&self, other: &Self) -> bool {
1299 PartialEq::ne(&**self, &**other)
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1305 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1306 PartialOrd::partial_cmp(&**self, &**other)
1309 fn lt(&self, other: &Self) -> bool {
1310 PartialOrd::lt(&**self, &**other)
1313 fn le(&self, other: &Self) -> bool {
1314 PartialOrd::le(&**self, &**other)
1317 fn ge(&self, other: &Self) -> bool {
1318 PartialOrd::ge(&**self, &**other)
1321 fn gt(&self, other: &Self) -> bool {
1322 PartialOrd::gt(&**self, &**other)
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1328 fn cmp(&self, other: &Self) -> Ordering {
1329 Ord::cmp(&**self, &**other)
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1335 #[stable(feature = "rust1", since = "1.0.0")]
1336 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1337 fn hash<H: Hasher>(&self, state: &mut H) {
1338 (**self).hash(state);
1342 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1343 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1344 fn finish(&self) -> u64 {
1347 fn write(&mut self, bytes: &[u8]) {
1348 (**self).write(bytes)
1350 fn write_u8(&mut self, i: u8) {
1351 (**self).write_u8(i)
1353 fn write_u16(&mut self, i: u16) {
1354 (**self).write_u16(i)
1356 fn write_u32(&mut self, i: u32) {
1357 (**self).write_u32(i)
1359 fn write_u64(&mut self, i: u64) {
1360 (**self).write_u64(i)
1362 fn write_u128(&mut self, i: u128) {
1363 (**self).write_u128(i)
1365 fn write_usize(&mut self, i: usize) {
1366 (**self).write_usize(i)
1368 fn write_i8(&mut self, i: i8) {
1369 (**self).write_i8(i)
1371 fn write_i16(&mut self, i: i16) {
1372 (**self).write_i16(i)
1374 fn write_i32(&mut self, i: i32) {
1375 (**self).write_i32(i)
1377 fn write_i64(&mut self, i: i64) {
1378 (**self).write_i64(i)
1380 fn write_i128(&mut self, i: i128) {
1381 (**self).write_i128(i)
1383 fn write_isize(&mut self, i: isize) {
1384 (**self).write_isize(i)
1386 fn write_length_prefix(&mut self, len: usize) {
1387 (**self).write_length_prefix(len)
1389 fn write_str(&mut self, s: &str) {
1390 (**self).write_str(s)
1394 #[cfg(not(no_global_oom_handling))]
1395 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1396 impl<T> From<T> for Box<T> {
1397 /// Converts a `T` into a `Box<T>`
1399 /// The conversion allocates on the heap and moves `t`
1400 /// from the stack into it.
1406 /// let boxed = Box::new(5);
1408 /// assert_eq!(Box::from(x), boxed);
1410 fn from(t: T) -> Self {
1415 #[stable(feature = "pin", since = "1.33.0")]
1416 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1417 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1421 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1423 /// This conversion does not allocate on the heap and happens in place.
1424 fn from(boxed: Box<T, A>) -> Self {
1425 Box::into_pin(boxed)
1429 #[cfg(not(no_global_oom_handling))]
1430 #[stable(feature = "box_from_slice", since = "1.17.0")]
1431 impl<T: Copy> From<&[T]> for Box<[T]> {
1432 /// Converts a `&[T]` into a `Box<[T]>`
1434 /// This conversion allocates on the heap
1435 /// and performs a copy of `slice`.
1439 /// // create a &[u8] which will be used to create a Box<[u8]>
1440 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1441 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1443 /// println!("{boxed_slice:?}");
1445 fn from(slice: &[T]) -> Box<[T]> {
1446 let len = slice.len();
1447 let buf = RawVec::with_capacity(len);
1449 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1450 buf.into_box(slice.len()).assume_init()
1455 #[cfg(not(no_global_oom_handling))]
1456 #[stable(feature = "box_from_cow", since = "1.45.0")]
1457 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1458 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1460 /// When `cow` is the `Cow::Borrowed` variant, this
1461 /// conversion allocates on the heap and copies the
1462 /// underlying slice. Otherwise, it will try to reuse the owned
1463 /// `Vec`'s allocation.
1465 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1467 Cow::Borrowed(slice) => Box::from(slice),
1468 Cow::Owned(slice) => Box::from(slice),
1473 #[cfg(not(no_global_oom_handling))]
1474 #[stable(feature = "box_from_slice", since = "1.17.0")]
1475 impl From<&str> for Box<str> {
1476 /// Converts a `&str` into a `Box<str>`
1478 /// This conversion allocates on the heap
1479 /// and performs a copy of `s`.
1484 /// let boxed: Box<str> = Box::from("hello");
1485 /// println!("{boxed}");
1488 fn from(s: &str) -> Box<str> {
1489 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1493 #[cfg(not(no_global_oom_handling))]
1494 #[stable(feature = "box_from_cow", since = "1.45.0")]
1495 impl From<Cow<'_, str>> for Box<str> {
1496 /// Converts a `Cow<'_, str>` into a `Box<str>`
1498 /// When `cow` is the `Cow::Borrowed` variant, this
1499 /// conversion allocates on the heap and copies the
1500 /// underlying `str`. Otherwise, it will try to reuse the owned
1501 /// `String`'s allocation.
1506 /// use std::borrow::Cow;
1508 /// let unboxed = Cow::Borrowed("hello");
1509 /// let boxed: Box<str> = Box::from(unboxed);
1510 /// println!("{boxed}");
1514 /// # use std::borrow::Cow;
1515 /// let unboxed = Cow::Owned("hello".to_string());
1516 /// let boxed: Box<str> = Box::from(unboxed);
1517 /// println!("{boxed}");
1520 fn from(cow: Cow<'_, str>) -> Box<str> {
1522 Cow::Borrowed(s) => Box::from(s),
1523 Cow::Owned(s) => Box::from(s),
1528 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1529 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1530 /// Converts a `Box<str>` into a `Box<[u8]>`
1532 /// This conversion does not allocate on the heap and happens in place.
1536 /// // create a Box<str> which will be used to create a Box<[u8]>
1537 /// let boxed: Box<str> = Box::from("hello");
1538 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1540 /// // create a &[u8] which will be used to create a Box<[u8]>
1541 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1542 /// let boxed_slice = Box::from(slice);
1544 /// assert_eq!(boxed_slice, boxed_str);
1547 fn from(s: Box<str, A>) -> Self {
1548 let (raw, alloc) = Box::into_raw_with_allocator(s);
1549 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1553 #[cfg(not(no_global_oom_handling))]
1554 #[stable(feature = "box_from_array", since = "1.45.0")]
1555 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1556 /// Converts a `[T; N]` into a `Box<[T]>`
1558 /// This conversion moves the array to newly heap-allocated memory.
1563 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1564 /// println!("{boxed:?}");
1566 fn from(array: [T; N]) -> Box<[T]> {
1571 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1572 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1573 type Error = Box<[T]>;
1575 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1577 /// The conversion occurs in-place and does not require a
1578 /// new memory allocation.
1582 /// Returns the old `Box<[T]>` in the `Err` variant if
1583 /// `boxed_slice.len()` does not equal `N`.
1584 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1585 if boxed_slice.len() == N {
1586 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1593 impl<A: Allocator> Box<dyn Any, A> {
1594 /// Attempt to downcast the box to a concrete type.
1599 /// use std::any::Any;
1601 /// fn print_if_string(value: Box<dyn Any>) {
1602 /// if let Ok(string) = value.downcast::<String>() {
1603 /// println!("String ({}): {}", string.len(), string);
1607 /// let my_string = "Hello World".to_string();
1608 /// print_if_string(Box::new(my_string));
1609 /// print_if_string(Box::new(0i8));
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1614 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1617 /// Downcasts the box to a concrete type.
1619 /// For a safe alternative see [`downcast`].
1624 /// #![feature(downcast_unchecked)]
1626 /// use std::any::Any;
1628 /// let x: Box<dyn Any> = Box::new(1_usize);
1631 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1637 /// The contained value must be of type `T`. Calling this method
1638 /// with the incorrect type is *undefined behavior*.
1640 /// [`downcast`]: Self::downcast
1642 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1643 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1644 debug_assert!(self.is::<T>());
1646 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1647 Box::from_raw_in(raw as *mut T, alloc)
1652 impl<A: Allocator> Box<dyn Any + Send, A> {
1653 /// Attempt to downcast the box to a concrete type.
1658 /// use std::any::Any;
1660 /// fn print_if_string(value: Box<dyn Any + Send>) {
1661 /// if let Ok(string) = value.downcast::<String>() {
1662 /// println!("String ({}): {}", string.len(), string);
1666 /// let my_string = "Hello World".to_string();
1667 /// print_if_string(Box::new(my_string));
1668 /// print_if_string(Box::new(0i8));
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1673 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1676 /// Downcasts the box to a concrete type.
1678 /// For a safe alternative see [`downcast`].
1683 /// #![feature(downcast_unchecked)]
1685 /// use std::any::Any;
1687 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1690 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1696 /// The contained value must be of type `T`. Calling this method
1697 /// with the incorrect type is *undefined behavior*.
1699 /// [`downcast`]: Self::downcast
1701 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1702 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1703 debug_assert!(self.is::<T>());
1705 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1706 Box::from_raw_in(raw as *mut T, alloc)
1711 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1712 /// Attempt to downcast the box to a concrete type.
1717 /// use std::any::Any;
1719 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1720 /// if let Ok(string) = value.downcast::<String>() {
1721 /// println!("String ({}): {}", string.len(), string);
1725 /// let my_string = "Hello World".to_string();
1726 /// print_if_string(Box::new(my_string));
1727 /// print_if_string(Box::new(0i8));
1730 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1731 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1732 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1735 /// Downcasts the box to a concrete type.
1737 /// For a safe alternative see [`downcast`].
1742 /// #![feature(downcast_unchecked)]
1744 /// use std::any::Any;
1746 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1749 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1755 /// The contained value must be of type `T`. Calling this method
1756 /// with the incorrect type is *undefined behavior*.
1758 /// [`downcast`]: Self::downcast
1760 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1761 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1762 debug_assert!(self.is::<T>());
1764 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1765 Box::into_raw_with_allocator(self);
1766 Box::from_raw_in(raw as *mut T, alloc)
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1773 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1774 fmt::Display::fmt(&**self, f)
1778 #[stable(feature = "rust1", since = "1.0.0")]
1779 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1780 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1781 fmt::Debug::fmt(&**self, f)
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1787 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1788 // It's not possible to extract the inner Uniq directly from the Box,
1789 // instead we cast it to a *const which aliases the Unique
1790 let ptr: *const T = &**self;
1791 fmt::Pointer::fmt(&ptr, f)
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1797 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1800 fn deref(&self) -> &T {
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1807 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1808 fn deref_mut(&mut self) -> &mut T {
1813 #[unstable(feature = "receiver_trait", issue = "none")]
1814 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1816 #[stable(feature = "rust1", since = "1.0.0")]
1817 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1818 type Item = I::Item;
1819 fn next(&mut self) -> Option<I::Item> {
1822 fn size_hint(&self) -> (usize, Option<usize>) {
1823 (**self).size_hint()
1825 fn nth(&mut self, n: usize) -> Option<I::Item> {
1828 fn last(self) -> Option<I::Item> {
1835 fn last(self) -> Option<Self::Item>;
1838 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1839 type Item = I::Item;
1840 default fn last(self) -> Option<I::Item> {
1842 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1846 self.fold(None, some)
1850 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1851 /// instead of the default.
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1854 fn last(self) -> Option<I::Item> {
1859 #[stable(feature = "rust1", since = "1.0.0")]
1860 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1861 fn next_back(&mut self) -> Option<I::Item> {
1862 (**self).next_back()
1864 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1865 (**self).nth_back(n)
1868 #[stable(feature = "rust1", since = "1.0.0")]
1869 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1870 fn len(&self) -> usize {
1873 fn is_empty(&self) -> bool {
1878 #[stable(feature = "fused", since = "1.26.0")]
1879 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1881 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1882 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1883 type Output = <F as FnOnce<Args>>::Output;
1885 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1886 <F as FnOnce<Args>>::call_once(*self, args)
1890 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1891 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1892 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1893 <F as FnMut<Args>>::call_mut(self, args)
1897 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1898 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1899 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1900 <F as Fn<Args>>::call(self, args)
1904 #[unstable(feature = "coerce_unsized", issue = "27732")]
1905 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1907 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1908 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1910 #[cfg(not(no_global_oom_handling))]
1911 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1912 impl<I> FromIterator<I> for Box<[I]> {
1913 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1914 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1918 #[cfg(not(no_global_oom_handling))]
1919 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1920 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1921 fn clone(&self) -> Self {
1922 let alloc = Box::allocator(self).clone();
1923 self.to_vec_in(alloc).into_boxed_slice()
1926 fn clone_from(&mut self, other: &Self) {
1927 if self.len() == other.len() {
1928 self.clone_from_slice(&other);
1930 *self = other.clone();
1935 #[stable(feature = "box_borrow", since = "1.1.0")]
1936 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1937 fn borrow(&self) -> &T {
1942 #[stable(feature = "box_borrow", since = "1.1.0")]
1943 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1944 fn borrow_mut(&mut self) -> &mut T {
1949 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1950 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1951 fn as_ref(&self) -> &T {
1956 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1957 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1958 fn as_mut(&mut self) -> &mut T {
1965 * We could have chosen not to add this impl, and instead have written a
1966 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1967 * because Box<T> implements Unpin even when T does not, as a result of
1970 * We chose this API instead of the alternative for a few reasons:
1971 * - Logically, it is helpful to understand pinning in regard to the
1972 * memory region being pointed to. For this reason none of the
1973 * standard library pointer types support projecting through a pin
1974 * (Box<T> is the only pointer type in std for which this would be
1976 * - It is in practice very useful to have Box<T> be unconditionally
1977 * Unpin because of trait objects, for which the structural auto
1978 * trait functionality does not apply (e.g., Box<dyn Foo> would
1979 * otherwise not be Unpin).
1981 * Another type with the same semantics as Box but only a conditional
1982 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1983 * could have a method to project a Pin<T> from it.
1985 #[stable(feature = "pin", since = "1.33.0")]
1986 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1987 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
1989 #[unstable(feature = "generator_trait", issue = "43122")]
1990 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1994 type Yield = G::Yield;
1995 type Return = G::Return;
1997 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1998 G::resume(Pin::new(&mut *self), arg)
2002 #[unstable(feature = "generator_trait", issue = "43122")]
2003 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2007 type Yield = G::Yield;
2008 type Return = G::Return;
2010 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2011 G::resume((*self).as_mut(), arg)
2015 #[stable(feature = "futures_api", since = "1.36.0")]
2016 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2020 type Output = F::Output;
2022 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2023 F::poll(Pin::new(&mut *self), cx)
2027 #[unstable(feature = "async_iterator", issue = "79024")]
2028 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2029 type Item = S::Item;
2031 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2032 Pin::new(&mut **self).poll_next(cx)
2035 fn size_hint(&self) -> (usize, Option<usize>) {
2036 (**self).size_hint()