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
;
62 use core
::future
::Future
;
63 use core
::hash
::{Hash, Hasher}
;
64 use core
::iter
::FusedIterator
;
65 use core
::marker
::{Unpin, Unsize}
;
66 use core
::mem
::{self, PinMut}
;
67 use core
::ops
::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState}
;
68 use core
::ptr
::{self, NonNull, Unique}
;
69 use core
::task
::{Context, Poll, UnsafeTask, TaskObj}
;
70 use core
::convert
::From
;
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`. Here, the lifetime `'a` may be chosen to be `'static`.
199 /// This function is mainly useful for data that lives for the remainder of
200 /// the program's life. Dropping the returned reference will cause a memory
201 /// leak. If this is not acceptable, the reference should first be wrapped
202 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
203 /// then be dropped which will properly destroy `T` and release the
204 /// allocated memory.
206 /// Note: this is an associated function, which means that you have
207 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
208 /// is so that there is no conflict with a method on the inner type.
210 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
218 /// let x = Box::new(41);
219 /// let static_ref: &'static mut usize = Box::leak(x);
220 /// *static_ref += 1;
221 /// assert_eq!(*static_ref, 42);
229 /// let x = vec![1, 2, 3].into_boxed_slice();
230 /// let static_ref = Box::leak(x);
231 /// static_ref[0] = 4;
232 /// assert_eq!(*static_ref, [4, 2, 3]);
235 #[stable(feature = "box_leak", since = "1.26.0")]
237 pub fn leak
<'a
>(b
: Box
<T
>) -> &'a
mut T
239 T
: 'a
// Technically not needed, but kept to be explicit.
241 unsafe { &mut *Box::into_raw(b) }
245 #[stable(feature = "rust1", since = "1.0.0")]
246 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
248 // FIXME: Do nothing, drop is currently performed by compiler.
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<T
: Default
> Default
for Box
<T
> {
254 /// Creates a `Box<T>`, with the `Default` value for T.
255 fn default() -> Box
<T
> {
256 box Default
::default()
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<T
> Default
for Box
<[T
]> {
262 fn default() -> Box
<[T
]> {
263 Box
::<[T
; 0]>::new([])
267 #[stable(feature = "default_box_extra", since = "1.17.0")]
268 impl Default
for Box
<str> {
269 fn default() -> Box
<str> {
270 unsafe { from_boxed_utf8_unchecked(Default::default()) }
274 #[stable(feature = "rust1", since = "1.0.0")]
275 impl<T
: Clone
> Clone
for Box
<T
> {
276 /// Returns a new box with a `clone()` of this box's contents.
281 /// let x = Box::new(5);
282 /// let y = x.clone();
286 fn clone(&self) -> Box
<T
> {
287 box { (**self).clone() }
289 /// Copies `source`'s contents into `self` without creating a new allocation.
294 /// let x = Box::new(5);
295 /// let mut y = Box::new(10);
297 /// y.clone_from(&x);
299 /// assert_eq!(*y, 5);
302 fn clone_from(&mut self, source
: &Box
<T
>) {
303 (**self).clone_from(&(**source
));
308 #[stable(feature = "box_slice_clone", since = "1.3.0")]
309 impl Clone
for Box
<str> {
310 fn clone(&self) -> Self {
311 let len
= self.len();
312 let buf
= RawVec
::with_capacity(len
);
314 ptr
::copy_nonoverlapping(self.as_ptr(), buf
.ptr(), len
);
315 from_boxed_utf8_unchecked(buf
.into_box())
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl<T
: ?Sized
+ PartialEq
> PartialEq
for Box
<T
> {
323 fn eq(&self, other
: &Box
<T
>) -> bool
{
324 PartialEq
::eq(&**self, &**other
)
327 fn ne(&self, other
: &Box
<T
>) -> bool
{
328 PartialEq
::ne(&**self, &**other
)
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<T
: ?Sized
+ PartialOrd
> PartialOrd
for Box
<T
> {
334 fn partial_cmp(&self, other
: &Box
<T
>) -> Option
<Ordering
> {
335 PartialOrd
::partial_cmp(&**self, &**other
)
338 fn lt(&self, other
: &Box
<T
>) -> bool
{
339 PartialOrd
::lt(&**self, &**other
)
342 fn le(&self, other
: &Box
<T
>) -> bool
{
343 PartialOrd
::le(&**self, &**other
)
346 fn ge(&self, other
: &Box
<T
>) -> bool
{
347 PartialOrd
::ge(&**self, &**other
)
350 fn gt(&self, other
: &Box
<T
>) -> bool
{
351 PartialOrd
::gt(&**self, &**other
)
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<T
: ?Sized
+ Ord
> Ord
for Box
<T
> {
357 fn cmp(&self, other
: &Box
<T
>) -> Ordering
{
358 Ord
::cmp(&**self, &**other
)
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T
: ?Sized
+ Eq
> Eq
for Box
<T
> {}
364 #[stable(feature = "rust1", since = "1.0.0")]
365 impl<T
: ?Sized
+ Hash
> Hash
for Box
<T
> {
366 fn hash
<H
: Hasher
>(&self, state
: &mut H
) {
367 (**self).hash(state
);
371 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
372 impl<T
: ?Sized
+ Hasher
> Hasher
for Box
<T
> {
373 fn finish(&self) -> u64 {
376 fn write(&mut self, bytes
: &[u8]) {
377 (**self).write(bytes
)
379 fn write_u8(&mut self, i
: u8) {
382 fn write_u16(&mut self, i
: u16) {
383 (**self).write_u16(i
)
385 fn write_u32(&mut self, i
: u32) {
386 (**self).write_u32(i
)
388 fn write_u64(&mut self, i
: u64) {
389 (**self).write_u64(i
)
391 fn write_u128(&mut self, i
: u128
) {
392 (**self).write_u128(i
)
394 fn write_usize(&mut self, i
: usize) {
395 (**self).write_usize(i
)
397 fn write_i8(&mut self, i
: i8) {
400 fn write_i16(&mut self, i
: i16) {
401 (**self).write_i16(i
)
403 fn write_i32(&mut self, i
: i32) {
404 (**self).write_i32(i
)
406 fn write_i64(&mut self, i
: i64) {
407 (**self).write_i64(i
)
409 fn write_i128(&mut self, i
: i128
) {
410 (**self).write_i128(i
)
412 fn write_isize(&mut self, i
: isize) {
413 (**self).write_isize(i
)
417 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
418 impl<T
> From
<T
> for Box
<T
> {
419 fn from(t
: T
) -> Self {
424 #[stable(feature = "box_from_slice", since = "1.17.0")]
425 impl<'a
, T
: Copy
> From
<&'a
[T
]> for Box
<[T
]> {
426 fn from(slice
: &'a
[T
]) -> Box
<[T
]> {
427 let mut boxed
= unsafe { RawVec::with_capacity(slice.len()).into_box() }
;
428 boxed
.copy_from_slice(slice
);
433 #[stable(feature = "box_from_slice", since = "1.17.0")]
434 impl<'a
> From
<&'a
str> for Box
<str> {
436 fn from(s
: &'a
str) -> Box
<str> {
437 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
441 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
442 impl From
<Box
<str>> for Box
<[u8]> {
444 fn from(s
: Box
<str>) -> Self {
445 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
451 #[stable(feature = "rust1", since = "1.0.0")]
452 /// Attempt to downcast the box to a concrete type.
457 /// use std::any::Any;
459 /// fn print_if_string(value: Box<Any>) {
460 /// if let Ok(string) = value.downcast::<String>() {
461 /// println!("String ({}): {}", string.len(), string);
466 /// let my_string = "Hello World".to_string();
467 /// print_if_string(Box::new(my_string));
468 /// print_if_string(Box::new(0i8));
471 pub fn downcast
<T
: Any
>(self) -> Result
<Box
<T
>, Box
<Any
>> {
474 let raw
: *mut Any
= Box
::into_raw(self);
475 Ok(Box
::from_raw(raw
as *mut T
))
483 impl Box
<Any
+ Send
> {
485 #[stable(feature = "rust1", since = "1.0.0")]
486 /// Attempt to downcast the box to a concrete type.
491 /// use std::any::Any;
493 /// fn print_if_string(value: Box<Any + Send>) {
494 /// if let Ok(string) = value.downcast::<String>() {
495 /// println!("String ({}): {}", string.len(), string);
500 /// let my_string = "Hello World".to_string();
501 /// print_if_string(Box::new(my_string));
502 /// print_if_string(Box::new(0i8));
505 pub fn downcast
<T
: Any
>(self) -> Result
<Box
<T
>, Box
<Any
+ Send
>> {
506 <Box
<Any
>>::downcast(self).map_err(|s
| unsafe {
507 // reapply the Send marker
508 Box
::from_raw(Box
::into_raw(s
) as *mut (Any
+ Send
))
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<T
: fmt
::Display
+ ?Sized
> fmt
::Display
for Box
<T
> {
515 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
516 fmt
::Display
::fmt(&**self, f
)
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl<T
: fmt
::Debug
+ ?Sized
> fmt
::Debug
for Box
<T
> {
522 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
523 fmt
::Debug
::fmt(&**self, f
)
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl<T
: ?Sized
> fmt
::Pointer
for Box
<T
> {
529 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
530 // It's not possible to extract the inner Uniq directly from the Box,
531 // instead we cast it to a *const which aliases the Unique
532 let ptr
: *const T
= &**self;
533 fmt
::Pointer
::fmt(&ptr
, f
)
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<T
: ?Sized
> Deref
for Box
<T
> {
541 fn deref(&self) -> &T
{
546 #[stable(feature = "rust1", since = "1.0.0")]
547 impl<T
: ?Sized
> DerefMut
for Box
<T
> {
548 fn deref_mut(&mut self) -> &mut T
{
553 #[stable(feature = "rust1", since = "1.0.0")]
554 impl<I
: Iterator
+ ?Sized
> Iterator
for Box
<I
> {
556 fn next(&mut self) -> Option
<I
::Item
> {
559 fn size_hint(&self) -> (usize, Option
<usize>) {
562 fn nth(&mut self, n
: usize) -> Option
<I
::Item
> {
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<I
: DoubleEndedIterator
+ ?Sized
> DoubleEndedIterator
for Box
<I
> {
568 fn next_back(&mut self) -> Option
<I
::Item
> {
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<I
: ExactSizeIterator
+ ?Sized
> ExactSizeIterator
for Box
<I
> {
574 fn len(&self) -> usize {
577 fn is_empty(&self) -> bool
{
582 #[stable(feature = "fused", since = "1.26.0")]
583 impl<I
: FusedIterator
+ ?Sized
> FusedIterator
for Box
<I
> {}
586 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
587 /// closure objects. The idea is that where one would normally store a
588 /// `Box<FnOnce()>` in a data structure, you should use
589 /// `Box<FnBox()>`. The two traits behave essentially the same, except
590 /// that a `FnBox` closure can only be called if it is boxed. (Note
591 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
592 /// closures become directly usable.)
596 /// Here is a snippet of code which creates a hashmap full of boxed
597 /// once closures and then removes them one by one, calling each
598 /// closure as it is removed. Note that the type of the closures
599 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
603 /// #![feature(fnbox)]
605 /// use std::boxed::FnBox;
606 /// use std::collections::HashMap;
608 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
609 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
610 /// map.insert(1, Box::new(|| 22));
611 /// map.insert(2, Box::new(|| 44));
616 /// let mut map = make_map();
617 /// for i in &[1, 2] {
618 /// let f = map.remove(&i).unwrap();
619 /// assert_eq!(f(), i * 22);
624 #[unstable(feature = "fnbox",
625 reason
= "will be deprecated if and when `Box<FnOnce>` becomes usable", issue
= "28796")]
629 fn call_box(self: Box
<Self>, args
: A
) -> Self::Output
;
632 #[unstable(feature = "fnbox",
633 reason
= "will be deprecated if and when `Box<FnOnce>` becomes usable", issue
= "28796")]
634 impl<A
, F
> FnBox
<A
> for F
637 type Output
= F
::Output
;
639 fn call_box(self: Box
<F
>, args
: A
) -> F
::Output
{
644 #[unstable(feature = "fnbox",
645 reason
= "will be deprecated if and when `Box<FnOnce>` becomes usable", issue
= "28796")]
646 impl<'a
, A
, R
> FnOnce
<A
> for Box
<FnBox
<A
, Output
= R
> + 'a
> {
649 extern "rust-call" fn call_once(self, args
: A
) -> R
{
654 #[unstable(feature = "fnbox",
655 reason
= "will be deprecated if and when `Box<FnOnce>` becomes usable", issue
= "28796")]
656 impl<'a
, A
, R
> FnOnce
<A
> for Box
<FnBox
<A
, Output
= R
> + Send
+ 'a
> {
659 extern "rust-call" fn call_once(self, args
: A
) -> R
{
664 #[unstable(feature = "coerce_unsized", issue = "27732")]
665 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<Box
<U
>> for Box
<T
> {}
667 #[stable(feature = "box_slice_clone", since = "1.3.0")]
668 impl<T
: Clone
> Clone
for Box
<[T
]> {
669 fn clone(&self) -> Self {
670 let mut new
= BoxBuilder
{
671 data
: RawVec
::with_capacity(self.len()),
675 let mut target
= new
.data
.ptr();
677 for item
in self.iter() {
679 ptr
::write(target
, item
.clone());
680 target
= target
.offset(1);
686 return unsafe { new.into_box() }
;
688 // Helper type for responding to panics correctly.
689 struct BoxBuilder
<T
> {
694 impl<T
> BoxBuilder
<T
> {
695 unsafe fn into_box(self) -> Box
<[T
]> {
696 let raw
= ptr
::read(&self.data
);
702 impl<T
> Drop
for BoxBuilder
<T
> {
704 let mut data
= self.data
.ptr();
705 let max
= unsafe { data.offset(self.len as isize) }
;
710 data
= data
.offset(1);
718 #[stable(feature = "box_borrow", since = "1.1.0")]
719 impl<T
: ?Sized
> borrow
::Borrow
<T
> for Box
<T
> {
720 fn borrow(&self) -> &T
{
725 #[stable(feature = "box_borrow", since = "1.1.0")]
726 impl<T
: ?Sized
> borrow
::BorrowMut
<T
> for Box
<T
> {
727 fn borrow_mut(&mut self) -> &mut T
{
732 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
733 impl<T
: ?Sized
> AsRef
<T
> for Box
<T
> {
734 fn as_ref(&self) -> &T
{
739 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
740 impl<T
: ?Sized
> AsMut
<T
> for Box
<T
> {
741 fn as_mut(&mut self) -> &mut T
{
746 #[unstable(feature = "generator_trait", issue = "43122")]
747 impl<T
> Generator
for Box
<T
>
748 where T
: Generator
+ ?Sized
750 type Yield
= T
::Yield
;
751 type Return
= T
::Return
;
752 unsafe fn resume(&mut self) -> GeneratorState
<Self::Yield
, Self::Return
> {
757 /// A pinned, heap allocated reference.
758 #[unstable(feature = "pin", issue = "49150")]
761 pub struct PinBox
<T
: ?Sized
> {
765 #[unstable(feature = "pin", issue = "49150")]
767 /// Allocate memory on the heap, move the data into it and pin it.
768 #[unstable(feature = "pin", issue = "49150")]
769 pub fn new(data
: T
) -> PinBox
<T
> {
770 PinBox { inner: Box::new(data) }
774 #[unstable(feature = "pin", issue = "49150")]
775 impl<T
: ?Sized
> PinBox
<T
> {
776 /// Get a pinned reference to the data in this PinBox.
778 pub fn as_pin_mut
<'a
>(&'a
mut self) -> PinMut
<'a
, T
> {
779 unsafe { PinMut::new_unchecked(&mut *self.inner) }
782 /// Constructs a `PinBox` from a raw pointer.
784 /// After calling this function, the raw pointer is owned by the
785 /// resulting `PinBox`. Specifically, the `PinBox` destructor will call
786 /// the destructor of `T` and free the allocated memory. Since the
787 /// way `PinBox` allocates and releases memory is unspecified, the
788 /// only valid pointer to pass to this function is the one taken
789 /// from another `PinBox` via the [`PinBox::into_raw`] function.
791 /// This function is unsafe because improper use may lead to
792 /// memory problems. For example, a double-free may occur if the
793 /// function is called twice on the same raw pointer.
795 /// [`PinBox::into_raw`]: struct.PinBox.html#method.into_raw
801 /// use std::boxed::PinBox;
802 /// let x = PinBox::new(5);
803 /// let ptr = PinBox::into_raw(x);
804 /// let x = unsafe { PinBox::from_raw(ptr) };
807 pub unsafe fn from_raw(raw
: *mut T
) -> Self {
808 PinBox { inner: Box::from_raw(raw) }
811 /// Consumes the `PinBox`, returning the wrapped raw pointer.
813 /// After calling this function, the caller is responsible for the
814 /// memory previously managed by the `PinBox`. In particular, the
815 /// caller should properly destroy `T` and release the memory. The
816 /// proper way to do so is to convert the raw pointer back into a
817 /// `PinBox` with the [`PinBox::from_raw`] function.
819 /// Note: this is an associated function, which means that you have
820 /// to call it as `PinBox::into_raw(b)` instead of `b.into_raw()`. This
821 /// is so that there is no conflict with a method on the inner type.
823 /// [`PinBox::from_raw`]: struct.PinBox.html#method.from_raw
829 /// use std::boxed::PinBox;
830 /// let x = PinBox::new(5);
831 /// let ptr = PinBox::into_raw(x);
834 pub fn into_raw(b
: PinBox
<T
>) -> *mut T
{
835 Box
::into_raw(b
.inner
)
838 /// Get a mutable reference to the data inside this PinBox.
840 /// This function is unsafe. Users must guarantee that the data is never
841 /// moved out of this reference.
843 pub unsafe fn get_mut
<'a
>(this
: &'a
mut PinBox
<T
>) -> &'a
mut T
{
847 /// Convert this PinBox into an unpinned Box.
849 /// This function is unsafe. Users must guarantee that the data is never
850 /// moved out of the box.
852 pub unsafe fn unpin(this
: PinBox
<T
>) -> Box
<T
> {
857 #[unstable(feature = "pin", issue = "49150")]
858 impl<T
: ?Sized
> From
<Box
<T
>> for PinBox
<T
> {
859 fn from(boxed
: Box
<T
>) -> PinBox
<T
> {
860 PinBox { inner: boxed }
864 #[unstable(feature = "pin", issue = "49150")]
865 impl<T
: Unpin
+ ?Sized
> From
<PinBox
<T
>> for Box
<T
> {
866 fn from(pinned
: PinBox
<T
>) -> Box
<T
> {
871 #[unstable(feature = "pin", issue = "49150")]
872 impl<T
: ?Sized
> Deref
for PinBox
<T
> {
875 fn deref(&self) -> &T
{
880 #[unstable(feature = "pin", issue = "49150")]
881 impl<T
: Unpin
+ ?Sized
> DerefMut
for PinBox
<T
> {
882 fn deref_mut(&mut self) -> &mut T
{
887 #[unstable(feature = "pin", issue = "49150")]
888 impl<T
: fmt
::Display
+ ?Sized
> fmt
::Display
for PinBox
<T
> {
889 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
890 fmt
::Display
::fmt(&*self.inner
, f
)
894 #[unstable(feature = "pin", issue = "49150")]
895 impl<T
: fmt
::Debug
+ ?Sized
> fmt
::Debug
for PinBox
<T
> {
896 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
897 fmt
::Debug
::fmt(&*self.inner
, f
)
901 #[unstable(feature = "pin", issue = "49150")]
902 impl<T
: ?Sized
> fmt
::Pointer
for PinBox
<T
> {
903 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
904 // It's not possible to extract the inner Uniq directly from the Box,
905 // instead we cast it to a *const which aliases the Unique
906 let ptr
: *const T
= &*self.inner
;
907 fmt
::Pointer
::fmt(&ptr
, f
)
911 #[unstable(feature = "pin", issue = "49150")]
912 impl<T
: ?Sized
+ Unsize
<U
>, U
: ?Sized
> CoerceUnsized
<PinBox
<U
>> for PinBox
<T
> {}
914 #[unstable(feature = "pin", issue = "49150")]
915 impl<T
: ?Sized
> Unpin
for PinBox
<T
> {}
917 #[unstable(feature = "futures_api", issue = "50547")]
918 impl<'a
, F
: ?Sized
+ Future
+ Unpin
> Future
for Box
<F
> {
919 type Output
= F
::Output
;
921 fn poll(mut self: PinMut
<Self>, cx
: &mut Context
) -> Poll
<Self::Output
> {
922 PinMut
::new(&mut **self).poll(cx
)
926 #[unstable(feature = "futures_api", issue = "50547")]
927 impl<'a
, F
: ?Sized
+ Future
> Future
for PinBox
<F
> {
928 type Output
= F
::Output
;
930 fn poll(mut self: PinMut
<Self>, cx
: &mut Context
) -> Poll
<Self::Output
> {
931 self.as_pin_mut().poll(cx
)
935 #[unstable(feature = "futures_api", issue = "50547")]
936 unsafe impl<F
: Future
<Output
= ()> + Send
+ '
static> UnsafeTask
for PinBox
<F
> {
937 fn into_raw(self) -> *mut () {
938 PinBox
::into_raw(self) as *mut ()
941 unsafe fn poll(task
: *mut (), cx
: &mut Context
) -> Poll
<()> {
942 let ptr
= task
as *mut F
;
943 let pin
: PinMut
<F
> = PinMut
::new_unchecked(&mut *ptr
);
947 unsafe fn drop(task
: *mut ()) {
948 drop(PinBox
::from_raw(task
as *mut F
))
952 #[unstable(feature = "futures_api", issue = "50547")]
953 impl<F
: Future
<Output
= ()> + Send
+ '
static> From
<PinBox
<F
>> for TaskObj
{
954 fn from(boxed
: PinBox
<F
>) -> Self {
959 #[unstable(feature = "futures_api", issue = "50547")]
960 impl<F
: Future
<Output
= ()> + Send
+ '
static> From
<Box
<F
>> for TaskObj
{
961 fn from(boxed
: Box
<F
>) -> Self {
962 TaskObj
::new(PinBox
::from(boxed
))