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>>),
33 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //! println!("{:?}", list);
38 //! This will print `Cons(1, Cons(2, Nil))`.
40 //! Recursive structures must be boxed, because if the definition of `Cons`
43 //! ```compile_fail,E0072
49 //! It wouldn't work. This is because the size of a `List` depends on how many
50 //! elements are in the list, and so we don't know how much memory to allocate
51 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
52 //! big `Cons` needs to be.
56 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
57 //! its allocation. It is valid to convert both ways between a [`Box`] and a
58 //! raw pointer allocated with the [`Global`] allocator, given that the
59 //! [`Layout`] used with the allocator is correct for the type. More precisely,
60 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
61 //! with `Layout::for_value(&*value)` may be converted into a box using
62 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
63 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
64 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
67 //! [dereferencing]: ../../std/ops/trait.Deref.html
68 //! [`Box`]: struct.Box.html
69 //! [`Box<T>`]: struct.Box.html
70 //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
71 //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
72 //! [`Global`]: ../alloc/struct.Global.html
73 //! [`Layout`]: ../alloc/struct.Layout.html
74 //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value
76 #![stable(feature = "rust1", since = "1.0.0")]
80 use core::cmp::Ordering;
81 use core::convert::From;
83 use core::future::Future;
84 use core::hash::{Hash, Hasher};
85 use core::iter::{Iterator, FromIterator, FusedIterator};
86 use core::marker::{Unpin, Unsize};
90 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
92 use core::ptr::{self, NonNull, Unique};
93 use core::task::{Context, Poll};
96 use crate::raw_vec::RawVec;
97 use crate::str::from_boxed_utf8_unchecked;
99 /// A pointer type for heap allocation.
101 /// See the [module-level documentation](../../std/boxed/index.html) for more.
102 #[lang = "owned_box"]
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub struct Box<T: ?Sized>(Unique<T>);
108 /// Allocates memory on the heap and then places `x` into it.
110 /// This doesn't actually allocate if `T` is zero-sized.
115 /// let five = Box::new(5);
117 #[stable(feature = "rust1", since = "1.0.0")]
119 pub fn new(x: T) -> Box<T> {
123 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
124 /// `x` will be pinned in memory and unable to be moved.
125 #[stable(feature = "pin", since = "1.33.0")]
127 pub fn pin(x: T) -> Pin<Box<T>> {
132 impl<T: ?Sized> Box<T> {
133 /// Constructs a box from a raw pointer.
135 /// After calling this function, the raw pointer is owned by the
136 /// resulting `Box`. Specifically, the `Box` destructor will call
137 /// the destructor of `T` and free the allocated memory. For this
138 /// to be safe, the memory must have been allocated in accordance
139 /// with the [memory layout] used by `Box` .
143 /// This function is unsafe because improper use may lead to
144 /// memory problems. For example, a double-free may occur if the
145 /// function is called twice on the same raw pointer.
148 /// Recreate a `Box` which was previously converted to a raw pointer
149 /// using [`Box::into_raw`]:
151 /// let x = Box::new(5);
152 /// let ptr = Box::into_raw(x);
153 /// let x = unsafe { Box::from_raw(ptr) };
155 /// Manually create a `Box` from scratch by using the global allocator:
157 /// use std::alloc::{alloc, Layout};
160 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
162 /// let x = Box::from_raw(ptr);
166 /// [memory layout]: index.html#memory-layout
167 /// [`Layout`]: ../alloc/struct.Layout.html
168 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
169 #[stable(feature = "box_raw", since = "1.4.0")]
171 pub unsafe fn from_raw(raw: *mut T) -> Self {
172 Box(Unique::new_unchecked(raw))
175 /// Consumes the `Box`, returning a wrapped raw pointer.
177 /// The pointer will be properly aligned and non-null.
179 /// After calling this function, the caller is responsible for the
180 /// memory previously managed by the `Box`. In particular, the
181 /// caller should properly destroy `T` and release the memory, taking
182 /// into account the [memory layout] used by `Box`. The easiest way to
183 /// do this is to convert the raw pointer back into a `Box` with the
184 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
187 /// Note: this is an associated function, which means that you have
188 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
189 /// is so that there is no conflict with a method on the inner type.
192 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
193 /// for automatic cleanup:
195 /// let x = Box::new(String::from("Hello"));
196 /// let ptr = Box::into_raw(x);
197 /// let x = unsafe { Box::from_raw(ptr) };
199 /// Manual cleanup by explicitly running the destructor and deallocating
202 /// use std::alloc::{dealloc, Layout};
205 /// let x = Box::new(String::from("Hello"));
206 /// let p = Box::into_raw(x);
208 /// ptr::drop_in_place(p);
209 /// dealloc(p as *mut u8, Layout::new::<String>());
213 /// [memory layout]: index.html#memory-layout
214 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
215 #[stable(feature = "box_raw", since = "1.4.0")]
217 pub fn into_raw(b: Box<T>) -> *mut T {
218 Box::into_raw_non_null(b).as_ptr()
221 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
223 /// After calling this function, the caller is responsible for the
224 /// memory previously managed by the `Box`. In particular, the
225 /// caller should properly destroy `T` and release the memory. The
226 /// easiest way to do so is to convert the `NonNull<T>` pointer
227 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
230 /// Note: this is an associated function, which means that you have
231 /// to call it as `Box::into_raw_non_null(b)`
232 /// instead of `b.into_raw_non_null()`. This
233 /// is so that there is no conflict with a method on the inner type.
235 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
240 /// #![feature(box_into_raw_non_null)]
243 /// let x = Box::new(5);
244 /// let ptr = Box::into_raw_non_null(x);
246 /// // Clean up the memory by converting the NonNull pointer back
247 /// // into a Box and letting the Box be dropped.
248 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
251 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
253 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
254 Box::into_unique(b).into()
257 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
260 pub fn into_unique(b: Box<T>) -> Unique<T> {
261 let mut unique = b.0;
263 // Box is kind-of a library type, but recognized as a "unique pointer" by
264 // Stacked Borrows. This function here corresponds to "reborrowing to
265 // a raw pointer", but there is no actual reborrow here -- so
266 // without some care, the pointer we are returning here still carries
267 // the tag of `b`, with `Unique` permission.
268 // We round-trip through a mutable reference to avoid that.
269 unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
272 /// Consumes and leaks the `Box`, returning a mutable reference,
273 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
274 /// `'a`. If the type has only static references, or none at all, then this
275 /// may be chosen to be `'static`.
277 /// This function is mainly useful for data that lives for the remainder of
278 /// the program's life. Dropping the returned reference will cause a memory
279 /// leak. If this is not acceptable, the reference should first be wrapped
280 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
281 /// then be dropped which will properly destroy `T` and release the
282 /// allocated memory.
284 /// Note: this is an associated function, which means that you have
285 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
286 /// is so that there is no conflict with a method on the inner type.
288 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
296 /// let x = Box::new(41);
297 /// let static_ref: &'static mut usize = Box::leak(x);
298 /// *static_ref += 1;
299 /// assert_eq!(*static_ref, 42);
307 /// let x = vec![1, 2, 3].into_boxed_slice();
308 /// let static_ref = Box::leak(x);
309 /// static_ref[0] = 4;
310 /// assert_eq!(*static_ref, [4, 2, 3]);
313 #[stable(feature = "box_leak", since = "1.26.0")]
315 pub fn leak<'a>(b: Box<T>) -> &'a mut T
317 T: 'a // Technically not needed, but kept to be explicit.
319 unsafe { &mut *Box::into_raw(b) }
322 /// Converts a `Box<T>` into a `Pin<Box<T>>`
324 /// This conversion does not allocate on the heap and happens in place.
326 /// This is also available via [`From`].
327 #[unstable(feature = "box_into_pin", issue = "62370")]
328 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
329 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
330 // when `T: !Unpin`, so it's safe to pin it directly without any
331 // additional requirements.
332 unsafe { Pin::new_unchecked(boxed) }
336 #[stable(feature = "rust1", since = "1.0.0")]
337 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
339 // FIXME: Do nothing, drop is currently performed by compiler.
343 #[stable(feature = "rust1", since = "1.0.0")]
344 impl<T: Default> Default for Box<T> {
345 /// Creates a `Box<T>`, with the `Default` value for T.
346 fn default() -> Box<T> {
347 box Default::default()
351 #[stable(feature = "rust1", since = "1.0.0")]
352 impl<T> Default for Box<[T]> {
353 fn default() -> Box<[T]> {
354 Box::<[T; 0]>::new([])
358 #[stable(feature = "default_box_extra", since = "1.17.0")]
359 impl Default for Box<str> {
360 fn default() -> Box<str> {
361 unsafe { from_boxed_utf8_unchecked(Default::default()) }
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<T: Clone> Clone for Box<T> {
367 /// Returns a new box with a `clone()` of this box's contents.
372 /// let x = Box::new(5);
373 /// let y = x.clone();
375 /// // The value is the same
376 /// assert_eq!(x, y);
378 /// // But they are unique objects
379 /// assert_ne!(&*x as *const i32, &*y as *const i32);
383 fn clone(&self) -> Box<T> {
384 box { (**self).clone() }
387 /// Copies `source`'s contents into `self` without creating a new allocation.
392 /// let x = Box::new(5);
393 /// let mut y = Box::new(10);
394 /// let yp: *const i32 = &*y;
396 /// y.clone_from(&x);
398 /// // The value is the same
399 /// assert_eq!(x, y);
401 /// // And no allocation occurred
402 /// assert_eq!(yp, &*y);
405 fn clone_from(&mut self, source: &Box<T>) {
406 (**self).clone_from(&(**source));
411 #[stable(feature = "box_slice_clone", since = "1.3.0")]
412 impl Clone for Box<str> {
413 fn clone(&self) -> Self {
414 // this makes a copy of the data
415 let buf: Box<[u8]> = self.as_bytes().into();
417 from_boxed_utf8_unchecked(buf)
422 #[stable(feature = "rust1", since = "1.0.0")]
423 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
425 fn eq(&self, other: &Box<T>) -> bool {
426 PartialEq::eq(&**self, &**other)
429 fn ne(&self, other: &Box<T>) -> bool {
430 PartialEq::ne(&**self, &**other)
433 #[stable(feature = "rust1", since = "1.0.0")]
434 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
436 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
437 PartialOrd::partial_cmp(&**self, &**other)
440 fn lt(&self, other: &Box<T>) -> bool {
441 PartialOrd::lt(&**self, &**other)
444 fn le(&self, other: &Box<T>) -> bool {
445 PartialOrd::le(&**self, &**other)
448 fn ge(&self, other: &Box<T>) -> bool {
449 PartialOrd::ge(&**self, &**other)
452 fn gt(&self, other: &Box<T>) -> bool {
453 PartialOrd::gt(&**self, &**other)
456 #[stable(feature = "rust1", since = "1.0.0")]
457 impl<T: ?Sized + Ord> Ord for Box<T> {
459 fn cmp(&self, other: &Box<T>) -> Ordering {
460 Ord::cmp(&**self, &**other)
463 #[stable(feature = "rust1", since = "1.0.0")]
464 impl<T: ?Sized + Eq> Eq for Box<T> {}
466 #[stable(feature = "rust1", since = "1.0.0")]
467 impl<T: ?Sized + Hash> Hash for Box<T> {
468 fn hash<H: Hasher>(&self, state: &mut H) {
469 (**self).hash(state);
473 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
474 impl<T: ?Sized + Hasher> Hasher for Box<T> {
475 fn finish(&self) -> u64 {
478 fn write(&mut self, bytes: &[u8]) {
479 (**self).write(bytes)
481 fn write_u8(&mut self, i: u8) {
484 fn write_u16(&mut self, i: u16) {
485 (**self).write_u16(i)
487 fn write_u32(&mut self, i: u32) {
488 (**self).write_u32(i)
490 fn write_u64(&mut self, i: u64) {
491 (**self).write_u64(i)
493 fn write_u128(&mut self, i: u128) {
494 (**self).write_u128(i)
496 fn write_usize(&mut self, i: usize) {
497 (**self).write_usize(i)
499 fn write_i8(&mut self, i: i8) {
502 fn write_i16(&mut self, i: i16) {
503 (**self).write_i16(i)
505 fn write_i32(&mut self, i: i32) {
506 (**self).write_i32(i)
508 fn write_i64(&mut self, i: i64) {
509 (**self).write_i64(i)
511 fn write_i128(&mut self, i: i128) {
512 (**self).write_i128(i)
514 fn write_isize(&mut self, i: isize) {
515 (**self).write_isize(i)
519 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
520 impl<T> From<T> for Box<T> {
521 /// Converts a generic type `T` into a `Box<T>`
523 /// The conversion allocates on the heap and moves `t`
524 /// from the stack into it.
529 /// let boxed = Box::new(5);
531 /// assert_eq!(Box::from(x), boxed);
533 fn from(t: T) -> Self {
538 #[stable(feature = "pin", since = "1.33.0")]
539 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
540 /// Converts a `Box<T>` into a `Pin<Box<T>>`
542 /// This conversion does not allocate on the heap and happens in place.
543 fn from(boxed: Box<T>) -> Self {
548 #[stable(feature = "box_from_slice", since = "1.17.0")]
549 impl<T: Copy> From<&[T]> for Box<[T]> {
550 /// Converts a `&[T]` into a `Box<[T]>`
552 /// This conversion allocates on the heap
553 /// and performs a copy of `slice`.
557 /// // create a &[u8] which will be used to create a Box<[u8]>
558 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
559 /// let boxed_slice: Box<[u8]> = Box::from(slice);
561 /// println!("{:?}", boxed_slice);
563 fn from(slice: &[T]) -> Box<[T]> {
564 let len = slice.len();
565 let buf = RawVec::with_capacity(len);
567 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
573 #[stable(feature = "box_from_slice", since = "1.17.0")]
574 impl From<&str> for Box<str> {
575 /// Converts a `&str` into a `Box<str>`
577 /// This conversion allocates on the heap
578 /// and performs a copy of `s`.
582 /// let boxed: Box<str> = Box::from("hello");
583 /// println!("{}", boxed);
586 fn from(s: &str) -> Box<str> {
587 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
591 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
592 impl From<Box<str>> for Box<[u8]> {
593 /// Converts a `Box<str>>` into a `Box<[u8]>`
595 /// This conversion does not allocate on the heap and happens in place.
599 /// // create a Box<str> which will be used to create a Box<[u8]>
600 /// let boxed: Box<str> = Box::from("hello");
601 /// let boxed_str: Box<[u8]> = Box::from(boxed);
603 /// // create a &[u8] which will be used to create a Box<[u8]>
604 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
605 /// let boxed_slice = Box::from(slice);
607 /// assert_eq!(boxed_slice, boxed_str);
610 fn from(s: Box<str>) -> Self {
611 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
617 #[stable(feature = "rust1", since = "1.0.0")]
618 /// Attempt to downcast the box to a concrete type.
623 /// use std::any::Any;
625 /// fn print_if_string(value: Box<dyn Any>) {
626 /// if let Ok(string) = value.downcast::<String>() {
627 /// println!("String ({}): {}", string.len(), string);
632 /// let my_string = "Hello World".to_string();
633 /// print_if_string(Box::new(my_string));
634 /// print_if_string(Box::new(0i8));
637 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
640 let raw: *mut dyn Any = Box::into_raw(self);
641 Ok(Box::from_raw(raw as *mut T))
649 impl Box<dyn Any + Send> {
651 #[stable(feature = "rust1", since = "1.0.0")]
652 /// Attempt to downcast the box to a concrete type.
657 /// use std::any::Any;
659 /// fn print_if_string(value: Box<dyn Any + Send>) {
660 /// if let Ok(string) = value.downcast::<String>() {
661 /// println!("String ({}): {}", string.len(), string);
666 /// let my_string = "Hello World".to_string();
667 /// print_if_string(Box::new(my_string));
668 /// print_if_string(Box::new(0i8));
671 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
672 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
673 // reapply the Send marker
674 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
681 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
682 fmt::Display::fmt(&**self, f)
686 #[stable(feature = "rust1", since = "1.0.0")]
687 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689 fmt::Debug::fmt(&**self, f)
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<T: ?Sized> fmt::Pointer for Box<T> {
695 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
696 // It's not possible to extract the inner Uniq directly from the Box,
697 // instead we cast it to a *const which aliases the Unique
698 let ptr: *const T = &**self;
699 fmt::Pointer::fmt(&ptr, f)
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<T: ?Sized> Deref for Box<T> {
707 fn deref(&self) -> &T {
712 #[stable(feature = "rust1", since = "1.0.0")]
713 impl<T: ?Sized> DerefMut for Box<T> {
714 fn deref_mut(&mut self) -> &mut T {
719 #[unstable(feature = "receiver_trait", issue = "0")]
720 impl<T: ?Sized> Receiver for Box<T> {}
722 #[stable(feature = "rust1", since = "1.0.0")]
723 impl<I: Iterator + ?Sized> Iterator for Box<I> {
725 fn next(&mut self) -> Option<I::Item> {
728 fn size_hint(&self) -> (usize, Option<usize>) {
731 fn nth(&mut self, n: usize) -> Option<I::Item> {
736 #[stable(feature = "rust1", since = "1.0.0")]
737 impl<I: Iterator + Sized> Iterator for Box<I> {
738 fn last(self) -> Option<I::Item> where I: Sized {
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
745 fn next_back(&mut self) -> Option<I::Item> {
748 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
754 fn len(&self) -> usize {
757 fn is_empty(&self) -> bool {
762 #[stable(feature = "fused", since = "1.26.0")]
763 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
765 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
766 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
767 type Output = <F as FnOnce<A>>::Output;
769 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
770 <F as FnOnce<A>>::call_once(*self, args)
774 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
775 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
776 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
777 <F as FnMut<A>>::call_mut(self, args)
781 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
782 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
783 extern "rust-call" fn call(&self, args: A) -> Self::Output {
784 <F as Fn<A>>::call(self, args)
788 #[unstable(feature = "coerce_unsized", issue = "27732")]
789 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
791 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
792 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
794 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
795 impl<A> FromIterator<A> for Box<[A]> {
796 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
797 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
801 #[stable(feature = "box_slice_clone", since = "1.3.0")]
802 impl<T: Clone> Clone for Box<[T]> {
803 fn clone(&self) -> Self {
804 let mut new = BoxBuilder {
805 data: RawVec::with_capacity(self.len()),
809 let mut target = new.data.ptr();
811 for item in self.iter() {
813 ptr::write(target, item.clone());
814 target = target.offset(1);
820 return unsafe { new.into_box() };
822 // Helper type for responding to panics correctly.
823 struct BoxBuilder<T> {
828 impl<T> BoxBuilder<T> {
829 unsafe fn into_box(self) -> Box<[T]> {
830 let raw = ptr::read(&self.data);
836 impl<T> Drop for BoxBuilder<T> {
838 let mut data = self.data.ptr();
839 let max = unsafe { data.add(self.len) };
844 data = data.offset(1);
852 #[stable(feature = "box_borrow", since = "1.1.0")]
853 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
854 fn borrow(&self) -> &T {
859 #[stable(feature = "box_borrow", since = "1.1.0")]
860 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
861 fn borrow_mut(&mut self) -> &mut T {
866 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
867 impl<T: ?Sized> AsRef<T> for Box<T> {
868 fn as_ref(&self) -> &T {
873 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
874 impl<T: ?Sized> AsMut<T> for Box<T> {
875 fn as_mut(&mut self) -> &mut T {
882 * We could have chosen not to add this impl, and instead have written a
883 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
884 * because Box<T> implements Unpin even when T does not, as a result of
887 * We chose this API instead of the alternative for a few reasons:
888 * - Logically, it is helpful to understand pinning in regard to the
889 * memory region being pointed to. For this reason none of the
890 * standard library pointer types support projecting through a pin
891 * (Box<T> is the only pointer type in std for which this would be
893 * - It is in practice very useful to have Box<T> be unconditionally
894 * Unpin because of trait objects, for which the structural auto
895 * trait functionality does not apply (e.g., Box<dyn Foo> would
896 * otherwise not be Unpin).
898 * Another type with the same semantics as Box but only a conditional
899 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
900 * could have a method to project a Pin<T> from it.
902 #[stable(feature = "pin", since = "1.33.0")]
903 impl<T: ?Sized> Unpin for Box<T> { }
905 #[unstable(feature = "generator_trait", issue = "43122")]
906 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
907 type Yield = G::Yield;
908 type Return = G::Return;
910 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
911 G::resume(Pin::new(&mut *self))
915 #[unstable(feature = "generator_trait", issue = "43122")]
916 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
917 type Yield = G::Yield;
918 type Return = G::Return;
920 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
921 G::resume((*self).as_mut())
925 #[stable(feature = "futures_api", since = "1.36.0")]
926 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
927 type Output = F::Output;
929 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
930 F::poll(Pin::new(&mut *self), cx)