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.
7 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
8 //! its allocation. It is valid to convert both ways between a [`Box`] and a
9 //! raw pointer allocated with the [`Global`] allocator, given that the
10 //! [`Layout`] used with the allocator is correct for the type. More precisely,
11 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
12 //! with `Layout::for_value(&*value)` may be converted into a box using
13 //! `Box::<T>::from_raw(value)`. Conversely, the memory backing a `value: *mut
14 //! T` obtained from `Box::<T>::into_raw` may be deallocated using the
15 //! [`Global`] allocator with `Layout::for_value(&*value)`.
19 //! Move a value from the stack to the heap by creating a [`Box`]:
23 //! let boxed: Box<u8> = Box::new(val);
26 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
29 //! let boxed: Box<u8> = Box::new(5);
30 //! let val: u8 = *boxed;
33 //! Creating a recursive data structure:
38 //! Cons(T, Box<List<T>>),
43 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
44 //! println!("{:?}", list);
48 //! This will print `Cons(1, Cons(2, Nil))`.
50 //! Recursive structures must be boxed, because if the definition of `Cons`
53 //! ```compile_fail,E0072
59 //! It wouldn't work. This is because the size of a `List` depends on how many
60 //! elements are in the list, and so we don't know how much memory to allocate
61 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
62 //! big `Cons` needs to be.
64 //! [dereferencing]: ../../std/ops/trait.Deref.html
65 //! [`Box`]: struct.Box.html
67 #![stable(feature = "rust1", since = "1.0.0")]
71 use core::cmp::Ordering;
72 use core::convert::From;
74 use core::future::Future;
75 use core::hash::{Hash, Hasher};
76 use core::iter::{Iterator, FromIterator, FusedIterator};
77 use core::marker::{Unpin, Unsize};
81 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
83 use core::ptr::{self, NonNull, Unique};
84 use core::task::{Waker, Poll};
87 use crate::raw_vec::RawVec;
88 use crate::str::from_boxed_utf8_unchecked;
90 /// A pointer type for heap allocation.
92 /// See the [module-level documentation](../../std/boxed/index.html) for more.
95 #[stable(feature = "rust1", since = "1.0.0")]
96 pub struct Box<T: ?Sized>(Unique<T>);
99 /// Allocates memory on the heap and then places `x` into it.
101 /// This doesn't actually allocate if `T` is zero-sized.
106 /// let five = Box::new(5);
108 #[stable(feature = "rust1", since = "1.0.0")]
110 pub fn new(x: T) -> Box<T> {
114 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
115 /// `x` will be pinned in memory and unable to be moved.
116 #[stable(feature = "pin", since = "1.33.0")]
118 pub fn pin(x: T) -> Pin<Box<T>> {
123 impl<T: ?Sized> Box<T> {
124 /// Constructs a box from a raw pointer.
126 /// After calling this function, the raw pointer is owned by the
127 /// resulting `Box`. Specifically, the `Box` destructor will call
128 /// the destructor of `T` and free the allocated memory. Since the
129 /// way `Box` allocates and releases memory is unspecified, the
130 /// only valid pointer to pass to this function is the one taken
131 /// from another `Box` via the [`Box::into_raw`] function.
133 /// This function is unsafe because improper use may lead to
134 /// memory problems. For example, a double-free may occur if the
135 /// function is called twice on the same raw pointer.
137 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
142 /// let x = Box::new(5);
143 /// let ptr = Box::into_raw(x);
144 /// let x = unsafe { Box::from_raw(ptr) };
146 #[stable(feature = "box_raw", since = "1.4.0")]
148 pub unsafe fn from_raw(raw: *mut T) -> Self {
149 Box(Unique::new_unchecked(raw))
152 /// Consumes the `Box`, returning a wrapped raw pointer.
154 /// The pointer will be properly aligned and non-null.
156 /// After calling this function, the caller is responsible for the
157 /// memory previously managed by the `Box`. In particular, the
158 /// caller should properly destroy `T` and release the memory. The
159 /// proper way to do so is to convert the raw pointer back into a
160 /// `Box` with the [`Box::from_raw`] function.
162 /// Note: this is an associated function, which means that you have
163 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
164 /// is so that there is no conflict with a method on the inner type.
166 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
171 /// let x = Box::new(5);
172 /// let ptr = Box::into_raw(x);
174 #[stable(feature = "box_raw", since = "1.4.0")]
176 pub fn into_raw(b: Box<T>) -> *mut T {
177 Box::into_raw_non_null(b).as_ptr()
180 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
182 /// After calling this function, the caller is responsible for the
183 /// memory previously managed by the `Box`. In particular, the
184 /// caller should properly destroy `T` and release the memory. The
185 /// proper way to do so is to convert the `NonNull<T>` pointer
186 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
189 /// Note: this is an associated function, which means that you have
190 /// to call it as `Box::into_raw_non_null(b)`
191 /// instead of `b.into_raw_non_null()`. This
192 /// is so that there is no conflict with a method on the inner type.
194 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
199 /// #![feature(box_into_raw_non_null)]
202 /// let x = Box::new(5);
203 /// let ptr = Box::into_raw_non_null(x);
206 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
208 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
209 Box::into_unique(b).into()
212 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
215 pub fn into_unique(mut b: Box<T>) -> Unique<T> {
216 // Box is kind-of a library type, but recognized as a "unique pointer" by
217 // Stacked Borrows. This function here corresponds to "reborrowing to
218 // a raw pointer", but there is no actual reborrow here -- so
219 // without some care, the pointer we are returning here still carries
220 // the `Uniq` tag. We round-trip through a mutable reference to avoid that.
221 let unique = unsafe { b.0.as_mut() as *mut T };
223 unsafe { Unique::new_unchecked(unique) }
226 /// Consumes and leaks the `Box`, returning a mutable reference,
227 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
228 /// `'a`. If the type has only static references, or none at all, then this
229 /// may be chosen to be `'static`.
231 /// This function is mainly useful for data that lives for the remainder of
232 /// the program's life. Dropping the returned reference will cause a memory
233 /// leak. If this is not acceptable, the reference should first be wrapped
234 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
235 /// then be dropped which will properly destroy `T` and release the
236 /// allocated memory.
238 /// Note: this is an associated function, which means that you have
239 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
240 /// is so that there is no conflict with a method on the inner type.
242 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
250 /// let x = Box::new(41);
251 /// let static_ref: &'static mut usize = Box::leak(x);
252 /// *static_ref += 1;
253 /// assert_eq!(*static_ref, 42);
261 /// let x = vec![1, 2, 3].into_boxed_slice();
262 /// let static_ref = Box::leak(x);
263 /// static_ref[0] = 4;
264 /// assert_eq!(*static_ref, [4, 2, 3]);
267 #[stable(feature = "box_leak", since = "1.26.0")]
269 pub fn leak<'a>(b: Box<T>) -> &'a mut T
271 T: 'a // Technically not needed, but kept to be explicit.
273 unsafe { &mut *Box::into_raw(b) }
276 /// Converts a `Box<T>` into a `Pin<Box<T>>`
278 /// This conversion does not allocate on the heap and happens in place.
280 /// This is also available via [`From`].
281 #[unstable(feature = "box_into_pin", issue = "0")]
282 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
283 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
284 // when `T: !Unpin`, so it's safe to pin it directly without any
285 // additional requirements.
286 unsafe { Pin::new_unchecked(boxed) }
290 #[stable(feature = "rust1", since = "1.0.0")]
291 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
293 // FIXME: Do nothing, drop is currently performed by compiler.
297 #[stable(feature = "rust1", since = "1.0.0")]
298 impl<T: Default> Default for Box<T> {
299 /// Creates a `Box<T>`, with the `Default` value for T.
300 fn default() -> Box<T> {
301 box Default::default()
305 #[stable(feature = "rust1", since = "1.0.0")]
306 impl<T> Default for Box<[T]> {
307 fn default() -> Box<[T]> {
308 Box::<[T; 0]>::new([])
312 #[stable(feature = "default_box_extra", since = "1.17.0")]
313 impl Default for Box<str> {
314 fn default() -> Box<str> {
315 unsafe { from_boxed_utf8_unchecked(Default::default()) }
319 #[stable(feature = "rust1", since = "1.0.0")]
320 impl<T: Clone> Clone for Box<T> {
321 /// Returns a new box with a `clone()` of this box's contents.
326 /// let x = Box::new(5);
327 /// let y = x.clone();
331 fn clone(&self) -> Box<T> {
332 box { (**self).clone() }
334 /// Copies `source`'s contents into `self` without creating a new allocation.
339 /// let x = Box::new(5);
340 /// let mut y = Box::new(10);
342 /// y.clone_from(&x);
344 /// assert_eq!(*y, 5);
347 fn clone_from(&mut self, source: &Box<T>) {
348 (**self).clone_from(&(**source));
353 #[stable(feature = "box_slice_clone", since = "1.3.0")]
354 impl Clone for Box<str> {
355 fn clone(&self) -> Self {
356 let len = self.len();
357 let buf = RawVec::with_capacity(len);
359 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
360 from_boxed_utf8_unchecked(buf.into_box())
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
368 fn eq(&self, other: &Box<T>) -> bool {
369 PartialEq::eq(&**self, &**other)
372 fn ne(&self, other: &Box<T>) -> bool {
373 PartialEq::ne(&**self, &**other)
376 #[stable(feature = "rust1", since = "1.0.0")]
377 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
379 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
380 PartialOrd::partial_cmp(&**self, &**other)
383 fn lt(&self, other: &Box<T>) -> bool {
384 PartialOrd::lt(&**self, &**other)
387 fn le(&self, other: &Box<T>) -> bool {
388 PartialOrd::le(&**self, &**other)
391 fn ge(&self, other: &Box<T>) -> bool {
392 PartialOrd::ge(&**self, &**other)
395 fn gt(&self, other: &Box<T>) -> bool {
396 PartialOrd::gt(&**self, &**other)
399 #[stable(feature = "rust1", since = "1.0.0")]
400 impl<T: ?Sized + Ord> Ord for Box<T> {
402 fn cmp(&self, other: &Box<T>) -> Ordering {
403 Ord::cmp(&**self, &**other)
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<T: ?Sized + Eq> Eq for Box<T> {}
409 #[stable(feature = "rust1", since = "1.0.0")]
410 impl<T: ?Sized + Hash> Hash for Box<T> {
411 fn hash<H: Hasher>(&self, state: &mut H) {
412 (**self).hash(state);
416 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
417 impl<T: ?Sized + Hasher> Hasher for Box<T> {
418 fn finish(&self) -> u64 {
421 fn write(&mut self, bytes: &[u8]) {
422 (**self).write(bytes)
424 fn write_u8(&mut self, i: u8) {
427 fn write_u16(&mut self, i: u16) {
428 (**self).write_u16(i)
430 fn write_u32(&mut self, i: u32) {
431 (**self).write_u32(i)
433 fn write_u64(&mut self, i: u64) {
434 (**self).write_u64(i)
436 fn write_u128(&mut self, i: u128) {
437 (**self).write_u128(i)
439 fn write_usize(&mut self, i: usize) {
440 (**self).write_usize(i)
442 fn write_i8(&mut self, i: i8) {
445 fn write_i16(&mut self, i: i16) {
446 (**self).write_i16(i)
448 fn write_i32(&mut self, i: i32) {
449 (**self).write_i32(i)
451 fn write_i64(&mut self, i: i64) {
452 (**self).write_i64(i)
454 fn write_i128(&mut self, i: i128) {
455 (**self).write_i128(i)
457 fn write_isize(&mut self, i: isize) {
458 (**self).write_isize(i)
462 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
463 impl<T> From<T> for Box<T> {
464 /// Converts a generic type `T` into a `Box<T>`
466 /// The conversion allocates on the heap and moves `t`
467 /// from the stack into it.
472 /// let boxed = Box::new(5);
474 /// assert_eq!(Box::from(x), boxed);
476 fn from(t: T) -> Self {
481 #[stable(feature = "pin", since = "1.33.0")]
482 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
483 /// Converts a `Box<T>` into a `Pin<Box<T>>`
485 /// This conversion does not allocate on the heap and happens in place.
486 fn from(boxed: Box<T>) -> Self {
491 #[stable(feature = "box_from_slice", since = "1.17.0")]
492 impl<T: Copy> From<&[T]> for Box<[T]> {
493 /// Converts a `&[T]` into a `Box<[T]>`
495 /// This conversion allocates on the heap
496 /// and performs a copy of `slice`.
500 /// // create a &[u8] which will be used to create a Box<[u8]>
501 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
502 /// let boxed_slice: Box<[u8]> = Box::from(slice);
504 /// println!("{:?}", boxed_slice);
506 fn from(slice: &[T]) -> Box<[T]> {
507 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
508 boxed.copy_from_slice(slice);
513 #[stable(feature = "box_from_slice", since = "1.17.0")]
514 impl From<&str> for Box<str> {
515 /// Converts a `&str` into a `Box<str>`
517 /// This conversion allocates on the heap
518 /// and performs a copy of `s`.
522 /// let boxed: Box<str> = Box::from("hello");
523 /// println!("{}", boxed);
526 fn from(s: &str) -> Box<str> {
527 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
531 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
532 impl From<Box<str>> for Box<[u8]> {
533 /// Converts a `Box<str>>` into a `Box<[u8]>`
535 /// This conversion does not allocate on the heap and happens in place.
539 /// // create a Box<str> which will be used to create a Box<[u8]>
540 /// let boxed: Box<str> = Box::from("hello");
541 /// let boxed_str: Box<[u8]> = Box::from(boxed);
543 /// // create a &[u8] which will be used to create a Box<[u8]>
544 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
545 /// let boxed_slice = Box::from(slice);
547 /// assert_eq!(boxed_slice, boxed_str);
550 fn from(s: Box<str>) -> Self {
551 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
557 #[stable(feature = "rust1", since = "1.0.0")]
558 /// Attempt to downcast the box to a concrete type.
563 /// use std::any::Any;
565 /// fn print_if_string(value: Box<dyn Any>) {
566 /// if let Ok(string) = value.downcast::<String>() {
567 /// println!("String ({}): {}", string.len(), string);
572 /// let my_string = "Hello World".to_string();
573 /// print_if_string(Box::new(my_string));
574 /// print_if_string(Box::new(0i8));
577 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
580 let raw: *mut dyn Any = Box::into_raw(self);
581 Ok(Box::from_raw(raw as *mut T))
589 impl Box<dyn Any + Send> {
591 #[stable(feature = "rust1", since = "1.0.0")]
592 /// Attempt to downcast the box to a concrete type.
597 /// use std::any::Any;
599 /// fn print_if_string(value: Box<dyn Any + Send>) {
600 /// if let Ok(string) = value.downcast::<String>() {
601 /// println!("String ({}): {}", string.len(), string);
606 /// let my_string = "Hello World".to_string();
607 /// print_if_string(Box::new(my_string));
608 /// print_if_string(Box::new(0i8));
611 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
612 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
613 // reapply the Send marker
614 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
619 #[stable(feature = "rust1", since = "1.0.0")]
620 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
622 fmt::Display::fmt(&**self, f)
626 #[stable(feature = "rust1", since = "1.0.0")]
627 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 fmt::Debug::fmt(&**self, f)
633 #[stable(feature = "rust1", since = "1.0.0")]
634 impl<T: ?Sized> fmt::Pointer for Box<T> {
635 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636 // It's not possible to extract the inner Uniq directly from the Box,
637 // instead we cast it to a *const which aliases the Unique
638 let ptr: *const T = &**self;
639 fmt::Pointer::fmt(&ptr, f)
643 #[stable(feature = "rust1", since = "1.0.0")]
644 impl<T: ?Sized> Deref for Box<T> {
647 fn deref(&self) -> &T {
652 #[stable(feature = "rust1", since = "1.0.0")]
653 impl<T: ?Sized> DerefMut for Box<T> {
654 fn deref_mut(&mut self) -> &mut T {
659 #[unstable(feature = "receiver_trait", issue = "0")]
660 impl<T: ?Sized> Receiver for Box<T> {}
662 #[stable(feature = "rust1", since = "1.0.0")]
663 impl<I: Iterator + ?Sized> Iterator for Box<I> {
665 fn next(&mut self) -> Option<I::Item> {
668 fn size_hint(&self) -> (usize, Option<usize>) {
671 fn nth(&mut self, n: usize) -> Option<I::Item> {
675 #[stable(feature = "rust1", since = "1.0.0")]
676 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
677 fn next_back(&mut self) -> Option<I::Item> {
680 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
686 fn len(&self) -> usize {
689 fn is_empty(&self) -> bool {
694 #[stable(feature = "fused", since = "1.26.0")]
695 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
697 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
698 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
699 type Output = <F as FnOnce<A>>::Output;
701 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
702 <F as FnOnce<A>>::call_once(*self, args)
706 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
707 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
708 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
709 <F as FnMut<A>>::call_mut(self, args)
713 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
714 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
715 extern "rust-call" fn call(&self, args: A) -> Self::Output {
716 <F as Fn<A>>::call(self, args)
720 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
721 /// closure objects. The idea is that where one would normally store a
722 /// `Box<dyn FnOnce()>` in a data structure, you should use
723 /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except
724 /// that a `FnBox` closure can only be called if it is boxed. (Note
725 /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>`
726 /// closures become directly usable.)
730 /// Here is a snippet of code which creates a hashmap full of boxed
731 /// once closures and then removes them one by one, calling each
732 /// closure as it is removed. Note that the type of the closures
733 /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce()
737 /// #![feature(fnbox)]
739 /// use std::boxed::FnBox;
740 /// use std::collections::HashMap;
742 /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> {
743 /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new();
744 /// map.insert(1, Box::new(|| 22));
745 /// map.insert(2, Box::new(|| 44));
750 /// let mut map = make_map();
751 /// for i in &[1, 2] {
752 /// let f = map.remove(&i).unwrap();
753 /// assert_eq!(f(), i * 22);
758 #[unstable(feature = "fnbox",
759 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
760 pub trait FnBox<A>: FnOnce<A> {
761 fn call_box(self: Box<Self>, args: A) -> Self::Output;
764 #[unstable(feature = "fnbox",
765 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
766 impl<A, F> FnBox<A> for F
769 fn call_box(self: Box<F>, args: A) -> F::Output {
774 #[unstable(feature = "coerce_unsized", issue = "27732")]
775 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
777 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
778 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
780 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
781 impl<A> FromIterator<A> for Box<[A]> {
782 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
783 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
787 #[stable(feature = "box_slice_clone", since = "1.3.0")]
788 impl<T: Clone> Clone for Box<[T]> {
789 fn clone(&self) -> Self {
790 let mut new = BoxBuilder {
791 data: RawVec::with_capacity(self.len()),
795 let mut target = new.data.ptr();
797 for item in self.iter() {
799 ptr::write(target, item.clone());
800 target = target.offset(1);
806 return unsafe { new.into_box() };
808 // Helper type for responding to panics correctly.
809 struct BoxBuilder<T> {
814 impl<T> BoxBuilder<T> {
815 unsafe fn into_box(self) -> Box<[T]> {
816 let raw = ptr::read(&self.data);
822 impl<T> Drop for BoxBuilder<T> {
824 let mut data = self.data.ptr();
825 let max = unsafe { data.add(self.len) };
830 data = data.offset(1);
838 #[stable(feature = "box_borrow", since = "1.1.0")]
839 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
840 fn borrow(&self) -> &T {
845 #[stable(feature = "box_borrow", since = "1.1.0")]
846 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
847 fn borrow_mut(&mut self) -> &mut T {
852 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
853 impl<T: ?Sized> AsRef<T> for Box<T> {
854 fn as_ref(&self) -> &T {
859 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
860 impl<T: ?Sized> AsMut<T> for Box<T> {
861 fn as_mut(&mut self) -> &mut T {
868 * We could have chosen not to add this impl, and instead have written a
869 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
870 * because Box<T> implements Unpin even when T does not, as a result of
873 * We chose this API instead of the alternative for a few reasons:
874 * - Logically, it is helpful to understand pinning in regard to the
875 * memory region being pointed to. For this reason none of the
876 * standard library pointer types support projecting through a pin
877 * (Box<T> is the only pointer type in std for which this would be
879 * - It is in practice very useful to have Box<T> be unconditionally
880 * Unpin because of trait objects, for which the structural auto
881 * trait functionality does not apply (e.g., Box<dyn Foo> would
882 * otherwise not be Unpin).
884 * Another type with the same semantics as Box but only a conditional
885 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
886 * could have a method to project a Pin<T> from it.
888 #[stable(feature = "pin", since = "1.33.0")]
889 impl<T: ?Sized> Unpin for Box<T> { }
891 #[unstable(feature = "generator_trait", issue = "43122")]
892 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
893 type Yield = G::Yield;
894 type Return = G::Return;
896 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
897 G::resume(Pin::new(&mut *self))
901 #[unstable(feature = "generator_trait", issue = "43122")]
902 impl<G: ?Sized + Generator> Generator for Pin<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((*self).as_mut())
911 #[unstable(feature = "futures_api", issue = "50547")]
912 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
913 type Output = F::Output;
915 fn poll(mut self: Pin<&mut Self>, waker: &Waker) -> Poll<Self::Output> {
916 F::poll(Pin::new(&mut *self), waker)