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.
54 //! [dereferencing]: ../../std/ops/trait.Deref.html
55 //! [`Box`]: struct.Box.html
57 #![stable(feature = "rust1", since = "1.0.0")]
61 use core::cmp::Ordering;
62 use core::convert::From;
64 use core::future::Future;
65 use core::hash::{Hash, Hasher};
66 use core::iter::{Iterator, FromIterator, FusedIterator};
67 use core::marker::{Unpin, Unsize};
71 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
73 use core::ptr::{self, NonNull, Unique};
74 use core::task::{LocalWaker, Poll};
77 use crate::raw_vec::RawVec;
78 use crate::str::from_boxed_utf8_unchecked;
80 /// A pointer type for heap allocation.
82 /// See the [module-level documentation](../../std/boxed/index.html) for more.
85 #[stable(feature = "rust1", since = "1.0.0")]
86 pub struct Box<T: ?Sized>(Unique<T>);
89 /// Allocates memory on the heap and then places `x` into it.
91 /// This doesn't actually allocate if `T` is zero-sized.
96 /// let five = Box::new(5);
98 #[stable(feature = "rust1", since = "1.0.0")]
100 pub fn new(x: T) -> Box<T> {
104 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
105 /// `x` will be pinned in memory and unable to be moved.
106 #[stable(feature = "pin", since = "1.33.0")]
108 pub fn pin(x: T) -> Pin<Box<T>> {
113 impl<T: ?Sized> Box<T> {
114 /// Constructs a box from a raw pointer.
116 /// After calling this function, the raw pointer is owned by the
117 /// resulting `Box`. Specifically, the `Box` destructor will call
118 /// the destructor of `T` and free the allocated memory. Since the
119 /// way `Box` allocates and releases memory is unspecified, the
120 /// only valid pointer to pass to this function is the one taken
121 /// from another `Box` via the [`Box::into_raw`] function.
123 /// This function is unsafe because improper use may lead to
124 /// memory problems. For example, a double-free may occur if the
125 /// function is called twice on the same raw pointer.
127 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
132 /// let x = Box::new(5);
133 /// let ptr = Box::into_raw(x);
134 /// let x = unsafe { Box::from_raw(ptr) };
136 #[stable(feature = "box_raw", since = "1.4.0")]
138 pub unsafe fn from_raw(raw: *mut T) -> Self {
139 Box(Unique::new_unchecked(raw))
142 /// Consumes the `Box`, returning a wrapped raw pointer.
144 /// The pointer will be properly aligned and non-null.
146 /// After calling this function, the caller is responsible for the
147 /// memory previously managed by the `Box`. In particular, the
148 /// caller should properly destroy `T` and release the memory. The
149 /// proper way to do so is to convert the raw pointer back into a
150 /// `Box` with the [`Box::from_raw`] function.
152 /// Note: this is an associated function, which means that you have
153 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
154 /// is so that there is no conflict with a method on the inner type.
156 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
161 /// let x = Box::new(5);
162 /// let ptr = Box::into_raw(x);
164 #[stable(feature = "box_raw", since = "1.4.0")]
166 pub fn into_raw(b: Box<T>) -> *mut T {
167 Box::into_raw_non_null(b).as_ptr()
170 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
172 /// After calling this function, the caller is responsible for the
173 /// memory previously managed by the `Box`. In particular, the
174 /// caller should properly destroy `T` and release the memory. The
175 /// proper way to do so is to convert the `NonNull<T>` pointer
176 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
179 /// Note: this is an associated function, which means that you have
180 /// to call it as `Box::into_raw_non_null(b)`
181 /// instead of `b.into_raw_non_null()`. This
182 /// is so that there is no conflict with a method on the inner type.
184 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
189 /// #![feature(box_into_raw_non_null)]
192 /// let x = Box::new(5);
193 /// let ptr = Box::into_raw_non_null(x);
196 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
198 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
199 Box::into_unique(b).into()
202 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
205 pub fn into_unique(b: Box<T>) -> Unique<T> {
211 /// Consumes and leaks the `Box`, returning a mutable reference,
212 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
213 /// `'a`. If the type has only static references, or none at all, then this
214 /// may be chosen to be `'static`.
216 /// This function is mainly useful for data that lives for the remainder of
217 /// the program's life. Dropping the returned reference will cause a memory
218 /// leak. If this is not acceptable, the reference should first be wrapped
219 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
220 /// then be dropped which will properly destroy `T` and release the
221 /// allocated memory.
223 /// Note: this is an associated function, which means that you have
224 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
225 /// is so that there is no conflict with a method on the inner type.
227 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
235 /// let x = Box::new(41);
236 /// let static_ref: &'static mut usize = Box::leak(x);
237 /// *static_ref += 1;
238 /// assert_eq!(*static_ref, 42);
246 /// let x = vec![1, 2, 3].into_boxed_slice();
247 /// let static_ref = Box::leak(x);
248 /// static_ref[0] = 4;
249 /// assert_eq!(*static_ref, [4, 2, 3]);
252 #[stable(feature = "box_leak", since = "1.26.0")]
254 pub fn leak<'a>(b: Box<T>) -> &'a mut T
256 T: 'a // Technically not needed, but kept to be explicit.
258 unsafe { &mut *Box::into_raw(b) }
261 /// Converts a `Box<T>` into a `Pin<Box<T>>`
263 /// This conversion does not allocate on the heap and happens in place.
265 /// This is also available via [`From`].
266 #[unstable(feature = "box_into_pin", issue = "0")]
267 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
268 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
269 // when `T: !Unpin`, so it's safe to pin it directly without any
270 // additional requirements.
271 unsafe { Pin::new_unchecked(boxed) }
275 #[stable(feature = "rust1", since = "1.0.0")]
276 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
278 // FIXME: Do nothing, drop is currently performed by compiler.
282 #[stable(feature = "rust1", since = "1.0.0")]
283 impl<T: Default> Default for Box<T> {
284 /// Creates a `Box<T>`, with the `Default` value for T.
285 fn default() -> Box<T> {
286 box Default::default()
290 #[stable(feature = "rust1", since = "1.0.0")]
291 impl<T> Default for Box<[T]> {
292 fn default() -> Box<[T]> {
293 Box::<[T; 0]>::new([])
297 #[stable(feature = "default_box_extra", since = "1.17.0")]
298 impl Default for Box<str> {
299 fn default() -> Box<str> {
300 unsafe { from_boxed_utf8_unchecked(Default::default()) }
304 #[stable(feature = "rust1", since = "1.0.0")]
305 impl<T: Clone> Clone for Box<T> {
306 /// Returns a new box with a `clone()` of this box's contents.
311 /// let x = Box::new(5);
312 /// let y = x.clone();
316 fn clone(&self) -> Box<T> {
317 box { (**self).clone() }
319 /// Copies `source`'s contents into `self` without creating a new allocation.
324 /// let x = Box::new(5);
325 /// let mut y = Box::new(10);
327 /// y.clone_from(&x);
329 /// assert_eq!(*y, 5);
332 fn clone_from(&mut self, source: &Box<T>) {
333 (**self).clone_from(&(**source));
338 #[stable(feature = "box_slice_clone", since = "1.3.0")]
339 impl Clone for Box<str> {
340 fn clone(&self) -> Self {
341 let len = self.len();
342 let buf = RawVec::with_capacity(len);
344 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
345 from_boxed_utf8_unchecked(buf.into_box())
350 #[stable(feature = "rust1", since = "1.0.0")]
351 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
353 fn eq(&self, other: &Box<T>) -> bool {
354 PartialEq::eq(&**self, &**other)
357 fn ne(&self, other: &Box<T>) -> bool {
358 PartialEq::ne(&**self, &**other)
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
364 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
365 PartialOrd::partial_cmp(&**self, &**other)
368 fn lt(&self, other: &Box<T>) -> bool {
369 PartialOrd::lt(&**self, &**other)
372 fn le(&self, other: &Box<T>) -> bool {
373 PartialOrd::le(&**self, &**other)
376 fn ge(&self, other: &Box<T>) -> bool {
377 PartialOrd::ge(&**self, &**other)
380 fn gt(&self, other: &Box<T>) -> bool {
381 PartialOrd::gt(&**self, &**other)
384 #[stable(feature = "rust1", since = "1.0.0")]
385 impl<T: ?Sized + Ord> Ord for Box<T> {
387 fn cmp(&self, other: &Box<T>) -> Ordering {
388 Ord::cmp(&**self, &**other)
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl<T: ?Sized + Eq> Eq for Box<T> {}
394 #[stable(feature = "rust1", since = "1.0.0")]
395 impl<T: ?Sized + Hash> Hash for Box<T> {
396 fn hash<H: Hasher>(&self, state: &mut H) {
397 (**self).hash(state);
401 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
402 impl<T: ?Sized + Hasher> Hasher for Box<T> {
403 fn finish(&self) -> u64 {
406 fn write(&mut self, bytes: &[u8]) {
407 (**self).write(bytes)
409 fn write_u8(&mut self, i: u8) {
412 fn write_u16(&mut self, i: u16) {
413 (**self).write_u16(i)
415 fn write_u32(&mut self, i: u32) {
416 (**self).write_u32(i)
418 fn write_u64(&mut self, i: u64) {
419 (**self).write_u64(i)
421 fn write_u128(&mut self, i: u128) {
422 (**self).write_u128(i)
424 fn write_usize(&mut self, i: usize) {
425 (**self).write_usize(i)
427 fn write_i8(&mut self, i: i8) {
430 fn write_i16(&mut self, i: i16) {
431 (**self).write_i16(i)
433 fn write_i32(&mut self, i: i32) {
434 (**self).write_i32(i)
436 fn write_i64(&mut self, i: i64) {
437 (**self).write_i64(i)
439 fn write_i128(&mut self, i: i128) {
440 (**self).write_i128(i)
442 fn write_isize(&mut self, i: isize) {
443 (**self).write_isize(i)
447 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
448 impl<T> From<T> for Box<T> {
449 /// Converts a generic type `T` into a `Box<T>`
451 /// The conversion allocates on the heap and moves `t`
452 /// from the stack into it.
457 /// let boxed = Box::new(5);
459 /// assert_eq!(Box::from(x), boxed);
461 fn from(t: T) -> Self {
466 #[stable(feature = "pin", since = "1.33.0")]
467 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
468 /// Converts a `Box<T>` into a `Pin<Box<T>>`
470 /// This conversion does not allocate on the heap and happens in place.
471 fn from(boxed: Box<T>) -> Self {
476 #[stable(feature = "box_from_slice", since = "1.17.0")]
477 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
478 /// Converts a `&[T]` into a `Box<[T]>`
480 /// This conversion allocates on the heap
481 /// and performs a copy of `slice`.
485 /// // create a &[u8] which will be used to create a Box<[u8]>
486 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
487 /// let boxed_slice: Box<[u8]> = Box::from(slice);
489 /// println!("{:?}", boxed_slice);
491 fn from(slice: &'a [T]) -> Box<[T]> {
492 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
493 boxed.copy_from_slice(slice);
498 #[stable(feature = "box_from_slice", since = "1.17.0")]
499 impl<'a> From<&'a str> for Box<str> {
500 /// Converts a `&str` into a `Box<str>`
502 /// This conversion allocates on the heap
503 /// and performs a copy of `s`.
507 /// let boxed: Box<str> = Box::from("hello");
508 /// println!("{}", boxed);
511 fn from(s: &'a str) -> Box<str> {
512 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
516 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
517 impl From<Box<str>> for Box<[u8]> {
518 /// Converts a `Box<str>>` into a `Box<[u8]>`
520 /// This conversion does not allocate on the heap and happens in place.
524 /// // create a Box<str> which will be used to create a Box<[u8]>
525 /// let boxed: Box<str> = Box::from("hello");
526 /// let boxed_str: Box<[u8]> = Box::from(boxed);
528 /// // create a &[u8] which will be used to create a Box<[u8]>
529 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
530 /// let boxed_slice = Box::from(slice);
532 /// assert_eq!(boxed_slice, boxed_str);
535 fn from(s: Box<str>) -> Self {
536 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
542 #[stable(feature = "rust1", since = "1.0.0")]
543 /// Attempt to downcast the box to a concrete type.
548 /// use std::any::Any;
550 /// fn print_if_string(value: Box<dyn Any>) {
551 /// if let Ok(string) = value.downcast::<String>() {
552 /// println!("String ({}): {}", string.len(), string);
557 /// let my_string = "Hello World".to_string();
558 /// print_if_string(Box::new(my_string));
559 /// print_if_string(Box::new(0i8));
562 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
565 let raw: *mut dyn Any = Box::into_raw(self);
566 Ok(Box::from_raw(raw as *mut T))
574 impl Box<dyn Any + Send> {
576 #[stable(feature = "rust1", since = "1.0.0")]
577 /// Attempt to downcast the box to a concrete type.
582 /// use std::any::Any;
584 /// fn print_if_string(value: Box<dyn Any + Send>) {
585 /// if let Ok(string) = value.downcast::<String>() {
586 /// println!("String ({}): {}", string.len(), string);
591 /// let my_string = "Hello World".to_string();
592 /// print_if_string(Box::new(my_string));
593 /// print_if_string(Box::new(0i8));
596 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
597 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
598 // reapply the Send marker
599 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
604 #[stable(feature = "rust1", since = "1.0.0")]
605 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
606 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
607 fmt::Display::fmt(&**self, f)
611 #[stable(feature = "rust1", since = "1.0.0")]
612 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 fmt::Debug::fmt(&**self, f)
618 #[stable(feature = "rust1", since = "1.0.0")]
619 impl<T: ?Sized> fmt::Pointer for Box<T> {
620 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621 // It's not possible to extract the inner Uniq directly from the Box,
622 // instead we cast it to a *const which aliases the Unique
623 let ptr: *const T = &**self;
624 fmt::Pointer::fmt(&ptr, f)
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl<T: ?Sized> Deref for Box<T> {
632 fn deref(&self) -> &T {
637 #[stable(feature = "rust1", since = "1.0.0")]
638 impl<T: ?Sized> DerefMut for Box<T> {
639 fn deref_mut(&mut self) -> &mut T {
644 #[unstable(feature = "receiver_trait", issue = "0")]
645 impl<T: ?Sized> Receiver for Box<T> {}
647 #[stable(feature = "rust1", since = "1.0.0")]
648 impl<I: Iterator + ?Sized> Iterator for Box<I> {
650 fn next(&mut self) -> Option<I::Item> {
653 fn size_hint(&self) -> (usize, Option<usize>) {
656 fn nth(&mut self, n: usize) -> Option<I::Item> {
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
662 fn next_back(&mut self) -> Option<I::Item> {
666 #[stable(feature = "rust1", since = "1.0.0")]
667 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
668 fn len(&self) -> usize {
671 fn is_empty(&self) -> bool {
676 #[stable(feature = "fused", since = "1.26.0")]
677 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
680 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
681 /// closure objects. The idea is that where one would normally store a
682 /// `Box<dyn FnOnce()>` in a data structure, you should use
683 /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except
684 /// that a `FnBox` closure can only be called if it is boxed. (Note
685 /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>`
686 /// closures become directly usable.)
690 /// Here is a snippet of code which creates a hashmap full of boxed
691 /// once closures and then removes them one by one, calling each
692 /// closure as it is removed. Note that the type of the closures
693 /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce()
697 /// #![feature(fnbox)]
699 /// use std::boxed::FnBox;
700 /// use std::collections::HashMap;
702 /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> {
703 /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new();
704 /// map.insert(1, Box::new(|| 22));
705 /// map.insert(2, Box::new(|| 44));
710 /// let mut map = make_map();
711 /// for i in &[1, 2] {
712 /// let f = map.remove(&i).unwrap();
713 /// assert_eq!(f(), i * 22);
718 #[unstable(feature = "fnbox",
719 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
723 fn call_box(self: Box<Self>, args: A) -> Self::Output;
726 #[unstable(feature = "fnbox",
727 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
728 impl<A, F> FnBox<A> for F
731 type Output = F::Output;
733 fn call_box(self: Box<F>, args: A) -> F::Output {
738 #[unstable(feature = "fnbox",
739 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
740 impl<A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + '_> {
743 extern "rust-call" fn call_once(self, args: A) -> R {
748 #[unstable(feature = "fnbox",
749 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
750 impl<A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + '_> {
753 extern "rust-call" fn call_once(self, args: A) -> R {
758 #[unstable(feature = "coerce_unsized", issue = "27732")]
759 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
761 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
762 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
764 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
765 impl<A> FromIterator<A> for Box<[A]> {
766 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
767 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
771 #[stable(feature = "box_slice_clone", since = "1.3.0")]
772 impl<T: Clone> Clone for Box<[T]> {
773 fn clone(&self) -> Self {
774 let mut new = BoxBuilder {
775 data: RawVec::with_capacity(self.len()),
779 let mut target = new.data.ptr();
781 for item in self.iter() {
783 ptr::write(target, item.clone());
784 target = target.offset(1);
790 return unsafe { new.into_box() };
792 // Helper type for responding to panics correctly.
793 struct BoxBuilder<T> {
798 impl<T> BoxBuilder<T> {
799 unsafe fn into_box(self) -> Box<[T]> {
800 let raw = ptr::read(&self.data);
806 impl<T> Drop for BoxBuilder<T> {
808 let mut data = self.data.ptr();
809 let max = unsafe { data.add(self.len) };
814 data = data.offset(1);
822 #[stable(feature = "box_borrow", since = "1.1.0")]
823 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
824 fn borrow(&self) -> &T {
829 #[stable(feature = "box_borrow", since = "1.1.0")]
830 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
831 fn borrow_mut(&mut self) -> &mut T {
836 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
837 impl<T: ?Sized> AsRef<T> for Box<T> {
838 fn as_ref(&self) -> &T {
843 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
844 impl<T: ?Sized> AsMut<T> for Box<T> {
845 fn as_mut(&mut self) -> &mut T {
852 * We could have chosen not to add this impl, and instead have written a
853 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
854 * because Box<T> implements Unpin even when T does not, as a result of
857 * We chose this API instead of the alternative for a few reasons:
858 * - Logically, it is helpful to understand pinning in regard to the
859 * memory region being pointed to. For this reason none of the
860 * standard library pointer types support projecting through a pin
861 * (Box<T> is the only pointer type in std for which this would be
863 * - It is in practice very useful to have Box<T> be unconditionally
864 * Unpin because of trait objects, for which the structural auto
865 * trait functionality does not apply (e.g., Box<dyn Foo> would
866 * otherwise not be Unpin).
868 * Another type with the same semantics as Box but only a conditional
869 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
870 * could have a method to project a Pin<T> from it.
872 #[stable(feature = "pin", since = "1.33.0")]
873 impl<T: ?Sized> Unpin for Box<T> { }
875 #[unstable(feature = "generator_trait", issue = "43122")]
876 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
877 type Yield = G::Yield;
878 type Return = G::Return;
880 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
881 G::resume(Pin::new(&mut *self))
885 #[unstable(feature = "generator_trait", issue = "43122")]
886 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
887 type Yield = G::Yield;
888 type Return = G::Return;
890 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
891 G::resume((*self).as_mut())
895 #[unstable(feature = "futures_api", issue = "50547")]
896 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
897 type Output = F::Output;
899 fn poll(mut self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
900 F::poll(Pin::new(&mut *self), lw)