1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A pointer type for heap allocation.
13 //! `Box<T>`, casually referred to as a 'box', provides the simplest form of
14 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
15 //! drop their contents when they go out of scope.
22 //! let x = Box::new(5);
25 //! Creating a recursive data structure:
30 //! Cons(T, Box<List<T>>),
35 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
36 //! println!("{:?}", list);
40 //! This will print `Cons(1, Cons(2, Nil))`.
42 //! Recursive structures must be boxed, because if the definition of `Cons`
45 //! ```compile_fail,E0072
51 //! It wouldn't work. This is because the size of a `List` depends on how many
52 //! elements are in the list, and so we don't know how much memory to allocate
53 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
54 //! big `Cons` needs to be.
56 #![stable(feature = "rust1", since = "1.0.0")]
60 use core::cmp::Ordering;
61 use core::convert::From;
63 use core::future::{Future, FutureObj, LocalFutureObj, UnsafeFutureObj};
64 use core::hash::{Hash, Hasher};
65 use core::iter::FusedIterator;
66 use core::marker::{Unpin, Unsize};
67 use core::mem::{self, PinMut};
68 use core::ops::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState};
69 use core::ptr::{self, NonNull, Unique};
70 use core::task::{Context, Poll, Spawn, SpawnErrorKind, SpawnObjError};
73 use str::from_boxed_utf8_unchecked;
75 /// A pointer type for heap allocation.
77 /// See the [module-level documentation](../../std/boxed/index.html) for more.
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub struct Box<T: ?Sized>(Unique<T>);
84 /// Allocates memory on the heap and then places `x` into it.
86 /// This doesn't actually allocate if `T` is zero-sized.
91 /// let five = Box::new(5);
93 #[stable(feature = "rust1", since = "1.0.0")]
95 pub fn new(x: T) -> Box<T> {
100 impl<T: ?Sized> Box<T> {
101 /// Constructs a box from a raw pointer.
103 /// After calling this function, the raw pointer is owned by the
104 /// resulting `Box`. Specifically, the `Box` destructor will call
105 /// the destructor of `T` and free the allocated memory. Since the
106 /// way `Box` allocates and releases memory is unspecified, the
107 /// only valid pointer to pass to this function is the one taken
108 /// from another `Box` via the [`Box::into_raw`] function.
110 /// This function is unsafe because improper use may lead to
111 /// memory problems. For example, a double-free may occur if the
112 /// function is called twice on the same raw pointer.
114 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
119 /// let x = Box::new(5);
120 /// let ptr = Box::into_raw(x);
121 /// let x = unsafe { Box::from_raw(ptr) };
123 #[stable(feature = "box_raw", since = "1.4.0")]
125 pub unsafe fn from_raw(raw: *mut T) -> Self {
126 Box(Unique::new_unchecked(raw))
129 /// Consumes the `Box`, returning the wrapped raw pointer.
131 /// After calling this function, the caller is responsible for the
132 /// memory previously managed by the `Box`. In particular, the
133 /// caller should properly destroy `T` and release the memory. The
134 /// proper way to do so is to convert the raw pointer back into a
135 /// `Box` with the [`Box::from_raw`] function.
137 /// Note: this is an associated function, which means that you have
138 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
139 /// is so that there is no conflict with a method on the inner type.
141 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
146 /// let x = Box::new(5);
147 /// let ptr = Box::into_raw(x);
149 #[stable(feature = "box_raw", since = "1.4.0")]
151 pub fn into_raw(b: Box<T>) -> *mut T {
152 Box::into_raw_non_null(b).as_ptr()
155 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
157 /// After calling this function, the caller is responsible for the
158 /// memory previously managed by the `Box`. In particular, the
159 /// caller should properly destroy `T` and release the memory. The
160 /// proper way to do so is to convert the `NonNull<T>` pointer
161 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
164 /// Note: this is an associated function, which means that you have
165 /// to call it as `Box::into_raw_non_null(b)`
166 /// instead of `b.into_raw_non_null()`. This
167 /// is so that there is no conflict with a method on the inner type.
169 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
174 /// #![feature(box_into_raw_non_null)]
177 /// let x = Box::new(5);
178 /// let ptr = Box::into_raw_non_null(x);
181 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
183 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
184 Box::into_unique(b).into()
187 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
190 pub fn into_unique(b: Box<T>) -> Unique<T> {
196 /// Consumes and leaks the `Box`, returning a mutable reference,
197 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
198 /// `'a`. If the type has only static references, or none at all, then this
199 /// may be chosen to be `'static`.
201 /// This function is mainly useful for data that lives for the remainder of
202 /// the program's life. Dropping the returned reference will cause a memory
203 /// leak. If this is not acceptable, the reference should first be wrapped
204 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
205 /// then be dropped which will properly destroy `T` and release the
206 /// allocated memory.
208 /// Note: this is an associated function, which means that you have
209 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
210 /// is so that there is no conflict with a method on the inner type.
212 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
220 /// let x = Box::new(41);
221 /// let static_ref: &'static mut usize = Box::leak(x);
222 /// *static_ref += 1;
223 /// assert_eq!(*static_ref, 42);
231 /// let x = vec![1, 2, 3].into_boxed_slice();
232 /// let static_ref = Box::leak(x);
233 /// static_ref[0] = 4;
234 /// assert_eq!(*static_ref, [4, 2, 3]);
237 #[stable(feature = "box_leak", since = "1.26.0")]
239 pub fn leak<'a>(b: Box<T>) -> &'a mut T
241 T: 'a // Technically not needed, but kept to be explicit.
243 unsafe { &mut *Box::into_raw(b) }
247 #[stable(feature = "rust1", since = "1.0.0")]
248 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
250 // FIXME: Do nothing, drop is currently performed by compiler.
254 #[stable(feature = "rust1", since = "1.0.0")]
255 impl<T: Default> Default for Box<T> {
256 /// Creates a `Box<T>`, with the `Default` value for T.
257 fn default() -> Box<T> {
258 box Default::default()
262 #[stable(feature = "rust1", since = "1.0.0")]
263 impl<T> Default for Box<[T]> {
264 fn default() -> Box<[T]> {
265 Box::<[T; 0]>::new([])
269 #[stable(feature = "default_box_extra", since = "1.17.0")]
270 impl Default for Box<str> {
271 fn default() -> Box<str> {
272 unsafe { from_boxed_utf8_unchecked(Default::default()) }
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<T: Clone> Clone for Box<T> {
278 /// Returns a new box with a `clone()` of this box's contents.
283 /// let x = Box::new(5);
284 /// let y = x.clone();
288 fn clone(&self) -> Box<T> {
289 box { (**self).clone() }
291 /// Copies `source`'s contents into `self` without creating a new allocation.
296 /// let x = Box::new(5);
297 /// let mut y = Box::new(10);
299 /// y.clone_from(&x);
301 /// assert_eq!(*y, 5);
304 fn clone_from(&mut self, source: &Box<T>) {
305 (**self).clone_from(&(**source));
310 #[stable(feature = "box_slice_clone", since = "1.3.0")]
311 impl Clone for Box<str> {
312 fn clone(&self) -> Self {
313 let len = self.len();
314 let buf = RawVec::with_capacity(len);
316 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
317 from_boxed_utf8_unchecked(buf.into_box())
322 #[stable(feature = "rust1", since = "1.0.0")]
323 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
325 fn eq(&self, other: &Box<T>) -> bool {
326 PartialEq::eq(&**self, &**other)
329 fn ne(&self, other: &Box<T>) -> bool {
330 PartialEq::ne(&**self, &**other)
333 #[stable(feature = "rust1", since = "1.0.0")]
334 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
336 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
337 PartialOrd::partial_cmp(&**self, &**other)
340 fn lt(&self, other: &Box<T>) -> bool {
341 PartialOrd::lt(&**self, &**other)
344 fn le(&self, other: &Box<T>) -> bool {
345 PartialOrd::le(&**self, &**other)
348 fn ge(&self, other: &Box<T>) -> bool {
349 PartialOrd::ge(&**self, &**other)
352 fn gt(&self, other: &Box<T>) -> bool {
353 PartialOrd::gt(&**self, &**other)
356 #[stable(feature = "rust1", since = "1.0.0")]
357 impl<T: ?Sized + Ord> Ord for Box<T> {
359 fn cmp(&self, other: &Box<T>) -> Ordering {
360 Ord::cmp(&**self, &**other)
363 #[stable(feature = "rust1", since = "1.0.0")]
364 impl<T: ?Sized + Eq> Eq for Box<T> {}
366 #[stable(feature = "rust1", since = "1.0.0")]
367 impl<T: ?Sized + Hash> Hash for Box<T> {
368 fn hash<H: Hasher>(&self, state: &mut H) {
369 (**self).hash(state);
373 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
374 impl<T: ?Sized + Hasher> Hasher for Box<T> {
375 fn finish(&self) -> u64 {
378 fn write(&mut self, bytes: &[u8]) {
379 (**self).write(bytes)
381 fn write_u8(&mut self, i: u8) {
384 fn write_u16(&mut self, i: u16) {
385 (**self).write_u16(i)
387 fn write_u32(&mut self, i: u32) {
388 (**self).write_u32(i)
390 fn write_u64(&mut self, i: u64) {
391 (**self).write_u64(i)
393 fn write_u128(&mut self, i: u128) {
394 (**self).write_u128(i)
396 fn write_usize(&mut self, i: usize) {
397 (**self).write_usize(i)
399 fn write_i8(&mut self, i: i8) {
402 fn write_i16(&mut self, i: i16) {
403 (**self).write_i16(i)
405 fn write_i32(&mut self, i: i32) {
406 (**self).write_i32(i)
408 fn write_i64(&mut self, i: i64) {
409 (**self).write_i64(i)
411 fn write_i128(&mut self, i: i128) {
412 (**self).write_i128(i)
414 fn write_isize(&mut self, i: isize) {
415 (**self).write_isize(i)
419 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
420 impl<T> From<T> for Box<T> {
421 fn from(t: T) -> Self {
426 #[stable(feature = "box_from_slice", since = "1.17.0")]
427 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
428 fn from(slice: &'a [T]) -> Box<[T]> {
429 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
430 boxed.copy_from_slice(slice);
435 #[stable(feature = "box_from_slice", since = "1.17.0")]
436 impl<'a> From<&'a str> for Box<str> {
438 fn from(s: &'a str) -> Box<str> {
439 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
443 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
444 impl From<Box<str>> for Box<[u8]> {
446 fn from(s: Box<str>) -> Self {
447 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
453 #[stable(feature = "rust1", since = "1.0.0")]
454 /// Attempt to downcast the box to a concrete type.
459 /// use std::any::Any;
461 /// fn print_if_string(value: Box<Any>) {
462 /// if let Ok(string) = value.downcast::<String>() {
463 /// println!("String ({}): {}", string.len(), string);
468 /// let my_string = "Hello World".to_string();
469 /// print_if_string(Box::new(my_string));
470 /// print_if_string(Box::new(0i8));
473 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
476 let raw: *mut dyn Any = Box::into_raw(self);
477 Ok(Box::from_raw(raw as *mut T))
485 impl Box<dyn Any + Send> {
487 #[stable(feature = "rust1", since = "1.0.0")]
488 /// Attempt to downcast the box to a concrete type.
493 /// use std::any::Any;
495 /// fn print_if_string(value: Box<Any + Send>) {
496 /// if let Ok(string) = value.downcast::<String>() {
497 /// println!("String ({}): {}", string.len(), string);
502 /// let my_string = "Hello World".to_string();
503 /// print_if_string(Box::new(my_string));
504 /// print_if_string(Box::new(0i8));
507 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
508 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
509 // reapply the Send marker
510 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
515 #[stable(feature = "rust1", since = "1.0.0")]
516 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
517 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
518 fmt::Display::fmt(&**self, f)
522 #[stable(feature = "rust1", since = "1.0.0")]
523 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
524 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
525 fmt::Debug::fmt(&**self, f)
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl<T: ?Sized> fmt::Pointer for Box<T> {
531 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
532 // It's not possible to extract the inner Uniq directly from the Box,
533 // instead we cast it to a *const which aliases the Unique
534 let ptr: *const T = &**self;
535 fmt::Pointer::fmt(&ptr, f)
539 #[stable(feature = "rust1", since = "1.0.0")]
540 impl<T: ?Sized> Deref for Box<T> {
543 fn deref(&self) -> &T {
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl<T: ?Sized> DerefMut for Box<T> {
550 fn deref_mut(&mut self) -> &mut T {
555 #[stable(feature = "rust1", since = "1.0.0")]
556 impl<I: Iterator + ?Sized> Iterator for Box<I> {
558 fn next(&mut self) -> Option<I::Item> {
561 fn size_hint(&self) -> (usize, Option<usize>) {
564 fn nth(&mut self, n: usize) -> Option<I::Item> {
568 #[stable(feature = "rust1", since = "1.0.0")]
569 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
570 fn next_back(&mut self) -> Option<I::Item> {
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
576 fn len(&self) -> usize {
579 fn is_empty(&self) -> bool {
584 #[stable(feature = "fused", since = "1.26.0")]
585 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
588 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
589 /// closure objects. The idea is that where one would normally store a
590 /// `Box<FnOnce()>` in a data structure, you should use
591 /// `Box<FnBox()>`. The two traits behave essentially the same, except
592 /// that a `FnBox` closure can only be called if it is boxed. (Note
593 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
594 /// closures become directly usable.)
598 /// Here is a snippet of code which creates a hashmap full of boxed
599 /// once closures and then removes them one by one, calling each
600 /// closure as it is removed. Note that the type of the closures
601 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
605 /// #![feature(fnbox)]
607 /// use std::boxed::FnBox;
608 /// use std::collections::HashMap;
610 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
611 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
612 /// map.insert(1, Box::new(|| 22));
613 /// map.insert(2, Box::new(|| 44));
618 /// let mut map = make_map();
619 /// for i in &[1, 2] {
620 /// let f = map.remove(&i).unwrap();
621 /// assert_eq!(f(), i * 22);
626 #[unstable(feature = "fnbox",
627 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
631 fn call_box(self: Box<Self>, args: A) -> Self::Output;
634 #[unstable(feature = "fnbox",
635 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
636 impl<A, F> FnBox<A> for F
639 type Output = F::Output;
641 fn call_box(self: Box<F>, args: A) -> F::Output {
646 #[unstable(feature = "fnbox",
647 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
648 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> {
651 extern "rust-call" fn call_once(self, args: A) -> R {
656 #[unstable(feature = "fnbox",
657 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
658 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> {
661 extern "rust-call" fn call_once(self, args: A) -> R {
666 #[unstable(feature = "coerce_unsized", issue = "27732")]
667 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
669 #[stable(feature = "box_slice_clone", since = "1.3.0")]
670 impl<T: Clone> Clone for Box<[T]> {
671 fn clone(&self) -> Self {
672 let mut new = BoxBuilder {
673 data: RawVec::with_capacity(self.len()),
677 let mut target = new.data.ptr();
679 for item in self.iter() {
681 ptr::write(target, item.clone());
682 target = target.offset(1);
688 return unsafe { new.into_box() };
690 // Helper type for responding to panics correctly.
691 struct BoxBuilder<T> {
696 impl<T> BoxBuilder<T> {
697 unsafe fn into_box(self) -> Box<[T]> {
698 let raw = ptr::read(&self.data);
704 impl<T> Drop for BoxBuilder<T> {
706 let mut data = self.data.ptr();
707 let max = unsafe { data.offset(self.len as isize) };
712 data = data.offset(1);
720 #[stable(feature = "box_borrow", since = "1.1.0")]
721 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
722 fn borrow(&self) -> &T {
727 #[stable(feature = "box_borrow", since = "1.1.0")]
728 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
729 fn borrow_mut(&mut self) -> &mut T {
734 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
735 impl<T: ?Sized> AsRef<T> for Box<T> {
736 fn as_ref(&self) -> &T {
741 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
742 impl<T: ?Sized> AsMut<T> for Box<T> {
743 fn as_mut(&mut self) -> &mut T {
748 #[unstable(feature = "generator_trait", issue = "43122")]
749 impl<T> Generator for Box<T>
750 where T: Generator + ?Sized
752 type Yield = T::Yield;
753 type Return = T::Return;
754 unsafe fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> {
759 /// A pinned, heap allocated reference.
760 #[unstable(feature = "pin", issue = "49150")]
763 pub struct PinBox<T: ?Sized> {
767 #[unstable(feature = "pin", issue = "49150")]
769 /// Allocate memory on the heap, move the data into it and pin it.
770 #[unstable(feature = "pin", issue = "49150")]
771 pub fn new(data: T) -> PinBox<T> {
772 PinBox { inner: Box::new(data) }
776 #[unstable(feature = "pin", issue = "49150")]
777 impl<T: ?Sized> PinBox<T> {
778 /// Get a pinned reference to the data in this PinBox.
780 pub fn as_pin_mut<'a>(&'a mut self) -> PinMut<'a, T> {
781 unsafe { PinMut::new_unchecked(&mut *self.inner) }
784 /// Constructs a `PinBox` from a raw pointer.
786 /// After calling this function, the raw pointer is owned by the
787 /// resulting `PinBox`. Specifically, the `PinBox` destructor will call
788 /// the destructor of `T` and free the allocated memory. Since the
789 /// way `PinBox` allocates and releases memory is unspecified, the
790 /// only valid pointer to pass to this function is the one taken
791 /// from another `PinBox` via the [`PinBox::into_raw`] function.
793 /// This function is unsafe because improper use may lead to
794 /// memory problems. For example, a double-free may occur if the
795 /// function is called twice on the same raw pointer.
797 /// [`PinBox::into_raw`]: struct.PinBox.html#method.into_raw
803 /// use std::boxed::PinBox;
804 /// let x = PinBox::new(5);
805 /// let ptr = PinBox::into_raw(x);
806 /// let x = unsafe { PinBox::from_raw(ptr) };
809 pub unsafe fn from_raw(raw: *mut T) -> Self {
810 PinBox { inner: Box::from_raw(raw) }
813 /// Consumes the `PinBox`, returning the wrapped raw pointer.
815 /// After calling this function, the caller is responsible for the
816 /// memory previously managed by the `PinBox`. In particular, the
817 /// caller should properly destroy `T` and release the memory. The
818 /// proper way to do so is to convert the raw pointer back into a
819 /// `PinBox` with the [`PinBox::from_raw`] function.
821 /// Note: this is an associated function, which means that you have
822 /// to call it as `PinBox::into_raw(b)` instead of `b.into_raw()`. This
823 /// is so that there is no conflict with a method on the inner type.
825 /// [`PinBox::from_raw`]: struct.PinBox.html#method.from_raw
831 /// use std::boxed::PinBox;
832 /// let x = PinBox::new(5);
833 /// let ptr = PinBox::into_raw(x);
836 pub fn into_raw(b: PinBox<T>) -> *mut T {
837 Box::into_raw(b.inner)
840 /// Get a mutable reference to the data inside this PinBox.
842 /// This function is unsafe. Users must guarantee that the data is never
843 /// moved out of this reference.
845 pub unsafe fn get_mut<'a>(this: &'a mut PinBox<T>) -> &'a mut T {
849 /// Convert this PinBox into an unpinned Box.
851 /// This function is unsafe. Users must guarantee that the data is never
852 /// moved out of the box.
854 pub unsafe fn unpin(this: PinBox<T>) -> Box<T> {
859 #[unstable(feature = "pin", issue = "49150")]
860 impl<T: ?Sized> From<Box<T>> for PinBox<T> {
861 fn from(boxed: Box<T>) -> PinBox<T> {
862 PinBox { inner: boxed }
866 #[unstable(feature = "pin", issue = "49150")]
867 impl<T: Unpin + ?Sized> From<PinBox<T>> for Box<T> {
868 fn from(pinned: PinBox<T>) -> Box<T> {
873 #[unstable(feature = "pin", issue = "49150")]
874 impl<T: ?Sized> Deref for PinBox<T> {
877 fn deref(&self) -> &T {
882 #[unstable(feature = "pin", issue = "49150")]
883 impl<T: Unpin + ?Sized> DerefMut for PinBox<T> {
884 fn deref_mut(&mut self) -> &mut T {
889 #[unstable(feature = "pin", issue = "49150")]
890 impl<T: fmt::Display + ?Sized> fmt::Display for PinBox<T> {
891 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
892 fmt::Display::fmt(&*self.inner, f)
896 #[unstable(feature = "pin", issue = "49150")]
897 impl<T: fmt::Debug + ?Sized> fmt::Debug for PinBox<T> {
898 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
899 fmt::Debug::fmt(&*self.inner, f)
903 #[unstable(feature = "pin", issue = "49150")]
904 impl<T: ?Sized> fmt::Pointer for PinBox<T> {
905 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
906 // It's not possible to extract the inner Uniq directly from the Box,
907 // instead we cast it to a *const which aliases the Unique
908 let ptr: *const T = &*self.inner;
909 fmt::Pointer::fmt(&ptr, f)
913 #[unstable(feature = "pin", issue = "49150")]
914 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinBox<U>> for PinBox<T> {}
916 #[unstable(feature = "pin", issue = "49150")]
917 impl<T: ?Sized> Unpin for PinBox<T> {}
919 #[unstable(feature = "futures_api", issue = "50547")]
920 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
921 type Output = F::Output;
923 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
924 PinMut::new(&mut **self).poll(cx)
928 #[unstable(feature = "futures_api", issue = "50547")]
929 impl<F: ?Sized + Future> Future for PinBox<F> {
930 type Output = F::Output;
932 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
933 self.as_pin_mut().poll(cx)
937 #[unstable(feature = "futures_api", issue = "50547")]
938 unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Box<F>
939 where F: Future<Output = T> + 'a
941 fn into_raw(self) -> *mut () {
942 Box::into_raw(self) as *mut ()
945 unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
946 let ptr = ptr as *mut F;
947 let pin: PinMut<F> = PinMut::new_unchecked(&mut *ptr);
951 unsafe fn drop(ptr: *mut ()) {
952 drop(Box::from_raw(ptr as *mut F))
956 #[unstable(feature = "futures_api", issue = "50547")]
957 unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for PinBox<F>
958 where F: Future<Output = T> + 'a
960 fn into_raw(self) -> *mut () {
961 PinBox::into_raw(self) as *mut ()
964 unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
965 let ptr = ptr as *mut F;
966 let pin: PinMut<F> = PinMut::new_unchecked(&mut *ptr);
970 unsafe fn drop(ptr: *mut ()) {
971 drop(PinBox::from_raw(ptr as *mut F))
975 #[unstable(feature = "futures_api", issue = "50547")]
976 impl<Sp> Spawn for Box<Sp>
977 where Sp: Spawn + ?Sized
981 future: FutureObj<'static, ()>,
982 ) -> Result<(), SpawnObjError> {
983 (**self).spawn_obj(future)
986 fn status(&self) -> Result<(), SpawnErrorKind> {
991 #[unstable(feature = "futures_api", issue = "50547")]
992 impl<'a, F: Future<Output = ()> + Send + 'a> From<PinBox<F>> for FutureObj<'a, ()> {
993 fn from(boxed: PinBox<F>) -> Self {
994 FutureObj::new(boxed)
998 #[unstable(feature = "futures_api", issue = "50547")]
999 impl<'a, F: Future<Output = ()> + Send + 'a> From<Box<F>> for FutureObj<'a, ()> {
1000 fn from(boxed: Box<F>) -> Self {
1001 FutureObj::new(boxed)
1005 #[unstable(feature = "futures_api", issue = "50547")]
1006 impl<'a, F: Future<Output = ()> + 'a> From<PinBox<F>> for LocalFutureObj<'a, ()> {
1007 fn from(boxed: PinBox<F>) -> Self {
1008 LocalFutureObj::new(boxed)
1012 #[unstable(feature = "futures_api", issue = "50547")]
1013 impl<'a, F: Future<Output = ()> + 'a> From<Box<F>> for LocalFutureObj<'a, ()> {
1014 fn from(boxed: Box<F>) -> Self {
1015 LocalFutureObj::new(boxed)