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
66 //! [`Global`]: ../alloc/struct.Global.html
67 //! [`Layout`]: ../alloc/struct.Layout.html
69 #![stable(feature = "rust1", since = "1.0.0")]
73 use core::cmp::Ordering;
74 use core::convert::From;
76 use core::future::Future;
77 use core::hash::{Hash, Hasher};
78 use core::iter::{Iterator, FromIterator, FusedIterator};
79 use core::marker::{Unpin, Unsize};
83 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
85 use core::ptr::{self, NonNull, Unique};
86 use core::task::{Context, Poll};
89 use crate::raw_vec::RawVec;
90 use crate::str::from_boxed_utf8_unchecked;
92 /// A pointer type for heap allocation.
94 /// See the [module-level documentation](../../std/boxed/index.html) for more.
97 #[stable(feature = "rust1", since = "1.0.0")]
98 pub struct Box<T: ?Sized>(Unique<T>);
101 /// Allocates memory on the heap and then places `x` into it.
103 /// This doesn't actually allocate if `T` is zero-sized.
108 /// let five = Box::new(5);
110 #[stable(feature = "rust1", since = "1.0.0")]
112 pub fn new(x: T) -> Box<T> {
116 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
117 /// `x` will be pinned in memory and unable to be moved.
118 #[stable(feature = "pin", since = "1.33.0")]
120 pub fn pin(x: T) -> Pin<Box<T>> {
125 impl<T: ?Sized> Box<T> {
126 /// Constructs a box from a raw pointer.
128 /// After calling this function, the raw pointer is owned by the
129 /// resulting `Box`. Specifically, the `Box` destructor will call
130 /// the destructor of `T` and free the allocated memory. Since the
131 /// way `Box` allocates and releases memory is unspecified, the
132 /// only valid pointer to pass to this function is the one taken
133 /// from another `Box` via the [`Box::into_raw`] function.
135 /// This function is unsafe because improper use may lead to
136 /// memory problems. For example, a double-free may occur if the
137 /// function is called twice on the same raw pointer.
139 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
144 /// let x = Box::new(5);
145 /// let ptr = Box::into_raw(x);
146 /// let x = unsafe { Box::from_raw(ptr) };
148 #[stable(feature = "box_raw", since = "1.4.0")]
150 pub unsafe fn from_raw(raw: *mut T) -> Self {
151 Box(Unique::new_unchecked(raw))
154 /// Consumes the `Box`, returning a wrapped raw pointer.
156 /// The pointer will be properly aligned and non-null.
158 /// After calling this function, the caller is responsible for the
159 /// memory previously managed by the `Box`. In particular, the
160 /// caller should properly destroy `T` and release the memory. The
161 /// proper way to do so is to convert the raw pointer back into a
162 /// `Box` with the [`Box::from_raw`] function.
164 /// Note: this is an associated function, which means that you have
165 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
166 /// is so that there is no conflict with a method on the inner type.
168 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
173 /// let x = Box::new(5);
174 /// let ptr = Box::into_raw(x);
176 #[stable(feature = "box_raw", since = "1.4.0")]
178 pub fn into_raw(b: Box<T>) -> *mut T {
179 Box::into_raw_non_null(b).as_ptr()
182 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
184 /// After calling this function, the caller is responsible for the
185 /// memory previously managed by the `Box`. In particular, the
186 /// caller should properly destroy `T` and release the memory. The
187 /// proper way to do so is to convert the `NonNull<T>` pointer
188 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
191 /// Note: this is an associated function, which means that you have
192 /// to call it as `Box::into_raw_non_null(b)`
193 /// instead of `b.into_raw_non_null()`. This
194 /// is so that there is no conflict with a method on the inner type.
196 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
201 /// #![feature(box_into_raw_non_null)]
204 /// let x = Box::new(5);
205 /// let ptr = Box::into_raw_non_null(x);
208 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
210 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
211 Box::into_unique(b).into()
214 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
217 pub fn into_unique(mut b: Box<T>) -> Unique<T> {
218 // Box is kind-of a library type, but recognized as a "unique pointer" by
219 // Stacked Borrows. This function here corresponds to "reborrowing to
220 // a raw pointer", but there is no actual reborrow here -- so
221 // without some care, the pointer we are returning here still carries
222 // the `Uniq` tag. We round-trip through a mutable reference to avoid that.
223 let unique = unsafe { b.0.as_mut() as *mut T };
225 unsafe { Unique::new_unchecked(unique) }
228 /// Consumes and leaks the `Box`, returning a mutable reference,
229 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
230 /// `'a`. If the type has only static references, or none at all, then this
231 /// may be chosen to be `'static`.
233 /// This function is mainly useful for data that lives for the remainder of
234 /// the program's life. Dropping the returned reference will cause a memory
235 /// leak. If this is not acceptable, the reference should first be wrapped
236 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
237 /// then be dropped which will properly destroy `T` and release the
238 /// allocated memory.
240 /// Note: this is an associated function, which means that you have
241 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
242 /// is so that there is no conflict with a method on the inner type.
244 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
252 /// let x = Box::new(41);
253 /// let static_ref: &'static mut usize = Box::leak(x);
254 /// *static_ref += 1;
255 /// assert_eq!(*static_ref, 42);
263 /// let x = vec![1, 2, 3].into_boxed_slice();
264 /// let static_ref = Box::leak(x);
265 /// static_ref[0] = 4;
266 /// assert_eq!(*static_ref, [4, 2, 3]);
269 #[stable(feature = "box_leak", since = "1.26.0")]
271 pub fn leak<'a>(b: Box<T>) -> &'a mut T
273 T: 'a // Technically not needed, but kept to be explicit.
275 unsafe { &mut *Box::into_raw(b) }
278 /// Converts a `Box<T>` into a `Pin<Box<T>>`
280 /// This conversion does not allocate on the heap and happens in place.
282 /// This is also available via [`From`].
283 #[unstable(feature = "box_into_pin", issue = "0")]
284 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
285 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
286 // when `T: !Unpin`, so it's safe to pin it directly without any
287 // additional requirements.
288 unsafe { Pin::new_unchecked(boxed) }
292 #[stable(feature = "rust1", since = "1.0.0")]
293 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
295 // FIXME: Do nothing, drop is currently performed by compiler.
299 #[stable(feature = "rust1", since = "1.0.0")]
300 impl<T: Default> Default for Box<T> {
301 /// Creates a `Box<T>`, with the `Default` value for T.
302 fn default() -> Box<T> {
303 box Default::default()
307 #[stable(feature = "rust1", since = "1.0.0")]
308 impl<T> Default for Box<[T]> {
309 fn default() -> Box<[T]> {
310 Box::<[T; 0]>::new([])
314 #[stable(feature = "default_box_extra", since = "1.17.0")]
315 impl Default for Box<str> {
316 fn default() -> Box<str> {
317 unsafe { from_boxed_utf8_unchecked(Default::default()) }
321 #[stable(feature = "rust1", since = "1.0.0")]
322 impl<T: Clone> Clone for Box<T> {
323 /// Returns a new box with a `clone()` of this box's contents.
328 /// let x = Box::new(5);
329 /// let y = x.clone();
333 fn clone(&self) -> Box<T> {
334 box { (**self).clone() }
336 /// Copies `source`'s contents into `self` without creating a new allocation.
341 /// let x = Box::new(5);
342 /// let mut y = Box::new(10);
344 /// y.clone_from(&x);
346 /// assert_eq!(*y, 5);
349 fn clone_from(&mut self, source: &Box<T>) {
350 (**self).clone_from(&(**source));
355 #[stable(feature = "box_slice_clone", since = "1.3.0")]
356 impl Clone for Box<str> {
357 fn clone(&self) -> Self {
358 let len = self.len();
359 let buf = RawVec::with_capacity(len);
361 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
362 from_boxed_utf8_unchecked(buf.into_box())
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
370 fn eq(&self, other: &Box<T>) -> bool {
371 PartialEq::eq(&**self, &**other)
374 fn ne(&self, other: &Box<T>) -> bool {
375 PartialEq::ne(&**self, &**other)
378 #[stable(feature = "rust1", since = "1.0.0")]
379 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
381 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
382 PartialOrd::partial_cmp(&**self, &**other)
385 fn lt(&self, other: &Box<T>) -> bool {
386 PartialOrd::lt(&**self, &**other)
389 fn le(&self, other: &Box<T>) -> bool {
390 PartialOrd::le(&**self, &**other)
393 fn ge(&self, other: &Box<T>) -> bool {
394 PartialOrd::ge(&**self, &**other)
397 fn gt(&self, other: &Box<T>) -> bool {
398 PartialOrd::gt(&**self, &**other)
401 #[stable(feature = "rust1", since = "1.0.0")]
402 impl<T: ?Sized + Ord> Ord for Box<T> {
404 fn cmp(&self, other: &Box<T>) -> Ordering {
405 Ord::cmp(&**self, &**other)
408 #[stable(feature = "rust1", since = "1.0.0")]
409 impl<T: ?Sized + Eq> Eq for Box<T> {}
411 #[stable(feature = "rust1", since = "1.0.0")]
412 impl<T: ?Sized + Hash> Hash for Box<T> {
413 fn hash<H: Hasher>(&self, state: &mut H) {
414 (**self).hash(state);
418 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
419 impl<T: ?Sized + Hasher> Hasher for Box<T> {
420 fn finish(&self) -> u64 {
423 fn write(&mut self, bytes: &[u8]) {
424 (**self).write(bytes)
426 fn write_u8(&mut self, i: u8) {
429 fn write_u16(&mut self, i: u16) {
430 (**self).write_u16(i)
432 fn write_u32(&mut self, i: u32) {
433 (**self).write_u32(i)
435 fn write_u64(&mut self, i: u64) {
436 (**self).write_u64(i)
438 fn write_u128(&mut self, i: u128) {
439 (**self).write_u128(i)
441 fn write_usize(&mut self, i: usize) {
442 (**self).write_usize(i)
444 fn write_i8(&mut self, i: i8) {
447 fn write_i16(&mut self, i: i16) {
448 (**self).write_i16(i)
450 fn write_i32(&mut self, i: i32) {
451 (**self).write_i32(i)
453 fn write_i64(&mut self, i: i64) {
454 (**self).write_i64(i)
456 fn write_i128(&mut self, i: i128) {
457 (**self).write_i128(i)
459 fn write_isize(&mut self, i: isize) {
460 (**self).write_isize(i)
464 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
465 impl<T> From<T> for Box<T> {
466 /// Converts a generic type `T` into a `Box<T>`
468 /// The conversion allocates on the heap and moves `t`
469 /// from the stack into it.
474 /// let boxed = Box::new(5);
476 /// assert_eq!(Box::from(x), boxed);
478 fn from(t: T) -> Self {
483 #[stable(feature = "pin", since = "1.33.0")]
484 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
485 /// Converts a `Box<T>` into a `Pin<Box<T>>`
487 /// This conversion does not allocate on the heap and happens in place.
488 fn from(boxed: Box<T>) -> Self {
493 #[stable(feature = "box_from_slice", since = "1.17.0")]
494 impl<T: Copy> From<&[T]> for Box<[T]> {
495 /// Converts a `&[T]` into a `Box<[T]>`
497 /// This conversion allocates on the heap
498 /// and performs a copy of `slice`.
502 /// // create a &[u8] which will be used to create a Box<[u8]>
503 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
504 /// let boxed_slice: Box<[u8]> = Box::from(slice);
506 /// println!("{:?}", boxed_slice);
508 fn from(slice: &[T]) -> Box<[T]> {
509 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
510 boxed.copy_from_slice(slice);
515 #[stable(feature = "box_from_slice", since = "1.17.0")]
516 impl From<&str> for Box<str> {
517 /// Converts a `&str` into a `Box<str>`
519 /// This conversion allocates on the heap
520 /// and performs a copy of `s`.
524 /// let boxed: Box<str> = Box::from("hello");
525 /// println!("{}", boxed);
528 fn from(s: &str) -> Box<str> {
529 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
533 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
534 impl From<Box<str>> for Box<[u8]> {
535 /// Converts a `Box<str>>` into a `Box<[u8]>`
537 /// This conversion does not allocate on the heap and happens in place.
541 /// // create a Box<str> which will be used to create a Box<[u8]>
542 /// let boxed: Box<str> = Box::from("hello");
543 /// let boxed_str: Box<[u8]> = Box::from(boxed);
545 /// // create a &[u8] which will be used to create a Box<[u8]>
546 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
547 /// let boxed_slice = Box::from(slice);
549 /// assert_eq!(boxed_slice, boxed_str);
552 fn from(s: Box<str>) -> Self {
553 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
559 #[stable(feature = "rust1", since = "1.0.0")]
560 /// Attempt to downcast the box to a concrete type.
565 /// use std::any::Any;
567 /// fn print_if_string(value: Box<dyn Any>) {
568 /// if let Ok(string) = value.downcast::<String>() {
569 /// println!("String ({}): {}", string.len(), string);
574 /// let my_string = "Hello World".to_string();
575 /// print_if_string(Box::new(my_string));
576 /// print_if_string(Box::new(0i8));
579 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
582 let raw: *mut dyn Any = Box::into_raw(self);
583 Ok(Box::from_raw(raw as *mut T))
591 impl Box<dyn Any + Send> {
593 #[stable(feature = "rust1", since = "1.0.0")]
594 /// Attempt to downcast the box to a concrete type.
599 /// use std::any::Any;
601 /// fn print_if_string(value: Box<dyn Any + Send>) {
602 /// if let Ok(string) = value.downcast::<String>() {
603 /// println!("String ({}): {}", string.len(), string);
608 /// let my_string = "Hello World".to_string();
609 /// print_if_string(Box::new(my_string));
610 /// print_if_string(Box::new(0i8));
613 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
614 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
615 // reapply the Send marker
616 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
621 #[stable(feature = "rust1", since = "1.0.0")]
622 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
623 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
624 fmt::Display::fmt(&**self, f)
628 #[stable(feature = "rust1", since = "1.0.0")]
629 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
630 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
631 fmt::Debug::fmt(&**self, f)
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl<T: ?Sized> fmt::Pointer for Box<T> {
637 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
638 // It's not possible to extract the inner Uniq directly from the Box,
639 // instead we cast it to a *const which aliases the Unique
640 let ptr: *const T = &**self;
641 fmt::Pointer::fmt(&ptr, f)
645 #[stable(feature = "rust1", since = "1.0.0")]
646 impl<T: ?Sized> Deref for Box<T> {
649 fn deref(&self) -> &T {
654 #[stable(feature = "rust1", since = "1.0.0")]
655 impl<T: ?Sized> DerefMut for Box<T> {
656 fn deref_mut(&mut self) -> &mut T {
661 #[unstable(feature = "receiver_trait", issue = "0")]
662 impl<T: ?Sized> Receiver for Box<T> {}
664 #[stable(feature = "rust1", since = "1.0.0")]
665 impl<I: Iterator + ?Sized> Iterator for Box<I> {
667 fn next(&mut self) -> Option<I::Item> {
670 fn size_hint(&self) -> (usize, Option<usize>) {
673 fn nth(&mut self, n: usize) -> Option<I::Item> {
677 #[stable(feature = "rust1", since = "1.0.0")]
678 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
679 fn next_back(&mut self) -> Option<I::Item> {
682 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
686 #[stable(feature = "rust1", since = "1.0.0")]
687 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
688 fn len(&self) -> usize {
691 fn is_empty(&self) -> bool {
696 #[stable(feature = "fused", since = "1.26.0")]
697 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
699 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
700 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
701 type Output = <F as FnOnce<A>>::Output;
703 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
704 <F as FnOnce<A>>::call_once(*self, args)
708 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
709 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
710 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
711 <F as FnMut<A>>::call_mut(self, args)
715 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
716 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
717 extern "rust-call" fn call(&self, args: A) -> Self::Output {
718 <F as Fn<A>>::call(self, args)
722 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
723 /// closure objects. The idea is that where one would normally store a
724 /// `Box<dyn FnOnce()>` in a data structure, you should use
725 /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except
726 /// that a `FnBox` closure can only be called if it is boxed. (Note
727 /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>`
728 /// closures become directly usable.)
732 /// Here is a snippet of code which creates a hashmap full of boxed
733 /// once closures and then removes them one by one, calling each
734 /// closure as it is removed. Note that the type of the closures
735 /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce()
739 /// #![feature(fnbox)]
741 /// use std::boxed::FnBox;
742 /// use std::collections::HashMap;
744 /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> {
745 /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new();
746 /// map.insert(1, Box::new(|| 22));
747 /// map.insert(2, Box::new(|| 44));
752 /// let mut map = make_map();
753 /// for i in &[1, 2] {
754 /// let f = map.remove(&i).unwrap();
755 /// assert_eq!(f(), i * 22);
760 #[unstable(feature = "fnbox",
761 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
762 pub trait FnBox<A>: FnOnce<A> {
763 fn call_box(self: Box<Self>, args: A) -> Self::Output;
766 #[unstable(feature = "fnbox",
767 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
768 impl<A, F> FnBox<A> for F
771 fn call_box(self: Box<F>, args: A) -> F::Output {
776 #[unstable(feature = "coerce_unsized", issue = "27732")]
777 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
779 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
780 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
782 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
783 impl<A> FromIterator<A> for Box<[A]> {
784 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
785 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
789 #[stable(feature = "box_slice_clone", since = "1.3.0")]
790 impl<T: Clone> Clone for Box<[T]> {
791 fn clone(&self) -> Self {
792 let mut new = BoxBuilder {
793 data: RawVec::with_capacity(self.len()),
797 let mut target = new.data.ptr();
799 for item in self.iter() {
801 ptr::write(target, item.clone());
802 target = target.offset(1);
808 return unsafe { new.into_box() };
810 // Helper type for responding to panics correctly.
811 struct BoxBuilder<T> {
816 impl<T> BoxBuilder<T> {
817 unsafe fn into_box(self) -> Box<[T]> {
818 let raw = ptr::read(&self.data);
824 impl<T> Drop for BoxBuilder<T> {
826 let mut data = self.data.ptr();
827 let max = unsafe { data.add(self.len) };
832 data = data.offset(1);
840 #[stable(feature = "box_borrow", since = "1.1.0")]
841 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
842 fn borrow(&self) -> &T {
847 #[stable(feature = "box_borrow", since = "1.1.0")]
848 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
849 fn borrow_mut(&mut self) -> &mut T {
854 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
855 impl<T: ?Sized> AsRef<T> for Box<T> {
856 fn as_ref(&self) -> &T {
861 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
862 impl<T: ?Sized> AsMut<T> for Box<T> {
863 fn as_mut(&mut self) -> &mut T {
870 * We could have chosen not to add this impl, and instead have written a
871 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
872 * because Box<T> implements Unpin even when T does not, as a result of
875 * We chose this API instead of the alternative for a few reasons:
876 * - Logically, it is helpful to understand pinning in regard to the
877 * memory region being pointed to. For this reason none of the
878 * standard library pointer types support projecting through a pin
879 * (Box<T> is the only pointer type in std for which this would be
881 * - It is in practice very useful to have Box<T> be unconditionally
882 * Unpin because of trait objects, for which the structural auto
883 * trait functionality does not apply (e.g., Box<dyn Foo> would
884 * otherwise not be Unpin).
886 * Another type with the same semantics as Box but only a conditional
887 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
888 * could have a method to project a Pin<T> from it.
890 #[stable(feature = "pin", since = "1.33.0")]
891 impl<T: ?Sized> Unpin for Box<T> { }
893 #[unstable(feature = "generator_trait", issue = "43122")]
894 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
895 type Yield = G::Yield;
896 type Return = G::Return;
898 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
899 G::resume(Pin::new(&mut *self))
903 #[unstable(feature = "generator_trait", issue = "43122")]
904 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
905 type Yield = G::Yield;
906 type Return = G::Return;
908 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
909 G::resume((*self).as_mut())
913 #[unstable(feature = "futures_api", issue = "50547")]
914 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
915 type Output = F::Output;
917 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
918 F::poll(Pin::new(&mut *self), cx)