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`, 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 //! [`Global`]: ../alloc/struct.Global.html
70 //! [`Layout`]: ../alloc/struct.Layout.html
72 #![stable(feature = "rust1", since = "1.0.0")]
76 use core::cmp::Ordering;
77 use core::convert::From;
79 use core::future::Future;
80 use core::hash::{Hash, Hasher};
81 use core::iter::{Iterator, FromIterator, FusedIterator};
82 use core::marker::{Unpin, Unsize};
86 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
88 use core::ptr::{self, NonNull, Unique};
89 use core::task::{Context, Poll};
92 use crate::raw_vec::RawVec;
93 use crate::str::from_boxed_utf8_unchecked;
95 /// A pointer type for heap allocation.
97 /// See the [module-level documentation](../../std/boxed/index.html) for more.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 pub struct Box<T: ?Sized>(Unique<T>);
104 /// Allocates memory on the heap and then places `x` into it.
106 /// This doesn't actually allocate if `T` is zero-sized.
111 /// let five = Box::new(5);
113 #[stable(feature = "rust1", since = "1.0.0")]
115 pub fn new(x: T) -> Box<T> {
119 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
120 /// `x` will be pinned in memory and unable to be moved.
121 #[stable(feature = "pin", since = "1.33.0")]
123 pub fn pin(x: T) -> Pin<Box<T>> {
128 impl<T: ?Sized> Box<T> {
129 /// Constructs a box from a raw pointer.
131 /// After calling this function, the raw pointer is owned by the
132 /// resulting `Box`. Specifically, the `Box` destructor will call
133 /// the destructor of `T` and free the allocated memory. For this
134 /// to be safe, the memory must have been allocated in accordance
135 /// with the [memory layout] used by `Box` .
139 /// This function is unsafe because improper use may lead to
140 /// memory problems. For example, a double-free may occur if the
141 /// function is called twice on the same raw pointer.
144 /// Recreate a `Box` which was previously converted to a raw pointer
145 /// using [`Box::into_raw`]:
147 /// let x = Box::new(5);
148 /// let ptr = Box::into_raw(x);
149 /// let x = unsafe { Box::from_raw(ptr) };
151 /// Manually create a `Box` from scratch by using the global allocator:
153 /// use std::alloc::{alloc, Layout};
156 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
158 /// let x = Box::from_raw(ptr);
162 /// [memory layout]: index.html#memory-layout
163 /// [`Layout`]: ../alloc/struct.Layout.html
164 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
165 #[stable(feature = "box_raw", since = "1.4.0")]
167 pub unsafe fn from_raw(raw: *mut T) -> Self {
168 Box(Unique::new_unchecked(raw))
171 /// Consumes the `Box`, returning a wrapped raw pointer.
173 /// The pointer will be properly aligned and non-null.
175 /// After calling this function, the caller is responsible for the
176 /// memory previously managed by the `Box`. In particular, the
177 /// caller should properly destroy `T` and release the memory, taking
178 /// into account the [memory layout] used by `Box`. The easiest way to
179 /// do this is to convert the raw pointer back into a `Box` with the
180 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
183 /// Note: this is an associated function, which means that you have
184 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
185 /// is so that there is no conflict with a method on the inner type.
188 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
189 /// for automatic cleanup:
191 /// let x = Box::new(String::from("Hello"));
192 /// let ptr = Box::into_raw(x);
193 /// let x = unsafe { Box::from_raw(ptr) };
195 /// Manual cleanup by explicitly running the destructor and deallocating
198 /// use std::alloc::{dealloc, Layout};
201 /// let x = Box::new(String::from("Hello"));
202 /// let p = Box::into_raw(x);
204 /// ptr::drop_in_place(p);
205 /// dealloc(p as *mut u8, Layout::new::<String>());
209 /// [memory layout]: index.html#memory-layout
210 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
211 #[stable(feature = "box_raw", since = "1.4.0")]
213 pub fn into_raw(b: Box<T>) -> *mut T {
214 Box::into_raw_non_null(b).as_ptr()
217 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
219 /// After calling this function, the caller is responsible for the
220 /// memory previously managed by the `Box`. In particular, the
221 /// caller should properly destroy `T` and release the memory. The
222 /// easiest way to do so is to convert the `NonNull<T>` pointer
223 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
226 /// Note: this is an associated function, which means that you have
227 /// to call it as `Box::into_raw_non_null(b)`
228 /// instead of `b.into_raw_non_null()`. This
229 /// is so that there is no conflict with a method on the inner type.
231 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
236 /// #![feature(box_into_raw_non_null)]
239 /// let x = Box::new(5);
240 /// let ptr = Box::into_raw_non_null(x);
242 /// // Clean up the memory by converting the NonNull pointer back
243 /// // into a Box and letting the Box be dropped.
244 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
247 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
249 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
250 Box::into_unique(b).into()
253 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
256 pub fn into_unique(b: Box<T>) -> Unique<T> {
257 let mut unique = b.0;
259 // Box is kind-of a library type, but recognized as a "unique pointer" by
260 // Stacked Borrows. This function here corresponds to "reborrowing to
261 // a raw pointer", but there is no actual reborrow here -- so
262 // without some care, the pointer we are returning here still carries
263 // the tag of `b`, with `Unique` permission.
264 // We round-trip through a mutable reference to avoid that.
265 unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
268 /// Consumes and leaks the `Box`, returning a mutable reference,
269 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
270 /// `'a`. If the type has only static references, or none at all, then this
271 /// may be chosen to be `'static`.
273 /// This function is mainly useful for data that lives for the remainder of
274 /// the program's life. Dropping the returned reference will cause a memory
275 /// leak. If this is not acceptable, the reference should first be wrapped
276 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
277 /// then be dropped which will properly destroy `T` and release the
278 /// allocated memory.
280 /// Note: this is an associated function, which means that you have
281 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
282 /// is so that there is no conflict with a method on the inner type.
284 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
292 /// let x = Box::new(41);
293 /// let static_ref: &'static mut usize = Box::leak(x);
294 /// *static_ref += 1;
295 /// assert_eq!(*static_ref, 42);
303 /// let x = vec![1, 2, 3].into_boxed_slice();
304 /// let static_ref = Box::leak(x);
305 /// static_ref[0] = 4;
306 /// assert_eq!(*static_ref, [4, 2, 3]);
309 #[stable(feature = "box_leak", since = "1.26.0")]
311 pub fn leak<'a>(b: Box<T>) -> &'a mut T
313 T: 'a // Technically not needed, but kept to be explicit.
315 unsafe { &mut *Box::into_raw(b) }
318 /// Converts a `Box<T>` into a `Pin<Box<T>>`
320 /// This conversion does not allocate on the heap and happens in place.
322 /// This is also available via [`From`].
323 #[unstable(feature = "box_into_pin", issue = "0")]
324 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
325 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
326 // when `T: !Unpin`, so it's safe to pin it directly without any
327 // additional requirements.
328 unsafe { Pin::new_unchecked(boxed) }
332 #[stable(feature = "rust1", since = "1.0.0")]
333 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
335 // FIXME: Do nothing, drop is currently performed by compiler.
339 #[stable(feature = "rust1", since = "1.0.0")]
340 impl<T: Default> Default for Box<T> {
341 /// Creates a `Box<T>`, with the `Default` value for T.
342 fn default() -> Box<T> {
343 box Default::default()
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<T> Default for Box<[T]> {
349 fn default() -> Box<[T]> {
350 Box::<[T; 0]>::new([])
354 #[stable(feature = "default_box_extra", since = "1.17.0")]
355 impl Default for Box<str> {
356 fn default() -> Box<str> {
357 unsafe { from_boxed_utf8_unchecked(Default::default()) }
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T: Clone> Clone for Box<T> {
363 /// Returns a new box with a `clone()` of this box's contents.
368 /// let x = Box::new(5);
369 /// let y = x.clone();
371 /// // The value is the same
372 /// assert_eq!(x, y);
374 /// // But they are unique objects
375 /// assert_ne!(&*x as *const i32, &*y as *const i32);
379 fn clone(&self) -> Box<T> {
380 box { (**self).clone() }
383 /// Copies `source`'s contents into `self` without creating a new allocation.
388 /// let x = Box::new(5);
389 /// let mut y = Box::new(10);
390 /// let yp: *const i32 = &*y;
392 /// y.clone_from(&x);
394 /// // The value is the same
395 /// assert_eq!(x, y);
397 /// // And no allocation occurred
398 /// assert_eq!(yp, &*y);
401 fn clone_from(&mut self, source: &Box<T>) {
402 (**self).clone_from(&(**source));
407 #[stable(feature = "box_slice_clone", since = "1.3.0")]
408 impl Clone for Box<str> {
409 fn clone(&self) -> Self {
410 // this makes a copy of the data
411 let buf: Box<[u8]> = self.as_bytes().into();
413 from_boxed_utf8_unchecked(buf)
418 #[stable(feature = "rust1", since = "1.0.0")]
419 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
421 fn eq(&self, other: &Box<T>) -> bool {
422 PartialEq::eq(&**self, &**other)
425 fn ne(&self, other: &Box<T>) -> bool {
426 PartialEq::ne(&**self, &**other)
429 #[stable(feature = "rust1", since = "1.0.0")]
430 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
432 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
433 PartialOrd::partial_cmp(&**self, &**other)
436 fn lt(&self, other: &Box<T>) -> bool {
437 PartialOrd::lt(&**self, &**other)
440 fn le(&self, other: &Box<T>) -> bool {
441 PartialOrd::le(&**self, &**other)
444 fn ge(&self, other: &Box<T>) -> bool {
445 PartialOrd::ge(&**self, &**other)
448 fn gt(&self, other: &Box<T>) -> bool {
449 PartialOrd::gt(&**self, &**other)
452 #[stable(feature = "rust1", since = "1.0.0")]
453 impl<T: ?Sized + Ord> Ord for Box<T> {
455 fn cmp(&self, other: &Box<T>) -> Ordering {
456 Ord::cmp(&**self, &**other)
459 #[stable(feature = "rust1", since = "1.0.0")]
460 impl<T: ?Sized + Eq> Eq for Box<T> {}
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<T: ?Sized + Hash> Hash for Box<T> {
464 fn hash<H: Hasher>(&self, state: &mut H) {
465 (**self).hash(state);
469 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
470 impl<T: ?Sized + Hasher> Hasher for Box<T> {
471 fn finish(&self) -> u64 {
474 fn write(&mut self, bytes: &[u8]) {
475 (**self).write(bytes)
477 fn write_u8(&mut self, i: u8) {
480 fn write_u16(&mut self, i: u16) {
481 (**self).write_u16(i)
483 fn write_u32(&mut self, i: u32) {
484 (**self).write_u32(i)
486 fn write_u64(&mut self, i: u64) {
487 (**self).write_u64(i)
489 fn write_u128(&mut self, i: u128) {
490 (**self).write_u128(i)
492 fn write_usize(&mut self, i: usize) {
493 (**self).write_usize(i)
495 fn write_i8(&mut self, i: i8) {
498 fn write_i16(&mut self, i: i16) {
499 (**self).write_i16(i)
501 fn write_i32(&mut self, i: i32) {
502 (**self).write_i32(i)
504 fn write_i64(&mut self, i: i64) {
505 (**self).write_i64(i)
507 fn write_i128(&mut self, i: i128) {
508 (**self).write_i128(i)
510 fn write_isize(&mut self, i: isize) {
511 (**self).write_isize(i)
515 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
516 impl<T> From<T> for Box<T> {
517 /// Converts a generic type `T` into a `Box<T>`
519 /// The conversion allocates on the heap and moves `t`
520 /// from the stack into it.
525 /// let boxed = Box::new(5);
527 /// assert_eq!(Box::from(x), boxed);
529 fn from(t: T) -> Self {
534 #[stable(feature = "pin", since = "1.33.0")]
535 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
536 /// Converts a `Box<T>` into a `Pin<Box<T>>`
538 /// This conversion does not allocate on the heap and happens in place.
539 fn from(boxed: Box<T>) -> Self {
544 #[stable(feature = "box_from_slice", since = "1.17.0")]
545 impl<T: Copy> From<&[T]> for Box<[T]> {
546 /// Converts a `&[T]` into a `Box<[T]>`
548 /// This conversion allocates on the heap
549 /// and performs a copy of `slice`.
553 /// // create a &[u8] which will be used to create a Box<[u8]>
554 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
555 /// let boxed_slice: Box<[u8]> = Box::from(slice);
557 /// println!("{:?}", boxed_slice);
559 fn from(slice: &[T]) -> Box<[T]> {
560 let len = slice.len();
561 let buf = RawVec::with_capacity(len);
563 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
569 #[stable(feature = "box_from_slice", since = "1.17.0")]
570 impl From<&str> for Box<str> {
571 /// Converts a `&str` into a `Box<str>`
573 /// This conversion allocates on the heap
574 /// and performs a copy of `s`.
578 /// let boxed: Box<str> = Box::from("hello");
579 /// println!("{}", boxed);
582 fn from(s: &str) -> Box<str> {
583 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
587 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
588 impl From<Box<str>> for Box<[u8]> {
589 /// Converts a `Box<str>>` into a `Box<[u8]>`
591 /// This conversion does not allocate on the heap and happens in place.
595 /// // create a Box<str> which will be used to create a Box<[u8]>
596 /// let boxed: Box<str> = Box::from("hello");
597 /// let boxed_str: Box<[u8]> = Box::from(boxed);
599 /// // create a &[u8] which will be used to create a Box<[u8]>
600 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
601 /// let boxed_slice = Box::from(slice);
603 /// assert_eq!(boxed_slice, boxed_str);
606 fn from(s: Box<str>) -> Self {
607 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
613 #[stable(feature = "rust1", since = "1.0.0")]
614 /// Attempt to downcast the box to a concrete type.
619 /// use std::any::Any;
621 /// fn print_if_string(value: Box<dyn Any>) {
622 /// if let Ok(string) = value.downcast::<String>() {
623 /// println!("String ({}): {}", string.len(), string);
628 /// let my_string = "Hello World".to_string();
629 /// print_if_string(Box::new(my_string));
630 /// print_if_string(Box::new(0i8));
633 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
636 let raw: *mut dyn Any = Box::into_raw(self);
637 Ok(Box::from_raw(raw as *mut T))
645 impl Box<dyn Any + Send> {
647 #[stable(feature = "rust1", since = "1.0.0")]
648 /// Attempt to downcast the box to a concrete type.
653 /// use std::any::Any;
655 /// fn print_if_string(value: Box<dyn Any + Send>) {
656 /// if let Ok(string) = value.downcast::<String>() {
657 /// println!("String ({}): {}", string.len(), string);
662 /// let my_string = "Hello World".to_string();
663 /// print_if_string(Box::new(my_string));
664 /// print_if_string(Box::new(0i8));
667 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
668 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
669 // reapply the Send marker
670 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
677 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678 fmt::Display::fmt(&**self, f)
682 #[stable(feature = "rust1", since = "1.0.0")]
683 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
684 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
685 fmt::Debug::fmt(&**self, f)
689 #[stable(feature = "rust1", since = "1.0.0")]
690 impl<T: ?Sized> fmt::Pointer for Box<T> {
691 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692 // It's not possible to extract the inner Uniq directly from the Box,
693 // instead we cast it to a *const which aliases the Unique
694 let ptr: *const T = &**self;
695 fmt::Pointer::fmt(&ptr, f)
699 #[stable(feature = "rust1", since = "1.0.0")]
700 impl<T: ?Sized> Deref for Box<T> {
703 fn deref(&self) -> &T {
708 #[stable(feature = "rust1", since = "1.0.0")]
709 impl<T: ?Sized> DerefMut for Box<T> {
710 fn deref_mut(&mut self) -> &mut T {
715 #[unstable(feature = "receiver_trait", issue = "0")]
716 impl<T: ?Sized> Receiver for Box<T> {}
718 #[stable(feature = "rust1", since = "1.0.0")]
719 impl<I: Iterator + ?Sized> Iterator for Box<I> {
721 fn next(&mut self) -> Option<I::Item> {
724 fn size_hint(&self) -> (usize, Option<usize>) {
727 fn nth(&mut self, n: usize) -> Option<I::Item> {
732 #[stable(feature = "rust1", since = "1.0.0")]
733 impl<I: Iterator + Sized> Iterator for Box<I> {
734 fn last(self) -> Option<I::Item> where I: Sized {
739 #[stable(feature = "rust1", since = "1.0.0")]
740 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
741 fn next_back(&mut self) -> Option<I::Item> {
744 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
748 #[stable(feature = "rust1", since = "1.0.0")]
749 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
750 fn len(&self) -> usize {
753 fn is_empty(&self) -> bool {
758 #[stable(feature = "fused", since = "1.26.0")]
759 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
761 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
762 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
763 type Output = <F as FnOnce<A>>::Output;
765 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
766 <F as FnOnce<A>>::call_once(*self, args)
770 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
771 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
772 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
773 <F as FnMut<A>>::call_mut(self, args)
777 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
778 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
779 extern "rust-call" fn call(&self, args: A) -> Self::Output {
780 <F as Fn<A>>::call(self, args)
784 #[unstable(feature = "coerce_unsized", issue = "27732")]
785 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
787 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
788 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
790 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
791 impl<A> FromIterator<A> for Box<[A]> {
792 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
793 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
797 #[stable(feature = "box_slice_clone", since = "1.3.0")]
798 impl<T: Clone> Clone for Box<[T]> {
799 fn clone(&self) -> Self {
800 let mut new = BoxBuilder {
801 data: RawVec::with_capacity(self.len()),
805 let mut target = new.data.ptr();
807 for item in self.iter() {
809 ptr::write(target, item.clone());
810 target = target.offset(1);
816 return unsafe { new.into_box() };
818 // Helper type for responding to panics correctly.
819 struct BoxBuilder<T> {
824 impl<T> BoxBuilder<T> {
825 unsafe fn into_box(self) -> Box<[T]> {
826 let raw = ptr::read(&self.data);
832 impl<T> Drop for BoxBuilder<T> {
834 let mut data = self.data.ptr();
835 let max = unsafe { data.add(self.len) };
840 data = data.offset(1);
848 #[stable(feature = "box_borrow", since = "1.1.0")]
849 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
850 fn borrow(&self) -> &T {
855 #[stable(feature = "box_borrow", since = "1.1.0")]
856 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
857 fn borrow_mut(&mut self) -> &mut T {
862 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
863 impl<T: ?Sized> AsRef<T> for Box<T> {
864 fn as_ref(&self) -> &T {
869 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
870 impl<T: ?Sized> AsMut<T> for Box<T> {
871 fn as_mut(&mut self) -> &mut T {
878 * We could have chosen not to add this impl, and instead have written a
879 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
880 * because Box<T> implements Unpin even when T does not, as a result of
883 * We chose this API instead of the alternative for a few reasons:
884 * - Logically, it is helpful to understand pinning in regard to the
885 * memory region being pointed to. For this reason none of the
886 * standard library pointer types support projecting through a pin
887 * (Box<T> is the only pointer type in std for which this would be
889 * - It is in practice very useful to have Box<T> be unconditionally
890 * Unpin because of trait objects, for which the structural auto
891 * trait functionality does not apply (e.g., Box<dyn Foo> would
892 * otherwise not be Unpin).
894 * Another type with the same semantics as Box but only a conditional
895 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
896 * could have a method to project a Pin<T> from it.
898 #[stable(feature = "pin", since = "1.33.0")]
899 impl<T: ?Sized> Unpin for Box<T> { }
901 #[unstable(feature = "generator_trait", issue = "43122")]
902 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
903 type Yield = G::Yield;
904 type Return = G::Return;
906 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
907 G::resume(Pin::new(&mut *self))
911 #[unstable(feature = "generator_trait", issue = "43122")]
912 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
913 type Yield = G::Yield;
914 type Return = G::Return;
916 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
917 G::resume((*self).as_mut())
921 #[stable(feature = "futures_api", since = "1.36.0")]
922 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
923 type Output = F::Output;
925 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
926 F::poll(Pin::new(&mut *self), cx)