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 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
126 //! [dereferencing]: core::ops::Deref
127 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
128 //! [`Global`]: crate::alloc::Global
129 //! [`Layout`]: crate::alloc::Layout
130 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
131 //! [valid]: ptr#safety
133 #![stable(feature = "rust1", since = "1.0.0")]
137 use core::cmp::Ordering;
138 use core::convert::{From, TryFrom};
140 use core::future::Future;
141 use core::hash::{Hash, Hasher};
142 #[cfg(not(no_global_oom_handling))]
143 use core::iter::FromIterator;
144 use core::iter::{FusedIterator, Iterator};
145 use core::marker::{Unpin, Unsize};
148 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
151 use core::ptr::{self, Unique};
152 use core::stream::Stream;
153 use core::task::{Context, Poll};
155 #[cfg(not(no_global_oom_handling))]
156 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
157 use crate::alloc::{AllocError, Allocator, Global, Layout};
158 #[cfg(not(no_global_oom_handling))]
159 use crate::borrow::Cow;
160 #[cfg(not(no_global_oom_handling))]
161 use crate::raw_vec::RawVec;
162 #[cfg(not(no_global_oom_handling))]
163 use crate::str::from_boxed_utf8_unchecked;
164 #[cfg(not(no_global_oom_handling))]
167 /// A pointer type for heap allocation.
169 /// See the [module-level documentation](../../std/boxed/index.html) for more.
170 #[lang = "owned_box"]
172 #[stable(feature = "rust1", since = "1.0.0")]
175 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
179 /// Allocates memory on the heap and then places `x` into it.
181 /// This doesn't actually allocate if `T` is zero-sized.
186 /// let five = Box::new(5);
188 #[cfg(not(no_global_oom_handling))]
190 #[doc(alias = "alloc")]
191 #[doc(alias = "malloc")]
192 #[stable(feature = "rust1", since = "1.0.0")]
193 pub fn new(x: T) -> Self {
197 /// Constructs a new box with uninitialized contents.
202 /// #![feature(new_uninit)]
204 /// let mut five = Box::<u32>::new_uninit();
206 /// let five = unsafe {
207 /// // Deferred initialization:
208 /// five.as_mut_ptr().write(5);
210 /// five.assume_init()
213 /// assert_eq!(*five, 5)
215 #[cfg(not(no_global_oom_handling))]
216 #[unstable(feature = "new_uninit", issue = "63291")]
218 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
219 Self::new_uninit_in(Global)
222 /// Constructs a new `Box` with uninitialized contents, with the memory
223 /// being filled with `0` bytes.
225 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
231 /// #![feature(new_uninit)]
233 /// let zero = Box::<u32>::new_zeroed();
234 /// let zero = unsafe { zero.assume_init() };
236 /// assert_eq!(*zero, 0)
239 /// [zeroed]: mem::MaybeUninit::zeroed
240 #[cfg(not(no_global_oom_handling))]
242 #[doc(alias = "calloc")]
243 #[unstable(feature = "new_uninit", issue = "63291")]
244 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
245 Self::new_zeroed_in(Global)
248 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
249 /// `x` will be pinned in memory and unable to be moved.
250 #[cfg(not(no_global_oom_handling))]
251 #[stable(feature = "pin", since = "1.33.0")]
253 pub fn pin(x: T) -> Pin<Box<T>> {
257 /// Allocates memory on the heap then places `x` into it,
258 /// returning an error if the allocation fails
260 /// This doesn't actually allocate if `T` is zero-sized.
265 /// #![feature(allocator_api)]
267 /// let five = Box::try_new(5)?;
268 /// # Ok::<(), std::alloc::AllocError>(())
270 #[unstable(feature = "allocator_api", issue = "32838")]
272 pub fn try_new(x: T) -> Result<Self, AllocError> {
273 Self::try_new_in(x, Global)
276 /// Constructs a new box with uninitialized contents on the heap,
277 /// returning an error if the allocation fails
282 /// #![feature(allocator_api, new_uninit)]
284 /// let mut five = Box::<u32>::try_new_uninit()?;
286 /// let five = unsafe {
287 /// // Deferred initialization:
288 /// five.as_mut_ptr().write(5);
290 /// five.assume_init()
293 /// assert_eq!(*five, 5);
294 /// # Ok::<(), std::alloc::AllocError>(())
296 #[unstable(feature = "allocator_api", issue = "32838")]
297 // #[unstable(feature = "new_uninit", issue = "63291")]
299 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
300 Box::try_new_uninit_in(Global)
303 /// Constructs a new `Box` with uninitialized contents, with the memory
304 /// being filled with `0` bytes on the heap
306 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
312 /// #![feature(allocator_api, new_uninit)]
314 /// let zero = Box::<u32>::try_new_zeroed()?;
315 /// let zero = unsafe { zero.assume_init() };
317 /// assert_eq!(*zero, 0);
318 /// # Ok::<(), std::alloc::AllocError>(())
321 /// [zeroed]: mem::MaybeUninit::zeroed
322 #[unstable(feature = "allocator_api", issue = "32838")]
323 // #[unstable(feature = "new_uninit", issue = "63291")]
325 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
326 Box::try_new_zeroed_in(Global)
330 impl<T, A: Allocator> Box<T, A> {
331 /// Allocates memory in the given allocator then places `x` into it.
333 /// This doesn't actually allocate if `T` is zero-sized.
338 /// #![feature(allocator_api)]
340 /// use std::alloc::System;
342 /// let five = Box::new_in(5, System);
344 #[cfg(not(no_global_oom_handling))]
345 #[unstable(feature = "allocator_api", issue = "32838")]
347 pub fn new_in(x: T, alloc: A) -> Self {
348 let mut boxed = Self::new_uninit_in(alloc);
350 boxed.as_mut_ptr().write(x);
355 /// Allocates memory in the given allocator then places `x` into it,
356 /// returning an error if the allocation fails
358 /// This doesn't actually allocate if `T` is zero-sized.
363 /// #![feature(allocator_api)]
365 /// use std::alloc::System;
367 /// let five = Box::try_new_in(5, System)?;
368 /// # Ok::<(), std::alloc::AllocError>(())
370 #[unstable(feature = "allocator_api", issue = "32838")]
372 pub fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError> {
373 let mut boxed = Self::try_new_uninit_in(alloc)?;
375 boxed.as_mut_ptr().write(x);
376 Ok(boxed.assume_init())
380 /// Constructs a new box with uninitialized contents in the provided allocator.
385 /// #![feature(allocator_api, new_uninit)]
387 /// use std::alloc::System;
389 /// let mut five = Box::<u32, _>::new_uninit_in(System);
391 /// let five = unsafe {
392 /// // Deferred initialization:
393 /// five.as_mut_ptr().write(5);
395 /// five.assume_init()
398 /// assert_eq!(*five, 5)
400 #[unstable(feature = "allocator_api", issue = "32838")]
401 #[cfg(not(no_global_oom_handling))]
402 // #[unstable(feature = "new_uninit", issue = "63291")]
403 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
404 let layout = Layout::new::<mem::MaybeUninit<T>>();
405 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
406 // That would make code size bigger.
407 match Box::try_new_uninit_in(alloc) {
409 Err(_) => handle_alloc_error(layout),
413 /// Constructs a new box with uninitialized contents in the provided allocator,
414 /// returning an error if the allocation fails
419 /// #![feature(allocator_api, new_uninit)]
421 /// use std::alloc::System;
423 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
425 /// let five = unsafe {
426 /// // Deferred initialization:
427 /// five.as_mut_ptr().write(5);
429 /// five.assume_init()
432 /// assert_eq!(*five, 5);
433 /// # Ok::<(), std::alloc::AllocError>(())
435 #[unstable(feature = "allocator_api", issue = "32838")]
436 // #[unstable(feature = "new_uninit", issue = "63291")]
437 pub fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> {
438 let layout = Layout::new::<mem::MaybeUninit<T>>();
439 let ptr = alloc.allocate(layout)?.cast();
440 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
443 /// Constructs a new `Box` with uninitialized contents, with the memory
444 /// being filled with `0` bytes in the provided allocator.
446 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
452 /// #![feature(allocator_api, new_uninit)]
454 /// use std::alloc::System;
456 /// let zero = Box::<u32, _>::new_zeroed_in(System);
457 /// let zero = unsafe { zero.assume_init() };
459 /// assert_eq!(*zero, 0)
462 /// [zeroed]: mem::MaybeUninit::zeroed
463 #[unstable(feature = "allocator_api", issue = "32838")]
464 #[cfg(not(no_global_oom_handling))]
465 // #[unstable(feature = "new_uninit", issue = "63291")]
466 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
467 let layout = Layout::new::<mem::MaybeUninit<T>>();
468 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
469 // That would make code size bigger.
470 match Box::try_new_zeroed_in(alloc) {
472 Err(_) => handle_alloc_error(layout),
476 /// Constructs a new `Box` with uninitialized contents, with the memory
477 /// being filled with `0` bytes in the provided allocator,
478 /// returning an error if the allocation fails,
480 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
486 /// #![feature(allocator_api, new_uninit)]
488 /// use std::alloc::System;
490 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
491 /// let zero = unsafe { zero.assume_init() };
493 /// assert_eq!(*zero, 0);
494 /// # Ok::<(), std::alloc::AllocError>(())
497 /// [zeroed]: mem::MaybeUninit::zeroed
498 #[unstable(feature = "allocator_api", issue = "32838")]
499 // #[unstable(feature = "new_uninit", issue = "63291")]
500 pub fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError> {
501 let layout = Layout::new::<mem::MaybeUninit<T>>();
502 let ptr = alloc.allocate_zeroed(layout)?.cast();
503 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
506 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
507 /// `x` will be pinned in memory and unable to be moved.
508 #[cfg(not(no_global_oom_handling))]
509 #[unstable(feature = "allocator_api", issue = "32838")]
511 pub fn pin_in(x: T, alloc: A) -> Pin<Self>
515 Self::new_in(x, alloc).into()
518 /// Converts a `Box<T>` into a `Box<[T]>`
520 /// This conversion does not allocate on the heap and happens in place.
521 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
522 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
523 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
524 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
527 /// Consumes the `Box`, returning the wrapped value.
532 /// #![feature(box_into_inner)]
534 /// let c = Box::new(5);
536 /// assert_eq!(Box::into_inner(c), 5);
538 #[unstable(feature = "box_into_inner", issue = "80437")]
540 pub fn into_inner(boxed: Self) -> T {
546 /// Constructs a new boxed slice with uninitialized contents.
551 /// #![feature(new_uninit)]
553 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
555 /// let values = unsafe {
556 /// // Deferred initialization:
557 /// values[0].as_mut_ptr().write(1);
558 /// values[1].as_mut_ptr().write(2);
559 /// values[2].as_mut_ptr().write(3);
561 /// values.assume_init()
564 /// assert_eq!(*values, [1, 2, 3])
566 #[cfg(not(no_global_oom_handling))]
567 #[unstable(feature = "new_uninit", issue = "63291")]
568 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
569 unsafe { RawVec::with_capacity(len).into_box(len) }
572 /// Constructs a new boxed slice with uninitialized contents, with the memory
573 /// being filled with `0` bytes.
575 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
581 /// #![feature(new_uninit)]
583 /// let values = Box::<[u32]>::new_zeroed_slice(3);
584 /// let values = unsafe { values.assume_init() };
586 /// assert_eq!(*values, [0, 0, 0])
589 /// [zeroed]: mem::MaybeUninit::zeroed
590 #[cfg(not(no_global_oom_handling))]
591 #[unstable(feature = "new_uninit", issue = "63291")]
592 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
593 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
597 impl<T, A: Allocator> Box<[T], A> {
598 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
603 /// #![feature(allocator_api, new_uninit)]
605 /// use std::alloc::System;
607 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
609 /// let values = unsafe {
610 /// // Deferred initialization:
611 /// values[0].as_mut_ptr().write(1);
612 /// values[1].as_mut_ptr().write(2);
613 /// values[2].as_mut_ptr().write(3);
615 /// values.assume_init()
618 /// assert_eq!(*values, [1, 2, 3])
620 #[cfg(not(no_global_oom_handling))]
621 #[unstable(feature = "allocator_api", issue = "32838")]
622 // #[unstable(feature = "new_uninit", issue = "63291")]
623 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
624 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
627 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
628 /// with the memory being filled with `0` bytes.
630 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
636 /// #![feature(allocator_api, new_uninit)]
638 /// use std::alloc::System;
640 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
641 /// let values = unsafe { values.assume_init() };
643 /// assert_eq!(*values, [0, 0, 0])
646 /// [zeroed]: mem::MaybeUninit::zeroed
647 #[cfg(not(no_global_oom_handling))]
648 #[unstable(feature = "allocator_api", issue = "32838")]
649 // #[unstable(feature = "new_uninit", issue = "63291")]
650 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
651 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
655 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
656 /// Converts to `Box<T, A>`.
660 /// As with [`MaybeUninit::assume_init`],
661 /// it is up to the caller to guarantee that the value
662 /// really is in an initialized state.
663 /// Calling this when the content is not yet fully initialized
664 /// causes immediate undefined behavior.
666 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
671 /// #![feature(new_uninit)]
673 /// let mut five = Box::<u32>::new_uninit();
675 /// let five: Box<u32> = unsafe {
676 /// // Deferred initialization:
677 /// five.as_mut_ptr().write(5);
679 /// five.assume_init()
682 /// assert_eq!(*five, 5)
684 #[unstable(feature = "new_uninit", issue = "63291")]
686 pub unsafe fn assume_init(self) -> Box<T, A> {
687 let (raw, alloc) = Box::into_raw_with_allocator(self);
688 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
692 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
693 /// Converts to `Box<[T], A>`.
697 /// As with [`MaybeUninit::assume_init`],
698 /// it is up to the caller to guarantee that the values
699 /// really are in an initialized state.
700 /// Calling this when the content is not yet fully initialized
701 /// causes immediate undefined behavior.
703 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
708 /// #![feature(new_uninit)]
710 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
712 /// let values = unsafe {
713 /// // Deferred initialization:
714 /// values[0].as_mut_ptr().write(1);
715 /// values[1].as_mut_ptr().write(2);
716 /// values[2].as_mut_ptr().write(3);
718 /// values.assume_init()
721 /// assert_eq!(*values, [1, 2, 3])
723 #[unstable(feature = "new_uninit", issue = "63291")]
725 pub unsafe fn assume_init(self) -> Box<[T], A> {
726 let (raw, alloc) = Box::into_raw_with_allocator(self);
727 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
731 impl<T: ?Sized> Box<T> {
732 /// Constructs a box from a raw pointer.
734 /// After calling this function, the raw pointer is owned by the
735 /// resulting `Box`. Specifically, the `Box` destructor will call
736 /// the destructor of `T` and free the allocated memory. For this
737 /// to be safe, the memory must have been allocated in accordance
738 /// with the [memory layout] used by `Box` .
742 /// This function is unsafe because improper use may lead to
743 /// memory problems. For example, a double-free may occur if the
744 /// function is called twice on the same raw pointer.
746 /// The safety conditions are described in the [memory layout] section.
750 /// Recreate a `Box` which was previously converted to a raw pointer
751 /// using [`Box::into_raw`]:
753 /// let x = Box::new(5);
754 /// let ptr = Box::into_raw(x);
755 /// let x = unsafe { Box::from_raw(ptr) };
757 /// Manually create a `Box` from scratch by using the global allocator:
759 /// use std::alloc::{alloc, Layout};
762 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
763 /// // In general .write is required to avoid attempting to destruct
764 /// // the (uninitialized) previous contents of `ptr`, though for this
765 /// // simple example `*ptr = 5` would have worked as well.
767 /// let x = Box::from_raw(ptr);
771 /// [memory layout]: self#memory-layout
772 /// [`Layout`]: crate::Layout
773 #[stable(feature = "box_raw", since = "1.4.0")]
775 pub unsafe fn from_raw(raw: *mut T) -> Self {
776 unsafe { Self::from_raw_in(raw, Global) }
780 impl<T: ?Sized, A: Allocator> Box<T, A> {
781 /// Constructs a box from a raw pointer in the given allocator.
783 /// After calling this function, the raw pointer is owned by the
784 /// resulting `Box`. Specifically, the `Box` destructor will call
785 /// the destructor of `T` and free the allocated memory. For this
786 /// to be safe, the memory must have been allocated in accordance
787 /// with the [memory layout] used by `Box` .
791 /// This function is unsafe because improper use may lead to
792 /// memory problems. For example, a double-free may occur if the
793 /// function is called twice on the same raw pointer.
798 /// Recreate a `Box` which was previously converted to a raw pointer
799 /// using [`Box::into_raw_with_allocator`]:
801 /// #![feature(allocator_api)]
803 /// use std::alloc::System;
805 /// let x = Box::new_in(5, System);
806 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
807 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
809 /// Manually create a `Box` from scratch by using the system allocator:
811 /// #![feature(allocator_api, slice_ptr_get)]
813 /// use std::alloc::{Allocator, Layout, System};
816 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
817 /// // In general .write is required to avoid attempting to destruct
818 /// // the (uninitialized) previous contents of `ptr`, though for this
819 /// // simple example `*ptr = 5` would have worked as well.
821 /// let x = Box::from_raw_in(ptr, System);
823 /// # Ok::<(), std::alloc::AllocError>(())
826 /// [memory layout]: self#memory-layout
827 /// [`Layout`]: crate::Layout
828 #[unstable(feature = "allocator_api", issue = "32838")]
830 pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
831 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
834 /// Consumes the `Box`, returning a wrapped raw pointer.
836 /// The pointer will be properly aligned and non-null.
838 /// After calling this function, the caller is responsible for the
839 /// memory previously managed by the `Box`. In particular, the
840 /// caller should properly destroy `T` and release the memory, taking
841 /// into account the [memory layout] used by `Box`. The easiest way to
842 /// do this is to convert the raw pointer back into a `Box` with the
843 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
846 /// Note: this is an associated function, which means that you have
847 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
848 /// is so that there is no conflict with a method on the inner type.
851 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
852 /// for automatic cleanup:
854 /// let x = Box::new(String::from("Hello"));
855 /// let ptr = Box::into_raw(x);
856 /// let x = unsafe { Box::from_raw(ptr) };
858 /// Manual cleanup by explicitly running the destructor and deallocating
861 /// use std::alloc::{dealloc, Layout};
864 /// let x = Box::new(String::from("Hello"));
865 /// let p = Box::into_raw(x);
867 /// ptr::drop_in_place(p);
868 /// dealloc(p as *mut u8, Layout::new::<String>());
872 /// [memory layout]: self#memory-layout
873 #[stable(feature = "box_raw", since = "1.4.0")]
875 pub fn into_raw(b: Self) -> *mut T {
876 Self::into_raw_with_allocator(b).0
879 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
881 /// The pointer will be properly aligned and non-null.
883 /// After calling this function, the caller is responsible for the
884 /// memory previously managed by the `Box`. In particular, the
885 /// caller should properly destroy `T` and release the memory, taking
886 /// into account the [memory layout] used by `Box`. The easiest way to
887 /// do this is to convert the raw pointer back into a `Box` with the
888 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
891 /// Note: this is an associated function, which means that you have
892 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
893 /// is so that there is no conflict with a method on the inner type.
896 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
897 /// for automatic cleanup:
899 /// #![feature(allocator_api)]
901 /// use std::alloc::System;
903 /// let x = Box::new_in(String::from("Hello"), System);
904 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
905 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
907 /// Manual cleanup by explicitly running the destructor and deallocating
910 /// #![feature(allocator_api)]
912 /// use std::alloc::{Allocator, Layout, System};
913 /// use std::ptr::{self, NonNull};
915 /// let x = Box::new_in(String::from("Hello"), System);
916 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
918 /// ptr::drop_in_place(ptr);
919 /// let non_null = NonNull::new_unchecked(ptr);
920 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
924 /// [memory layout]: self#memory-layout
925 #[unstable(feature = "allocator_api", issue = "32838")]
927 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
928 let (leaked, alloc) = Box::into_unique(b);
929 (leaked.as_ptr(), alloc)
933 feature = "ptr_internals",
935 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
939 pub fn into_unique(b: Self) -> (Unique<T>, A) {
940 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
941 // raw pointer for the type system. Turning it directly into a raw pointer would not be
942 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
943 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
944 // behaves correctly.
945 let alloc = unsafe { ptr::read(&b.1) };
946 (Unique::from(Box::leak(b)), alloc)
949 /// Returns a reference to the underlying allocator.
951 /// Note: this is an associated function, which means that you have
952 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
953 /// is so that there is no conflict with a method on the inner type.
954 #[unstable(feature = "allocator_api", issue = "32838")]
956 pub fn allocator(b: &Self) -> &A {
960 /// Consumes and leaks the `Box`, returning a mutable reference,
961 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
962 /// `'a`. If the type has only static references, or none at all, then this
963 /// may be chosen to be `'static`.
965 /// This function is mainly useful for data that lives for the remainder of
966 /// the program's life. Dropping the returned reference will cause a memory
967 /// leak. If this is not acceptable, the reference should first be wrapped
968 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
969 /// then be dropped which will properly destroy `T` and release the
970 /// allocated memory.
972 /// Note: this is an associated function, which means that you have
973 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
974 /// is so that there is no conflict with a method on the inner type.
981 /// let x = Box::new(41);
982 /// let static_ref: &'static mut usize = Box::leak(x);
983 /// *static_ref += 1;
984 /// assert_eq!(*static_ref, 42);
990 /// let x = vec![1, 2, 3].into_boxed_slice();
991 /// let static_ref = Box::leak(x);
992 /// static_ref[0] = 4;
993 /// assert_eq!(*static_ref, [4, 2, 3]);
995 #[stable(feature = "box_leak", since = "1.26.0")]
997 pub fn leak<'a>(b: Self) -> &'a mut T
1001 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1004 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1006 /// This conversion does not allocate on the heap and happens in place.
1008 /// This is also available via [`From`].
1009 #[unstable(feature = "box_into_pin", issue = "62370")]
1010 pub fn into_pin(boxed: Self) -> Pin<Self>
1014 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1015 // when `T: !Unpin`, so it's safe to pin it directly without any
1016 // additional requirements.
1017 unsafe { Pin::new_unchecked(boxed) }
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1023 fn drop(&mut self) {
1024 // FIXME: Do nothing, drop is currently performed by compiler.
1028 #[stable(feature = "rust1", since = "1.0.0")]
1029 impl<T: Default> Default for Box<T> {
1030 /// Creates a `Box<T>`, with the `Default` value for T.
1031 fn default() -> Self {
1036 #[cfg(not(no_global_oom_handling))]
1037 #[stable(feature = "rust1", since = "1.0.0")]
1038 impl<T> Default for Box<[T]> {
1039 fn default() -> Self {
1040 Box::<[T; 0]>::new([])
1044 #[cfg(not(no_global_oom_handling))]
1045 #[stable(feature = "default_box_extra", since = "1.17.0")]
1046 impl Default for Box<str> {
1047 fn default() -> Self {
1048 unsafe { from_boxed_utf8_unchecked(Default::default()) }
1052 #[cfg(not(no_global_oom_handling))]
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1055 /// Returns a new box with a `clone()` of this box's contents.
1060 /// let x = Box::new(5);
1061 /// let y = x.clone();
1063 /// // The value is the same
1064 /// assert_eq!(x, y);
1066 /// // But they are unique objects
1067 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1070 fn clone(&self) -> Self {
1071 // Pre-allocate memory to allow writing the cloned value directly.
1072 let mut boxed = Self::new_uninit_in(self.1.clone());
1074 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1079 /// Copies `source`'s contents into `self` without creating a new allocation.
1084 /// let x = Box::new(5);
1085 /// let mut y = Box::new(10);
1086 /// let yp: *const i32 = &*y;
1088 /// y.clone_from(&x);
1090 /// // The value is the same
1091 /// assert_eq!(x, y);
1093 /// // And no allocation occurred
1094 /// assert_eq!(yp, &*y);
1097 fn clone_from(&mut self, source: &Self) {
1098 (**self).clone_from(&(**source));
1102 #[cfg(not(no_global_oom_handling))]
1103 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1104 impl Clone for Box<str> {
1105 fn clone(&self) -> Self {
1106 // this makes a copy of the data
1107 let buf: Box<[u8]> = self.as_bytes().into();
1108 unsafe { from_boxed_utf8_unchecked(buf) }
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1115 fn eq(&self, other: &Self) -> bool {
1116 PartialEq::eq(&**self, &**other)
1119 fn ne(&self, other: &Self) -> bool {
1120 PartialEq::ne(&**self, &**other)
1123 #[stable(feature = "rust1", since = "1.0.0")]
1124 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1126 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1127 PartialOrd::partial_cmp(&**self, &**other)
1130 fn lt(&self, other: &Self) -> bool {
1131 PartialOrd::lt(&**self, &**other)
1134 fn le(&self, other: &Self) -> bool {
1135 PartialOrd::le(&**self, &**other)
1138 fn ge(&self, other: &Self) -> bool {
1139 PartialOrd::ge(&**self, &**other)
1142 fn gt(&self, other: &Self) -> bool {
1143 PartialOrd::gt(&**self, &**other)
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1149 fn cmp(&self, other: &Self) -> Ordering {
1150 Ord::cmp(&**self, &**other)
1153 #[stable(feature = "rust1", since = "1.0.0")]
1154 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1156 #[stable(feature = "rust1", since = "1.0.0")]
1157 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1158 fn hash<H: Hasher>(&self, state: &mut H) {
1159 (**self).hash(state);
1163 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1164 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1165 fn finish(&self) -> u64 {
1168 fn write(&mut self, bytes: &[u8]) {
1169 (**self).write(bytes)
1171 fn write_u8(&mut self, i: u8) {
1172 (**self).write_u8(i)
1174 fn write_u16(&mut self, i: u16) {
1175 (**self).write_u16(i)
1177 fn write_u32(&mut self, i: u32) {
1178 (**self).write_u32(i)
1180 fn write_u64(&mut self, i: u64) {
1181 (**self).write_u64(i)
1183 fn write_u128(&mut self, i: u128) {
1184 (**self).write_u128(i)
1186 fn write_usize(&mut self, i: usize) {
1187 (**self).write_usize(i)
1189 fn write_i8(&mut self, i: i8) {
1190 (**self).write_i8(i)
1192 fn write_i16(&mut self, i: i16) {
1193 (**self).write_i16(i)
1195 fn write_i32(&mut self, i: i32) {
1196 (**self).write_i32(i)
1198 fn write_i64(&mut self, i: i64) {
1199 (**self).write_i64(i)
1201 fn write_i128(&mut self, i: i128) {
1202 (**self).write_i128(i)
1204 fn write_isize(&mut self, i: isize) {
1205 (**self).write_isize(i)
1209 #[cfg(not(no_global_oom_handling))]
1210 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1211 impl<T> From<T> for Box<T> {
1212 /// Converts a `T` into a `Box<T>`
1214 /// The conversion allocates on the heap and moves `t`
1215 /// from the stack into it.
1220 /// let boxed = Box::new(5);
1222 /// assert_eq!(Box::from(x), boxed);
1224 fn from(t: T) -> Self {
1229 #[stable(feature = "pin", since = "1.33.0")]
1230 impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
1234 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1236 /// This conversion does not allocate on the heap and happens in place.
1237 fn from(boxed: Box<T, A>) -> Self {
1238 Box::into_pin(boxed)
1242 #[cfg(not(no_global_oom_handling))]
1243 #[stable(feature = "box_from_slice", since = "1.17.0")]
1244 impl<T: Copy> From<&[T]> for Box<[T]> {
1245 /// Converts a `&[T]` into a `Box<[T]>`
1247 /// This conversion allocates on the heap
1248 /// and performs a copy of `slice`.
1252 /// // create a &[u8] which will be used to create a Box<[u8]>
1253 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1254 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1256 /// println!("{:?}", boxed_slice);
1258 fn from(slice: &[T]) -> Box<[T]> {
1259 let len = slice.len();
1260 let buf = RawVec::with_capacity(len);
1262 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1263 buf.into_box(slice.len()).assume_init()
1268 #[cfg(not(no_global_oom_handling))]
1269 #[stable(feature = "box_from_cow", since = "1.45.0")]
1270 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1272 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1274 Cow::Borrowed(slice) => Box::from(slice),
1275 Cow::Owned(slice) => Box::from(slice),
1280 #[cfg(not(no_global_oom_handling))]
1281 #[stable(feature = "box_from_slice", since = "1.17.0")]
1282 impl From<&str> for Box<str> {
1283 /// Converts a `&str` into a `Box<str>`
1285 /// This conversion allocates on the heap
1286 /// and performs a copy of `s`.
1290 /// let boxed: Box<str> = Box::from("hello");
1291 /// println!("{}", boxed);
1294 fn from(s: &str) -> Box<str> {
1295 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1299 #[cfg(not(no_global_oom_handling))]
1300 #[stable(feature = "box_from_cow", since = "1.45.0")]
1301 impl From<Cow<'_, str>> for Box<str> {
1303 fn from(cow: Cow<'_, str>) -> Box<str> {
1305 Cow::Borrowed(s) => Box::from(s),
1306 Cow::Owned(s) => Box::from(s),
1311 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1312 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1313 /// Converts a `Box<str>` into a `Box<[u8]>`
1315 /// This conversion does not allocate on the heap and happens in place.
1319 /// // create a Box<str> which will be used to create a Box<[u8]>
1320 /// let boxed: Box<str> = Box::from("hello");
1321 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1323 /// // create a &[u8] which will be used to create a Box<[u8]>
1324 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1325 /// let boxed_slice = Box::from(slice);
1327 /// assert_eq!(boxed_slice, boxed_str);
1330 fn from(s: Box<str, A>) -> Self {
1331 let (raw, alloc) = Box::into_raw_with_allocator(s);
1332 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1336 #[stable(feature = "box_from_array", since = "1.45.0")]
1337 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1338 /// Converts a `[T; N]` into a `Box<[T]>`
1340 /// This conversion moves the array to newly heap-allocated memory.
1344 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1345 /// println!("{:?}", boxed);
1347 fn from(array: [T; N]) -> Box<[T]> {
1352 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1353 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1354 type Error = Box<[T]>;
1356 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1357 if boxed_slice.len() == N {
1358 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1365 impl<A: Allocator> Box<dyn Any, A> {
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 /// Attempt to downcast the box to a concrete type.
1373 /// use std::any::Any;
1375 /// fn print_if_string(value: Box<dyn Any>) {
1376 /// if let Ok(string) = value.downcast::<String>() {
1377 /// println!("String ({}): {}", string.len(), string);
1381 /// let my_string = "Hello World".to_string();
1382 /// print_if_string(Box::new(my_string));
1383 /// print_if_string(Box::new(0i8));
1385 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1388 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1389 Ok(Box::from_raw_in(raw as *mut T, alloc))
1397 impl<A: Allocator> Box<dyn Any + Send, A> {
1399 #[stable(feature = "rust1", since = "1.0.0")]
1400 /// Attempt to downcast the box to a concrete type.
1405 /// use std::any::Any;
1407 /// fn print_if_string(value: Box<dyn Any + Send>) {
1408 /// if let Ok(string) = value.downcast::<String>() {
1409 /// println!("String ({}): {}", string.len(), string);
1413 /// let my_string = "Hello World".to_string();
1414 /// print_if_string(Box::new(my_string));
1415 /// print_if_string(Box::new(0i8));
1417 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1420 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1421 Ok(Box::from_raw_in(raw as *mut T, alloc))
1429 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1431 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1432 /// Attempt to downcast the box to a concrete type.
1437 /// use std::any::Any;
1439 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1440 /// if let Ok(string) = value.downcast::<String>() {
1441 /// println!("String ({}): {}", string.len(), string);
1445 /// let my_string = "Hello World".to_string();
1446 /// print_if_string(Box::new(my_string));
1447 /// print_if_string(Box::new(0i8));
1449 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1452 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1453 Box::into_raw_with_allocator(self);
1454 Ok(Box::from_raw_in(raw as *mut T, alloc))
1462 #[stable(feature = "rust1", since = "1.0.0")]
1463 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1464 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1465 fmt::Display::fmt(&**self, f)
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1471 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1472 fmt::Debug::fmt(&**self, f)
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1478 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1479 // It's not possible to extract the inner Uniq directly from the Box,
1480 // instead we cast it to a *const which aliases the Unique
1481 let ptr: *const T = &**self;
1482 fmt::Pointer::fmt(&ptr, f)
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
1490 fn deref(&self) -> &T {
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
1497 fn deref_mut(&mut self) -> &mut T {
1502 #[unstable(feature = "receiver_trait", issue = "none")]
1503 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1507 type Item = I::Item;
1508 fn next(&mut self) -> Option<I::Item> {
1511 fn size_hint(&self) -> (usize, Option<usize>) {
1512 (**self).size_hint()
1514 fn nth(&mut self, n: usize) -> Option<I::Item> {
1517 fn last(self) -> Option<I::Item> {
1524 fn last(self) -> Option<Self::Item>;
1527 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1528 type Item = I::Item;
1529 default fn last(self) -> Option<I::Item> {
1531 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1535 self.fold(None, some)
1539 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1540 /// instead of the default.
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1543 fn last(self) -> Option<I::Item> {
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1550 fn next_back(&mut self) -> Option<I::Item> {
1551 (**self).next_back()
1553 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1554 (**self).nth_back(n)
1557 #[stable(feature = "rust1", since = "1.0.0")]
1558 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1559 fn len(&self) -> usize {
1562 fn is_empty(&self) -> bool {
1567 #[stable(feature = "fused", since = "1.26.0")]
1568 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1570 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1571 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1572 type Output = <F as FnOnce<Args>>::Output;
1574 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1575 <F as FnOnce<Args>>::call_once(*self, args)
1579 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1580 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1581 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1582 <F as FnMut<Args>>::call_mut(self, args)
1586 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1587 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1588 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1589 <F as Fn<Args>>::call(self, args)
1593 #[unstable(feature = "coerce_unsized", issue = "27732")]
1594 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1596 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1597 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1599 #[cfg(not(no_global_oom_handling))]
1600 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1601 impl<I> FromIterator<I> for Box<[I]> {
1602 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1603 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1607 #[cfg(not(no_global_oom_handling))]
1608 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1609 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1610 fn clone(&self) -> Self {
1611 let alloc = Box::allocator(self).clone();
1612 self.to_vec_in(alloc).into_boxed_slice()
1615 fn clone_from(&mut self, other: &Self) {
1616 if self.len() == other.len() {
1617 self.clone_from_slice(&other);
1619 *self = other.clone();
1624 #[stable(feature = "box_borrow", since = "1.1.0")]
1625 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1626 fn borrow(&self) -> &T {
1631 #[stable(feature = "box_borrow", since = "1.1.0")]
1632 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1633 fn borrow_mut(&mut self) -> &mut T {
1638 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1639 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1640 fn as_ref(&self) -> &T {
1645 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1646 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1647 fn as_mut(&mut self) -> &mut T {
1654 * We could have chosen not to add this impl, and instead have written a
1655 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1656 * because Box<T> implements Unpin even when T does not, as a result of
1659 * We chose this API instead of the alternative for a few reasons:
1660 * - Logically, it is helpful to understand pinning in regard to the
1661 * memory region being pointed to. For this reason none of the
1662 * standard library pointer types support projecting through a pin
1663 * (Box<T> is the only pointer type in std for which this would be
1665 * - It is in practice very useful to have Box<T> be unconditionally
1666 * Unpin because of trait objects, for which the structural auto
1667 * trait functionality does not apply (e.g., Box<dyn Foo> would
1668 * otherwise not be Unpin).
1670 * Another type with the same semantics as Box but only a conditional
1671 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1672 * could have a method to project a Pin<T> from it.
1674 #[stable(feature = "pin", since = "1.33.0")]
1675 impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
1677 #[unstable(feature = "generator_trait", issue = "43122")]
1678 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
1682 type Yield = G::Yield;
1683 type Return = G::Return;
1685 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1686 G::resume(Pin::new(&mut *self), arg)
1690 #[unstable(feature = "generator_trait", issue = "43122")]
1691 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
1695 type Yield = G::Yield;
1696 type Return = G::Return;
1698 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1699 G::resume((*self).as_mut(), arg)
1703 #[stable(feature = "futures_api", since = "1.36.0")]
1704 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
1708 type Output = F::Output;
1710 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1711 F::poll(Pin::new(&mut *self), cx)
1715 #[unstable(feature = "async_stream", issue = "79024")]
1716 impl<S: ?Sized + Stream + Unpin> Stream for Box<S> {
1717 type Item = S::Item;
1719 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
1720 Pin::new(&mut **self).poll_next(cx)
1723 fn size_hint(&self) -> (usize, Option<usize>) {
1724 (**self).size_hint()