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.
9 //! Move a value from the stack to the heap by creating a [`Box`]:
13 //! let boxed: Box<u8> = Box::new(val);
16 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
19 //! let boxed: Box<u8> = Box::new(5);
20 //! let val: u8 = *boxed;
23 //! Creating a recursive data structure:
28 //! Cons(T, Box<List<T>>),
32 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
33 //! println!("{:?}", list);
36 //! This will print `Cons(1, Cons(2, Nil))`.
38 //! Recursive structures must be boxed, because if the definition of `Cons`
41 //! ```compile_fail,E0072
47 //! It wouldn't work. This is because the size of a `List` depends on how many
48 //! elements are in the list, and so we don't know how much memory to allocate
49 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
50 //! big `Cons` needs to be.
54 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
55 //! its allocation. It is valid to convert both ways between a [`Box`] and a
56 //! raw pointer allocated with the [`Global`] allocator, given that the
57 //! [`Layout`] used with the allocator is correct for the type. More precisely,
58 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
59 //! with `Layout::for_value(&*value)` may be converted into a box using
60 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
61 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
62 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
64 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
65 //! as a single pointer and is also ABI-compatible with C pointers
66 //! (i.e. the C type `T*`). This means that if you have extern "C"
67 //! Rust functions that will be called from C, you can define those
68 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
69 //! type on the C side. As an example, consider this C header which
70 //! declares functions that create and destroy some kind of `Foo`
76 //! /* Returns ownership to the caller */
77 //! struct Foo* foo_new(void);
79 //! /* Takes ownership from the caller; no-op when invoked with NULL */
80 //! void foo_delete(struct Foo*);
83 //! These two functions might be implemented in Rust as follows. Here, the
84 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
85 //! the ownership constraints. Note also that the nullable argument to
86 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
94 //! pub extern "C" fn foo_new() -> Box<Foo> {
99 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
102 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
103 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
104 //! and expect things to work. `Box<T>` values will always be fully aligned,
105 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
106 //! free the value with the global allocator. In general, the best practice
107 //! is to only use `Box<T>` for pointers that originated from the global
110 //! **Important.** At least at present, you should avoid using
111 //! `Box<T>` types for functions that are defined in C but invoked
112 //! from Rust. In those cases, you should directly mirror the C types
113 //! as closely as possible. Using types like `Box<T>` where the C
114 //! definition is just using `T*` can lead to undefined behavior, as
115 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
117 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
118 //! [dereferencing]: ../../std/ops/trait.Deref.html
119 //! [`Box`]: struct.Box.html
120 //! [`Box<T>`]: struct.Box.html
121 //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
122 //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
123 //! [`Global`]: ../alloc/struct.Global.html
124 //! [`Layout`]: ../alloc/struct.Layout.html
125 //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value
127 #![stable(feature = "rust1", since = "1.0.0")]
130 use core
::array
::LengthAtMost32
;
132 use core
::cmp
::Ordering
;
133 use core
::convert
::{From, TryFrom}
;
135 use core
::future
::Future
;
136 use core
::hash
::{Hash, Hasher}
;
137 use core
::iter
::{Iterator, FromIterator, FusedIterator}
;
138 use core
::marker
::{Unpin, Unsize}
;
142 CoerceUnsized
, DispatchFromDyn
, Deref
, DerefMut
, Receiver
, Generator
, GeneratorState
144 use core
::ptr
::{self, NonNull, Unique}
;
146 use core
::task
::{Context, Poll}
;
148 use crate::alloc
::{self, Global, Alloc}
;
150 use crate::raw_vec
::RawVec
;
151 use crate::str::from_boxed_utf8_unchecked
;
153 /// A pointer type for heap allocation.
155 /// See the [module-level documentation](../../std/boxed/index.html) for more.
156 #[lang = "owned_box"]
158 #[stable(feature = "rust1", since = "1.0.0")]
159 pub struct Box
<T
: ?Sized
>(Unique
<T
>);
162 /// Allocates memory on the heap and then places `x` into it.
164 /// This doesn't actually allocate if `T` is zero-sized.
169 /// let five = Box::new(5);
171 #[stable(feature = "rust1", since = "1.0.0")]
173 pub fn new(x
: T
) -> Box
<T
> {
177 /// Constructs a new box with uninitialized contents.
182 /// #![feature(new_uninit)]
184 /// let mut five = Box::<u32>::new_uninit();
186 /// let five = unsafe {
187 /// // Deferred initialization:
188 /// five.as_mut_ptr().write(5);
190 /// five.assume_init()
193 /// assert_eq!(*five, 5)
195 #[unstable(feature = "new_uninit", issue = "63291")]
196 pub fn new_uninit() -> Box
<mem
::MaybeUninit
<T
>> {
197 let layout
= alloc
::Layout
::new
::<mem
::MaybeUninit
<T
>>();
198 if layout
.size() == 0 {
199 return Box(NonNull
::dangling().into())
203 .unwrap_or_else(|_
| alloc
::handle_alloc_error(layout
))
205 Box(ptr
.cast().into())
208 /// Constructs a new `Box` with uninitialized contents, with the memory
209 /// being filled with `0` bytes.
211 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
217 /// #![feature(new_uninit)]
219 /// let zero = Box::<u32>::new_zeroed();
220 /// let zero = unsafe { zero.assume_init() };
222 /// assert_eq!(*zero, 0)
225 /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
226 #[unstable(feature = "new_uninit", issue = "63291")]
227 pub fn new_zeroed() -> Box
<mem
::MaybeUninit
<T
>> {
229 let mut uninit
= Self::new_uninit();
230 ptr
::write_bytes
::<T
>(uninit
.as_mut_ptr(), 0, 1);
235 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
236 /// `x` will be pinned in memory and unable to be moved.
237 #[stable(feature = "pin", since = "1.33.0")]
239 pub fn pin(x
: T
) -> Pin
<Box
<T
>> {
245 /// Constructs a new boxed slice with uninitialized contents.
250 /// #![feature(new_uninit)]
252 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
254 /// let values = unsafe {
255 /// // Deferred initialization:
256 /// values[0].as_mut_ptr().write(1);
257 /// values[1].as_mut_ptr().write(2);
258 /// values[2].as_mut_ptr().write(3);
260 /// values.assume_init()
263 /// assert_eq!(*values, [1, 2, 3])
265 #[unstable(feature = "new_uninit", issue = "63291")]
266 pub fn new_uninit_slice(len
: usize) -> Box
<[mem
::MaybeUninit
<T
>]> {
267 let layout
= alloc
::Layout
::array
::<mem
::MaybeUninit
<T
>>(len
).unwrap();
268 let ptr
= if layout
.size() == 0 {
273 .unwrap_or_else(|_
| alloc
::handle_alloc_error(layout
))
277 let slice
= unsafe { slice::from_raw_parts_mut(ptr.as_ptr(), len) }
;
278 Box(Unique
::from(slice
))
282 impl<T
> Box
<mem
::MaybeUninit
<T
>> {
283 /// Converts to `Box<T>`.
287 /// As with [`MaybeUninit::assume_init`],
288 /// it is up to the caller to guarantee that the value
289 /// really is in an initialized state.
290 /// Calling this when the content is not yet fully initialized
291 /// causes immediate undefined behavior.
293 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
298 /// #![feature(new_uninit)]
300 /// let mut five = Box::<u32>::new_uninit();
302 /// let five: Box<u32> = unsafe {
303 /// // Deferred initialization:
304 /// five.as_mut_ptr().write(5);
306 /// five.assume_init()
309 /// assert_eq!(*five, 5)
311 #[unstable(feature = "new_uninit", issue = "63291")]
313 pub unsafe fn assume_init(self) -> Box
<T
> {
314 Box(Box
::into_unique(self).cast())
318 impl<T
> Box
<[mem
::MaybeUninit
<T
>]> {
319 /// Converts to `Box<[T]>`.
323 /// As with [`MaybeUninit::assume_init`],
324 /// it is up to the caller to guarantee that the values
325 /// really are in an initialized state.
326 /// Calling this when the content is not yet fully initialized
327 /// causes immediate undefined behavior.
329 /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
334 /// #![feature(new_uninit)]
336 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
338 /// let values = unsafe {
339 /// // Deferred initialization:
340 /// values[0].as_mut_ptr().write(1);
341 /// values[1].as_mut_ptr().write(2);
342 /// values[2].as_mut_ptr().write(3);
344 /// values.assume_init()
347 /// assert_eq!(*values, [1, 2, 3])
349 #[unstable(feature = "new_uninit", issue = "63291")]
351 pub unsafe fn assume_init(self) -> Box
<[T
]> {
352 Box(Unique
::new_unchecked(Box
::into_raw(self) as _
))
356 impl<T
: ?Sized
> Box
<T
> {
357 /// Constructs a box from a raw pointer.
359 /// After calling this function, the raw pointer is owned by the
360 /// resulting `Box`. Specifically, the `Box` destructor will call
361 /// the destructor of `T` and free the allocated memory. For this
362 /// to be safe, the memory must have been allocated in accordance
363 /// with the [memory layout] used by `Box` .
367 /// This function is unsafe because improper use may lead to
368 /// memory problems. For example, a double-free may occur if the
369 /// function is called twice on the same raw pointer.
372 /// Recreate a `Box` which was previously converted to a raw pointer
373 /// using [`Box::into_raw`]:
375 /// let x = Box::new(5);
376 /// let ptr = Box::into_raw(x);
377 /// let x = unsafe { Box::from_raw(ptr) };
379 /// Manually create a `Box` from scratch by using the global allocator:
381 /// use std::alloc::{alloc, Layout};
384 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
386 /// let x = Box::from_raw(ptr);
390 /// [memory layout]: index.html#memory-layout
391 /// [`Layout`]: ../alloc/struct.Layout.html
392 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
393 #[stable(feature = "box_raw", since = "1.4.0")]
395 pub unsafe fn from_raw(raw
: *mut T
) -> Self {
396 Box(Unique
::new_unchecked(raw
))
399 /// Consumes the `Box`, returning a wrapped raw pointer.
401 /// The pointer will be properly aligned and non-null.
403 /// After calling this function, the caller is responsible for the
404 /// memory previously managed by the `Box`. In particular, the
405 /// caller should properly destroy `T` and release the memory, taking
406 /// into account the [memory layout] used by `Box`. The easiest way to
407 /// do this is to convert the raw pointer back into a `Box` with the
408 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
411 /// Note: this is an associated function, which means that you have
412 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
413 /// is so that there is no conflict with a method on the inner type.
416 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
417 /// for automatic cleanup:
419 /// let x = Box::new(String::from("Hello"));
420 /// let ptr = Box::into_raw(x);
421 /// let x = unsafe { Box::from_raw(ptr) };
423 /// Manual cleanup by explicitly running the destructor and deallocating
426 /// use std::alloc::{dealloc, Layout};
429 /// let x = Box::new(String::from("Hello"));
430 /// let p = Box::into_raw(x);
432 /// ptr::drop_in_place(p);
433 /// dealloc(p as *mut u8, Layout::new::<String>());
437 /// [memory layout]: index.html#memory-layout
438 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
439 #[stable(feature = "box_raw", since = "1.4.0")]
441 pub fn into_raw(b
: Box
<T
>) -> *mut T
{
442 Box
::into_raw_non_null(b
).as_ptr()
445 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
447 /// After calling this function, the caller is responsible for the
448 /// memory previously managed by the `Box`. In particular, the
449 /// caller should properly destroy `T` and release the memory. The
450 /// easiest way to do so is to convert the `NonNull<T>` pointer
451 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
454 /// Note: this is an associated function, which means that you have
455 /// to call it as `Box::into_raw_non_null(b)`
456 /// instead of `b.into_raw_non_null()`. This
457 /// is so that there is no conflict with a method on the inner type.
459 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
464 /// #![feature(box_into_raw_non_null)]
466 /// let x = Box::new(5);
467 /// let ptr = Box::into_raw_non_null(x);
469 /// // Clean up the memory by converting the NonNull pointer back
470 /// // into a Box and letting the Box be dropped.
471 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
473 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
475 pub fn into_raw_non_null(b
: Box
<T
>) -> NonNull
<T
> {
476 Box
::into_unique(b
).into()
479 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
482 pub fn into_unique(b
: Box
<T
>) -> Unique
<T
> {
483 let mut unique
= b
.0;
485 // Box is kind-of a library type, but recognized as a "unique pointer" by
486 // Stacked Borrows. This function here corresponds to "reborrowing to
487 // a raw pointer", but there is no actual reborrow here -- so
488 // without some care, the pointer we are returning here still carries
489 // the tag of `b`, with `Unique` permission.
490 // We round-trip through a mutable reference to avoid that.
491 unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
494 /// Consumes and leaks the `Box`, returning a mutable reference,
495 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
496 /// `'a`. If the type has only static references, or none at all, then this
497 /// may be chosen to be `'static`.
499 /// This function is mainly useful for data that lives for the remainder of
500 /// the program's life. Dropping the returned reference will cause a memory
501 /// leak. If this is not acceptable, the reference should first be wrapped
502 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
503 /// then be dropped which will properly destroy `T` and release the
504 /// allocated memory.
506 /// Note: this is an associated function, which means that you have
507 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
508 /// is so that there is no conflict with a method on the inner type.
510 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
517 /// let x = Box::new(41);
518 /// let static_ref: &'static mut usize = Box::leak(x);
519 /// *static_ref += 1;
520 /// assert_eq!(*static_ref, 42);
526 /// let x = vec![1, 2, 3].into_boxed_slice();
527 /// let static_ref = Box::leak(x);
528 /// static_ref[0] = 4;
529 /// assert_eq!(*static_ref, [4, 2, 3]);
531 #[stable(feature = "box_leak", since = "1.26.0")]
533 pub fn leak
<'a
>(b
: Box
<T
>) -> &'a
mut T
535 T
: 'a
// Technically not needed, but kept to be explicit.
537 unsafe { &mut *Box::into_raw(b) }
540 /// Converts a `Box<T>` into a `Pin<Box<T>>`
542 /// This conversion does not allocate on the heap and happens in place.
544 /// This is also available via [`From`].
545 #[unstable(feature = "box_into_pin", issue = "62370")]
546 pub fn into_pin(boxed
: Box
<T
>) -> Pin
<Box
<T
>> {
547 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
548 // when `T: !Unpin`, so it's safe to pin it directly without any
549 // additional requirements.
550 unsafe { Pin::new_unchecked(boxed) }
554 #[stable(feature = "rust1", since = "1.0.0")]
555 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
557 // FIXME: Do nothing, drop is currently performed by compiler.
561 #[stable(feature = "rust1", since = "1.0.0")]
562 impl<T
: Default
> Default
for Box
<T
> {
563 /// Creates a `Box<T>`, with the `Default` value for T.
564 fn default() -> Box
<T
> {
565 box Default
::default()
569 #[stable(feature = "rust1", since = "1.0.0")]
570 impl<T
> Default
for Box
<[T
]> {
571 fn default() -> Box
<[T
]> {
572 Box
::<[T
; 0]>::new([])
576 #[stable(feature = "default_box_extra", since = "1.17.0")]
577 impl Default
for Box
<str> {
578 fn default() -> Box
<str> {
579 unsafe { from_boxed_utf8_unchecked(Default::default()) }
583 #[stable(feature = "rust1", since = "1.0.0")]
584 impl<T
: Clone
> Clone
for Box
<T
> {
585 /// Returns a new box with a `clone()` of this box's contents.
590 /// let x = Box::new(5);
591 /// let y = x.clone();
593 /// // The value is the same
594 /// assert_eq!(x, y);
596 /// // But they are unique objects
597 /// assert_ne!(&*x as *const i32, &*y as *const i32);
601 fn clone(&self) -> Box
<T
> {
602 box { (**self).clone() }
605 /// Copies `source`'s contents into `self` without creating a new allocation.
610 /// let x = Box::new(5);
611 /// let mut y = Box::new(10);
612 /// let yp: *const i32 = &*y;
614 /// y.clone_from(&x);
616 /// // The value is the same
617 /// assert_eq!(x, y);
619 /// // And no allocation occurred
620 /// assert_eq!(yp, &*y);
623 fn clone_from(&mut self, source
: &Box
<T
>) {
624 (**self).clone_from(&(**source
));
629 #[stable(feature = "box_slice_clone", since = "1.3.0")]
630 impl Clone
for Box
<str> {
631 fn clone(&self) -> Self {
632 // this makes a copy of the data
633 let buf
: Box
<[u8]> = self.as_bytes().into();
635 from_boxed_utf8_unchecked(buf
)
640 #[stable(feature = "rust1", since = "1.0.0")]
641 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Box
<T
> {
643 fn eq(&self, other
: &Box
<T
>) -> bool
{
644 PartialEq
::eq(&**self, &**other
)
647 fn ne(&self, other
: &Box
<T
>) -> bool
{
648 PartialEq
::ne(&**self, &**other
)
651 #[stable(feature = "rust1", since = "1.0.0")]
652 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Box
<T
> {
654 fn partial_cmp(&self, other
: &Box
<T
>) -> Option
<Ordering
> {
655 PartialOrd
::partial_cmp(&**self, &**other
)
658 fn lt(&self, other
: &Box
<T
>) -> bool
{
659 PartialOrd
::lt(&**self, &**other
)
662 fn le(&self, other
: &Box
<T
>) -> bool
{
663 PartialOrd
::le(&**self, &**other
)
666 fn ge(&self, other
: &Box
<T
>) -> bool
{
667 PartialOrd
::ge(&**self, &**other
)
670 fn gt(&self, other
: &Box
<T
>) -> bool
{
671 PartialOrd
::gt(&**self, &**other
)
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl<T
: ?Sized
+ Ord
> Ord
for Box
<T
> {
677 fn cmp(&self, other
: &Box
<T
>) -> Ordering
{
678 Ord
::cmp(&**self, &**other
)
681 #[stable(feature = "rust1", since = "1.0.0")]
682 impl<T
: ?Sized
+ Eq
> Eq
for Box
<T
> {}
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T
: ?Sized
+ Hash
> Hash
for Box
<T
> {
686 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
687 (**self).hash(state
);
691 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
692 impl<T
: ?Sized
+ Hasher
> Hasher
for Box
<T
> {
693 fn finish(&self) -> u64 {
696 fn write(&mut self, bytes
: &[u8]) {
697 (**self).write(bytes
)
699 fn write_u8(&mut self, i
: u8) {
702 fn write_u16(&mut self, i
: u16) {
703 (**self).write_u16(i
)
705 fn write_u32(&mut self, i
: u32) {
706 (**self).write_u32(i
)
708 fn write_u64(&mut self, i
: u64) {
709 (**self).write_u64(i
)
711 fn write_u128(&mut self, i
: u128
) {
712 (**self).write_u128(i
)
714 fn write_usize(&mut self, i
: usize) {
715 (**self).write_usize(i
)
717 fn write_i8(&mut self, i
: i8) {
720 fn write_i16(&mut self, i
: i16) {
721 (**self).write_i16(i
)
723 fn write_i32(&mut self, i
: i32) {
724 (**self).write_i32(i
)
726 fn write_i64(&mut self, i
: i64) {
727 (**self).write_i64(i
)
729 fn write_i128(&mut self, i
: i128
) {
730 (**self).write_i128(i
)
732 fn write_isize(&mut self, i
: isize) {
733 (**self).write_isize(i
)
737 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
738 impl<T
> From
<T
> for Box
<T
> {
739 /// Converts a generic type `T` into a `Box<T>`
741 /// The conversion allocates on the heap and moves `t`
742 /// from the stack into it.
747 /// let boxed = Box::new(5);
749 /// assert_eq!(Box::from(x), boxed);
751 fn from(t
: T
) -> Self {
756 #[stable(feature = "pin", since = "1.33.0")]
757 impl<T
: ?Sized
> From
<Box
<T
>> for Pin
<Box
<T
>> {
758 /// Converts a `Box<T>` into a `Pin<Box<T>>`
760 /// This conversion does not allocate on the heap and happens in place.
761 fn from(boxed
: Box
<T
>) -> Self {
766 #[stable(feature = "box_from_slice", since = "1.17.0")]
767 impl<T
: Copy
> From
<&[T
]> for Box
<[T
]> {
768 /// Converts a `&[T]` into a `Box<[T]>`
770 /// This conversion allocates on the heap
771 /// and performs a copy of `slice`.
775 /// // create a &[u8] which will be used to create a Box<[u8]>
776 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
777 /// let boxed_slice: Box<[u8]> = Box::from(slice);
779 /// println!("{:?}", boxed_slice);
781 fn from(slice
: &[T
]) -> Box
<[T
]> {
782 let len
= slice
.len();
783 let buf
= RawVec
::with_capacity(len
);
785 ptr
::copy_nonoverlapping(slice
.as_ptr(), buf
.ptr(), len
);
791 #[stable(feature = "box_from_slice", since = "1.17.0")]
792 impl From
<&str> for Box
<str> {
793 /// Converts a `&str` into a `Box<str>`
795 /// This conversion allocates on the heap
796 /// and performs a copy of `s`.
800 /// let boxed: Box<str> = Box::from("hello");
801 /// println!("{}", boxed);
804 fn from(s
: &str) -> Box
<str> {
805 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
809 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
810 impl From
<Box
<str>> for Box
<[u8]> {
811 /// Converts a `Box<str>>` into a `Box<[u8]>`
813 /// This conversion does not allocate on the heap and happens in place.
817 /// // create a Box<str> which will be used to create a Box<[u8]>
818 /// let boxed: Box<str> = Box::from("hello");
819 /// let boxed_str: Box<[u8]> = Box::from(boxed);
821 /// // create a &[u8] which will be used to create a Box<[u8]>
822 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
823 /// let boxed_slice = Box::from(slice);
825 /// assert_eq!(boxed_slice, boxed_str);
828 fn from(s
: Box
<str>) -> Self {
829 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
833 #[unstable(feature = "boxed_slice_try_from", issue = "0")]
834 impl<T
, const N
: usize> TryFrom
<Box
<[T
]>> for Box
<[T
; N
]>
836 [T
; N
]: LengthAtMost32
,
838 type Error
= Box
<[T
]>;
840 fn try_from(boxed_slice
: Box
<[T
]>) -> Result
<Self, Self::Error
> {
841 if boxed_slice
.len() == N
{
842 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) }
)
851 #[stable(feature = "rust1", since = "1.0.0")]
852 /// Attempt to downcast the box to a concrete type.
857 /// use std::any::Any;
859 /// fn print_if_string(value: Box<dyn Any>) {
860 /// if let Ok(string) = value.downcast::<String>() {
861 /// println!("String ({}): {}", string.len(), string);
865 /// let my_string = "Hello World".to_string();
866 /// print_if_string(Box::new(my_string));
867 /// print_if_string(Box::new(0i8));
869 pub fn downcast
<T
: Any
>(self) -> Result
<Box
<T
>, Box
<dyn Any
>> {
872 let raw
: *mut dyn Any
= Box
::into_raw(self);
873 Ok(Box
::from_raw(raw
as *mut T
))
881 impl Box
<dyn Any
+ Send
> {
883 #[stable(feature = "rust1", since = "1.0.0")]
884 /// Attempt to downcast the box to a concrete type.
889 /// use std::any::Any;
891 /// fn print_if_string(value: Box<dyn Any + Send>) {
892 /// if let Ok(string) = value.downcast::<String>() {
893 /// println!("String ({}): {}", string.len(), string);
897 /// let my_string = "Hello World".to_string();
898 /// print_if_string(Box::new(my_string));
899 /// print_if_string(Box::new(0i8));
901 pub fn downcast
<T
: Any
>(self) -> Result
<Box
<T
>, Box
<dyn Any
+ Send
>> {
902 <Box
<dyn Any
>>::downcast(self).map_err(|s
| unsafe {
903 // reapply the Send marker
904 Box
::from_raw(Box
::into_raw(s
) as *mut (dyn Any
+ Send
))
909 #[stable(feature = "rust1", since = "1.0.0")]
910 impl<T
: fmt
::Display
+ ?Sized
> fmt
::Display
for Box
<T
> {
911 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
912 fmt
::Display
::fmt(&**self, f
)
916 #[stable(feature = "rust1", since = "1.0.0")]
917 impl<T
: fmt
::Debug
+ ?Sized
> fmt
::Debug
for Box
<T
> {
918 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
919 fmt
::Debug
::fmt(&**self, f
)
923 #[stable(feature = "rust1", since = "1.0.0")]
924 impl<T
: ?Sized
> fmt
::Pointer
for Box
<T
> {
925 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
926 // It's not possible to extract the inner Uniq directly from the Box,
927 // instead we cast it to a *const which aliases the Unique
928 let ptr
: *const T
= &**self;
929 fmt
::Pointer
::fmt(&ptr
, f
)
933 #[stable(feature = "rust1", since = "1.0.0")]
934 impl<T
: ?Sized
> Deref
for Box
<T
> {
937 fn deref(&self) -> &T
{
942 #[stable(feature = "rust1", since = "1.0.0")]
943 impl<T
: ?Sized
> DerefMut
for Box
<T
> {
944 fn deref_mut(&mut self) -> &mut T
{
949 #[unstable(feature = "receiver_trait", issue = "0")]
950 impl<T
: ?Sized
> Receiver
for Box
<T
> {}
952 #[stable(feature = "rust1", since = "1.0.0")]
953 impl<I
: Iterator
+ ?Sized
> Iterator
for Box
<I
> {
955 fn next(&mut self) -> Option
<I
::Item
> {
958 fn size_hint(&self) -> (usize, Option
<usize>) {
961 fn nth(&mut self, n
: usize) -> Option
<I
::Item
> {
964 fn last(self) -> Option
<I
::Item
> {
971 fn last(self) -> Option
<Self::Item
>;
974 impl<I
: Iterator
+ ?Sized
> BoxIter
for Box
<I
> {
976 default fn last(self) -> Option
<I
::Item
> {
978 fn some
<T
>(_
: Option
<T
>, x
: T
) -> Option
<T
> {
982 self.fold(None
, some
)
986 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
987 /// instead of the default.
988 #[stable(feature = "rust1", since = "1.0.0")]
989 impl<I
: Iterator
> BoxIter
for Box
<I
> {
990 fn last(self) -> Option
<I
::Item
> {
995 #[stable(feature = "rust1", since = "1.0.0")]
996 impl<I
: DoubleEndedIterator
+ ?Sized
> DoubleEndedIterator
for Box
<I
> {
997 fn next_back(&mut self) -> Option
<I
::Item
> {
1000 fn nth_back(&mut self, n
: usize) -> Option
<I
::Item
> {
1001 (**self).nth_back(n
)
1004 #[stable(feature = "rust1", since = "1.0.0")]
1005 impl<I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for Box
<I
> {
1006 fn len(&self) -> usize {
1009 fn is_empty(&self) -> bool
{
1014 #[stable(feature = "fused", since = "1.26.0")]
1015 impl<I
: FusedIterator
+ ?Sized
> FusedIterator
for Box
<I
> {}
1017 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1018 impl<A
, F
: FnOnce
<A
> + ?Sized
> FnOnce
<A
> for Box
<F
> {
1019 type Output
= <F
as FnOnce
<A
>>::Output
;
1021 extern "rust-call" fn call_once(self, args
: A
) -> Self::Output
{
1022 <F
as FnOnce
<A
>>::call_once(*self, args
)
1026 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1027 impl<A
, F
: FnMut
<A
> + ?Sized
> FnMut
<A
> for Box
<F
> {
1028 extern "rust-call" fn call_mut(&mut self, args
: A
) -> Self::Output
{
1029 <F
as FnMut
<A
>>::call_mut(self, args
)
1033 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1034 impl<A
, F
: Fn
<A
> + ?Sized
> Fn
<A
> for Box
<F
> {
1035 extern "rust-call" fn call(&self, args
: A
) -> Self::Output
{
1036 <F
as Fn
<A
>>::call(self, args
)
1040 #[unstable(feature = "coerce_unsized", issue = "27732")]
1041 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Box
<U
>> for Box
<T
> {}
1043 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
1044 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> DispatchFromDyn
<Box
<U
>> for Box
<T
> {}
1046 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1047 impl<A
> FromIterator
<A
> for Box
<[A
]> {
1048 fn from_iter
<T
: IntoIterator
<Item
= A
>>(iter
: T
) -> Self {
1049 iter
.into_iter().collect
::<Vec
<_
>>().into_boxed_slice()
1053 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1054 impl<T
: Clone
> Clone
for Box
<[T
]> {
1055 fn clone(&self) -> Self {
1056 let mut new
= BoxBuilder
{
1057 data
: RawVec
::with_capacity(self.len()),
1061 let mut target
= new
.data
.ptr();
1063 for item
in self.iter() {
1065 ptr
::write(target
, item
.clone());
1066 target
= target
.offset(1);
1072 return unsafe { new.into_box() }
;
1074 // Helper type for responding to panics correctly.
1075 struct BoxBuilder
<T
> {
1080 impl<T
> BoxBuilder
<T
> {
1081 unsafe fn into_box(self) -> Box
<[T
]> {
1082 let raw
= ptr
::read(&self.data
);
1088 impl<T
> Drop
for BoxBuilder
<T
> {
1089 fn drop(&mut self) {
1090 let mut data
= self.data
.ptr();
1091 let max
= unsafe { data.add(self.len) }
;
1096 data
= data
.offset(1);
1104 #[stable(feature = "box_borrow", since = "1.1.0")]
1105 impl<T
: ?Sized
> borrow
::Borrow
<T
> for Box
<T
> {
1106 fn borrow(&self) -> &T
{
1111 #[stable(feature = "box_borrow", since = "1.1.0")]
1112 impl<T
: ?Sized
> borrow
::BorrowMut
<T
> for Box
<T
> {
1113 fn borrow_mut(&mut self) -> &mut T
{
1118 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1119 impl<T
: ?Sized
> AsRef
<T
> for Box
<T
> {
1120 fn as_ref(&self) -> &T
{
1125 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1126 impl<T
: ?Sized
> AsMut
<T
> for Box
<T
> {
1127 fn as_mut(&mut self) -> &mut T
{
1134 * We could have chosen not to add this impl, and instead have written a
1135 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1136 * because Box<T> implements Unpin even when T does not, as a result of
1139 * We chose this API instead of the alternative for a few reasons:
1140 * - Logically, it is helpful to understand pinning in regard to the
1141 * memory region being pointed to. For this reason none of the
1142 * standard library pointer types support projecting through a pin
1143 * (Box<T> is the only pointer type in std for which this would be
1145 * - It is in practice very useful to have Box<T> be unconditionally
1146 * Unpin because of trait objects, for which the structural auto
1147 * trait functionality does not apply (e.g., Box<dyn Foo> would
1148 * otherwise not be Unpin).
1150 * Another type with the same semantics as Box but only a conditional
1151 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1152 * could have a method to project a Pin<T> from it.
1154 #[stable(feature = "pin", since = "1.33.0")]
1155 impl<T
: ?Sized
> Unpin
for Box
<T
> { }
1157 #[unstable(feature = "generator_trait", issue = "43122")]
1158 impl<G
: ?Sized
+ Generator
+ Unpin
> Generator
for Box
<G
> {
1159 type Yield
= G
::Yield
;
1160 type Return
= G
::Return
;
1162 fn resume(mut self: Pin
<&mut Self>) -> GeneratorState
<Self::Yield
, Self::Return
> {
1163 G
::resume(Pin
::new(&mut *self))
1167 #[unstable(feature = "generator_trait", issue = "43122")]
1168 impl<G
: ?Sized
+ Generator
> Generator
for Pin
<Box
<G
>> {
1169 type Yield
= G
::Yield
;
1170 type Return
= G
::Return
;
1172 fn resume(mut self: Pin
<&mut Self>) -> GeneratorState
<Self::Yield
, Self::Return
> {
1173 G
::resume((*self).as_mut())
1177 #[stable(feature = "futures_api", since = "1.36.0")]
1178 impl<F
: ?Sized
+ Future
+ Unpin
> Future
for Box
<F
> {
1179 type Output
= F
::Output
;
1181 fn poll(mut self: Pin
<&mut Self>, cx
: &mut Context
<'_
>) -> Poll
<Self::Output
> {
1182 F
::poll(Pin
::new(&mut *self), cx
)