1 //! A pointer type for heap allocation.
3 //! `Box<T>`, casually referred to as a 'box', provides the simplest form of
4 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
5 //! drop their contents when they go out of scope.
9 //! Move a value from the stack to the heap by creating a [`Box`]:
13 //! let boxed: Box<u8> = Box::new(val);
16 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
19 //! let boxed: Box<u8> = Box::new(5);
20 //! let val: u8 = *boxed;
23 //! Creating a recursive data structure:
28 //! Cons(T, Box<List<T>>),
33 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //! println!("{:?}", list);
38 //! This will print `Cons(1, Cons(2, Nil))`.
40 //! Recursive structures must be boxed, because if the definition of `Cons`
43 //! ```compile_fail,E0072
49 //! It wouldn't work. This is because the size of a `List` depends on how many
50 //! elements are in the list, and so we don't know how much memory to allocate
51 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
52 //! big `Cons` needs to be.
56 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
57 //! its allocation. It is valid to convert both ways between a [`Box`] and a
58 //! raw pointer allocated with the [`Global`] allocator, given that the
59 //! [`Layout`] used with the allocator is correct for the type. More precisely,
60 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
61 //! with `Layout::for_value(&*value)` may be converted into a box using
62 //! `Box::<T>::from_raw(value)`. Conversely, the memory backing a `value: *mut
63 //! T` obtained from `Box::<T>::into_raw` may be deallocated using the
64 //! [`Global`] allocator with `Layout::for_value(&*value)`.
67 //! [dereferencing]: ../../std/ops/trait.Deref.html
68 //! [`Box`]: struct.Box.html
69 //! [`Global`]: ../alloc/struct.Global.html
70 //! [`Layout`]: ../alloc/struct.Layout.html
72 #![stable(feature = "rust1", since = "1.0.0")]
76 use core::cmp::Ordering;
77 use core::convert::From;
79 use core::future::Future;
80 use core::hash::{Hash, Hasher};
81 use core::iter::{Iterator, FromIterator, FusedIterator};
82 use core::marker::{Unpin, Unsize};
86 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
88 use core::ptr::{self, NonNull, Unique};
89 use core::task::{Context, Poll};
92 use crate::raw_vec::RawVec;
93 use crate::str::from_boxed_utf8_unchecked;
95 /// A pointer type for heap allocation.
97 /// See the [module-level documentation](../../std/boxed/index.html) for more.
100 #[stable(feature = "rust1", since = "1.0.0")]
101 pub struct Box<T: ?Sized>(Unique<T>);
104 /// Allocates memory on the heap and then places `x` into it.
106 /// This doesn't actually allocate if `T` is zero-sized.
111 /// let five = Box::new(5);
113 #[stable(feature = "rust1", since = "1.0.0")]
115 pub fn new(x: T) -> Box<T> {
119 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
120 /// `x` will be pinned in memory and unable to be moved.
121 #[stable(feature = "pin", since = "1.33.0")]
123 pub fn pin(x: T) -> Pin<Box<T>> {
128 impl<T: ?Sized> Box<T> {
129 /// Constructs a box from a raw pointer.
131 /// After calling this function, the raw pointer is owned by the
132 /// resulting `Box`. Specifically, the `Box` destructor will call
133 /// the destructor of `T` and free the allocated memory. For this
134 /// to be safe, the memory must have been allocated in accordance
135 /// with the [memory layout] used by `Box` .
139 /// This function is unsafe because improper use may lead to
140 /// memory problems. For example, a double-free may occur if the
141 /// function is called twice on the same raw pointer.
144 /// Recreate a `Box` which was previously converted to a raw pointer
145 /// using [`Box::into_raw`]:
147 /// let x = Box::new(5);
148 /// let ptr = Box::into_raw(x);
149 /// let x = unsafe { Box::from_raw(ptr) };
151 /// Manually create a `Box` from scratch by using the global allocator:
153 /// use std::alloc::{alloc, Layout};
156 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
158 /// let x = Box::from_raw(ptr);
162 /// [memory layout]: index.html#memory-layout
163 /// [`Layout`]: ../alloc/struct.Layout.html
164 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
165 #[stable(feature = "box_raw", since = "1.4.0")]
167 pub unsafe fn from_raw(raw: *mut T) -> Self {
168 Box(Unique::new_unchecked(raw))
171 /// Consumes the `Box`, returning a wrapped raw pointer.
173 /// The pointer will be properly aligned and non-null.
175 /// After calling this function, the caller is responsible for the
176 /// memory previously managed by the `Box`. In particular, the
177 /// caller should properly destroy `T` and release the memory, taking
178 /// into account the [memory layout] used by `Box`. The easiest way to
179 /// do this is to convert the raw pointer back into a `Box` with the
180 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
183 /// Note: this is an associated function, which means that you have
184 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
185 /// is so that there is no conflict with a method on the inner type.
188 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
189 /// for automatic cleanup:
191 /// let x = Box::new(String::from("Hello"));
192 /// let ptr = Box::into_raw(x);
193 /// let x = unsafe { Box::from_raw(ptr) };
195 /// Manual cleanup by explicitly running the destructor and deallocating
198 /// use std::alloc::{dealloc, Layout};
201 /// let x = Box::new(String::from("Hello"));
202 /// let p = Box::into_raw(x);
204 /// ptr::drop_in_place(p);
205 /// dealloc(p as *mut u8, Layout::new::<String>());
209 /// [memory layout]: index.html#memory-layout
210 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
211 #[stable(feature = "box_raw", since = "1.4.0")]
213 pub fn into_raw(b: Box<T>) -> *mut T {
214 Box::into_raw_non_null(b).as_ptr()
217 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
219 /// After calling this function, the caller is responsible for the
220 /// memory previously managed by the `Box`. In particular, the
221 /// caller should properly destroy `T` and release the memory. The
222 /// easiest way to do so is to convert the `NonNull<T>` pointer
223 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
226 /// Note: this is an associated function, which means that you have
227 /// to call it as `Box::into_raw_non_null(b)`
228 /// instead of `b.into_raw_non_null()`. This
229 /// is so that there is no conflict with a method on the inner type.
231 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
236 /// #![feature(box_into_raw_non_null)]
239 /// let x = Box::new(5);
240 /// let ptr = Box::into_raw_non_null(x);
242 /// // Clean up the memory by converting the NonNull pointer back
243 /// // into a Box and letting the Box be dropped.
244 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
247 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
249 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
250 Box::into_unique(b).into()
253 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
256 pub fn into_unique(mut b: Box<T>) -> Unique<T> {
257 // Box is kind-of a library type, but recognized as a "unique pointer" by
258 // Stacked Borrows. This function here corresponds to "reborrowing to
259 // a raw pointer", but there is no actual reborrow here -- so
260 // without some care, the pointer we are returning here still carries
261 // the `Uniq` tag. We round-trip through a mutable reference to avoid that.
262 let unique = unsafe { b.0.as_mut() as *mut T };
264 unsafe { Unique::new_unchecked(unique) }
267 /// Consumes and leaks the `Box`, returning a mutable reference,
268 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
269 /// `'a`. If the type has only static references, or none at all, then this
270 /// may be chosen to be `'static`.
272 /// This function is mainly useful for data that lives for the remainder of
273 /// the program's life. Dropping the returned reference will cause a memory
274 /// leak. If this is not acceptable, the reference should first be wrapped
275 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
276 /// then be dropped which will properly destroy `T` and release the
277 /// allocated memory.
279 /// Note: this is an associated function, which means that you have
280 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
281 /// is so that there is no conflict with a method on the inner type.
283 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
291 /// let x = Box::new(41);
292 /// let static_ref: &'static mut usize = Box::leak(x);
293 /// *static_ref += 1;
294 /// assert_eq!(*static_ref, 42);
302 /// let x = vec![1, 2, 3].into_boxed_slice();
303 /// let static_ref = Box::leak(x);
304 /// static_ref[0] = 4;
305 /// assert_eq!(*static_ref, [4, 2, 3]);
308 #[stable(feature = "box_leak", since = "1.26.0")]
310 pub fn leak<'a>(b: Box<T>) -> &'a mut T
312 T: 'a // Technically not needed, but kept to be explicit.
314 unsafe { &mut *Box::into_raw(b) }
317 /// Converts a `Box<T>` into a `Pin<Box<T>>`
319 /// This conversion does not allocate on the heap and happens in place.
321 /// This is also available via [`From`].
322 #[unstable(feature = "box_into_pin", issue = "0")]
323 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
324 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
325 // when `T: !Unpin`, so it's safe to pin it directly without any
326 // additional requirements.
327 unsafe { Pin::new_unchecked(boxed) }
331 #[stable(feature = "rust1", since = "1.0.0")]
332 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
334 // FIXME: Do nothing, drop is currently performed by compiler.
338 #[stable(feature = "rust1", since = "1.0.0")]
339 impl<T: Default> Default for Box<T> {
340 /// Creates a `Box<T>`, with the `Default` value for T.
341 fn default() -> Box<T> {
342 box Default::default()
346 #[stable(feature = "rust1", since = "1.0.0")]
347 impl<T> Default for Box<[T]> {
348 fn default() -> Box<[T]> {
349 Box::<[T; 0]>::new([])
353 #[stable(feature = "default_box_extra", since = "1.17.0")]
354 impl Default for Box<str> {
355 fn default() -> Box<str> {
356 unsafe { from_boxed_utf8_unchecked(Default::default()) }
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl<T: Clone> Clone for Box<T> {
362 /// Returns a new box with a `clone()` of this box's contents.
367 /// let x = Box::new(5);
368 /// let y = x.clone();
372 fn clone(&self) -> Box<T> {
373 box { (**self).clone() }
375 /// Copies `source`'s contents into `self` without creating a new allocation.
380 /// let x = Box::new(5);
381 /// let mut y = Box::new(10);
383 /// y.clone_from(&x);
385 /// assert_eq!(*y, 5);
388 fn clone_from(&mut self, source: &Box<T>) {
389 (**self).clone_from(&(**source));
394 #[stable(feature = "box_slice_clone", since = "1.3.0")]
395 impl Clone for Box<str> {
396 fn clone(&self) -> Self {
397 let len = self.len();
398 let buf = RawVec::with_capacity(len);
400 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
401 from_boxed_utf8_unchecked(buf.into_box())
406 #[stable(feature = "rust1", since = "1.0.0")]
407 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
409 fn eq(&self, other: &Box<T>) -> bool {
410 PartialEq::eq(&**self, &**other)
413 fn ne(&self, other: &Box<T>) -> bool {
414 PartialEq::ne(&**self, &**other)
417 #[stable(feature = "rust1", since = "1.0.0")]
418 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
420 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
421 PartialOrd::partial_cmp(&**self, &**other)
424 fn lt(&self, other: &Box<T>) -> bool {
425 PartialOrd::lt(&**self, &**other)
428 fn le(&self, other: &Box<T>) -> bool {
429 PartialOrd::le(&**self, &**other)
432 fn ge(&self, other: &Box<T>) -> bool {
433 PartialOrd::ge(&**self, &**other)
436 fn gt(&self, other: &Box<T>) -> bool {
437 PartialOrd::gt(&**self, &**other)
440 #[stable(feature = "rust1", since = "1.0.0")]
441 impl<T: ?Sized + Ord> Ord for Box<T> {
443 fn cmp(&self, other: &Box<T>) -> Ordering {
444 Ord::cmp(&**self, &**other)
447 #[stable(feature = "rust1", since = "1.0.0")]
448 impl<T: ?Sized + Eq> Eq for Box<T> {}
450 #[stable(feature = "rust1", since = "1.0.0")]
451 impl<T: ?Sized + Hash> Hash for Box<T> {
452 fn hash<H: Hasher>(&self, state: &mut H) {
453 (**self).hash(state);
457 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
458 impl<T: ?Sized + Hasher> Hasher for Box<T> {
459 fn finish(&self) -> u64 {
462 fn write(&mut self, bytes: &[u8]) {
463 (**self).write(bytes)
465 fn write_u8(&mut self, i: u8) {
468 fn write_u16(&mut self, i: u16) {
469 (**self).write_u16(i)
471 fn write_u32(&mut self, i: u32) {
472 (**self).write_u32(i)
474 fn write_u64(&mut self, i: u64) {
475 (**self).write_u64(i)
477 fn write_u128(&mut self, i: u128) {
478 (**self).write_u128(i)
480 fn write_usize(&mut self, i: usize) {
481 (**self).write_usize(i)
483 fn write_i8(&mut self, i: i8) {
486 fn write_i16(&mut self, i: i16) {
487 (**self).write_i16(i)
489 fn write_i32(&mut self, i: i32) {
490 (**self).write_i32(i)
492 fn write_i64(&mut self, i: i64) {
493 (**self).write_i64(i)
495 fn write_i128(&mut self, i: i128) {
496 (**self).write_i128(i)
498 fn write_isize(&mut self, i: isize) {
499 (**self).write_isize(i)
503 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
504 impl<T> From<T> for Box<T> {
505 /// Converts a generic type `T` into a `Box<T>`
507 /// The conversion allocates on the heap and moves `t`
508 /// from the stack into it.
513 /// let boxed = Box::new(5);
515 /// assert_eq!(Box::from(x), boxed);
517 fn from(t: T) -> Self {
522 #[stable(feature = "pin", since = "1.33.0")]
523 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
524 /// Converts a `Box<T>` into a `Pin<Box<T>>`
526 /// This conversion does not allocate on the heap and happens in place.
527 fn from(boxed: Box<T>) -> Self {
532 #[stable(feature = "box_from_slice", since = "1.17.0")]
533 impl<T: Copy> From<&[T]> for Box<[T]> {
534 /// Converts a `&[T]` into a `Box<[T]>`
536 /// This conversion allocates on the heap
537 /// and performs a copy of `slice`.
541 /// // create a &[u8] which will be used to create a Box<[u8]>
542 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
543 /// let boxed_slice: Box<[u8]> = Box::from(slice);
545 /// println!("{:?}", boxed_slice);
547 fn from(slice: &[T]) -> Box<[T]> {
548 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
549 boxed.copy_from_slice(slice);
554 #[stable(feature = "box_from_slice", since = "1.17.0")]
555 impl From<&str> for Box<str> {
556 /// Converts a `&str` into a `Box<str>`
558 /// This conversion allocates on the heap
559 /// and performs a copy of `s`.
563 /// let boxed: Box<str> = Box::from("hello");
564 /// println!("{}", boxed);
567 fn from(s: &str) -> Box<str> {
568 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
572 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
573 impl From<Box<str>> for Box<[u8]> {
574 /// Converts a `Box<str>>` into a `Box<[u8]>`
576 /// This conversion does not allocate on the heap and happens in place.
580 /// // create a Box<str> which will be used to create a Box<[u8]>
581 /// let boxed: Box<str> = Box::from("hello");
582 /// let boxed_str: Box<[u8]> = Box::from(boxed);
584 /// // create a &[u8] which will be used to create a Box<[u8]>
585 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
586 /// let boxed_slice = Box::from(slice);
588 /// assert_eq!(boxed_slice, boxed_str);
591 fn from(s: Box<str>) -> Self {
592 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
598 #[stable(feature = "rust1", since = "1.0.0")]
599 /// Attempt to downcast the box to a concrete type.
604 /// use std::any::Any;
606 /// fn print_if_string(value: Box<dyn Any>) {
607 /// if let Ok(string) = value.downcast::<String>() {
608 /// println!("String ({}): {}", string.len(), string);
613 /// let my_string = "Hello World".to_string();
614 /// print_if_string(Box::new(my_string));
615 /// print_if_string(Box::new(0i8));
618 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
621 let raw: *mut dyn Any = Box::into_raw(self);
622 Ok(Box::from_raw(raw as *mut T))
630 impl Box<dyn Any + Send> {
632 #[stable(feature = "rust1", since = "1.0.0")]
633 /// Attempt to downcast the box to a concrete type.
638 /// use std::any::Any;
640 /// fn print_if_string(value: Box<dyn Any + Send>) {
641 /// if let Ok(string) = value.downcast::<String>() {
642 /// println!("String ({}): {}", string.len(), string);
647 /// let my_string = "Hello World".to_string();
648 /// print_if_string(Box::new(my_string));
649 /// print_if_string(Box::new(0i8));
652 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
653 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
654 // reapply the Send marker
655 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
660 #[stable(feature = "rust1", since = "1.0.0")]
661 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
662 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
663 fmt::Display::fmt(&**self, f)
667 #[stable(feature = "rust1", since = "1.0.0")]
668 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 fmt::Debug::fmt(&**self, f)
674 #[stable(feature = "rust1", since = "1.0.0")]
675 impl<T: ?Sized> fmt::Pointer for Box<T> {
676 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677 // It's not possible to extract the inner Uniq directly from the Box,
678 // instead we cast it to a *const which aliases the Unique
679 let ptr: *const T = &**self;
680 fmt::Pointer::fmt(&ptr, f)
684 #[stable(feature = "rust1", since = "1.0.0")]
685 impl<T: ?Sized> Deref for Box<T> {
688 fn deref(&self) -> &T {
693 #[stable(feature = "rust1", since = "1.0.0")]
694 impl<T: ?Sized> DerefMut for Box<T> {
695 fn deref_mut(&mut self) -> &mut T {
700 #[unstable(feature = "receiver_trait", issue = "0")]
701 impl<T: ?Sized> Receiver for Box<T> {}
703 #[stable(feature = "rust1", since = "1.0.0")]
704 impl<I: Iterator + ?Sized> Iterator for Box<I> {
706 fn next(&mut self) -> Option<I::Item> {
709 fn size_hint(&self) -> (usize, Option<usize>) {
712 fn nth(&mut self, n: usize) -> Option<I::Item> {
716 #[stable(feature = "rust1", since = "1.0.0")]
717 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
718 fn next_back(&mut self) -> Option<I::Item> {
721 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
725 #[stable(feature = "rust1", since = "1.0.0")]
726 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
727 fn len(&self) -> usize {
730 fn is_empty(&self) -> bool {
735 #[stable(feature = "fused", since = "1.26.0")]
736 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
738 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
739 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
740 type Output = <F as FnOnce<A>>::Output;
742 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
743 <F as FnOnce<A>>::call_once(*self, args)
747 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
748 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
749 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
750 <F as FnMut<A>>::call_mut(self, args)
754 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
755 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
756 extern "rust-call" fn call(&self, args: A) -> Self::Output {
757 <F as Fn<A>>::call(self, args)
761 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
762 /// closure objects. The idea is that where one would normally store a
763 /// `Box<dyn FnOnce()>` in a data structure, you should use
764 /// `Box<dyn FnBox()>`. The two traits behave essentially the same, except
765 /// that a `FnBox` closure can only be called if it is boxed. (Note
766 /// that `FnBox` may be deprecated in the future if `Box<dyn FnOnce()>`
767 /// closures become directly usable.)
771 /// Here is a snippet of code which creates a hashmap full of boxed
772 /// once closures and then removes them one by one, calling each
773 /// closure as it is removed. Note that the type of the closures
774 /// stored in the map is `Box<dyn FnBox() -> i32>` and not `Box<dyn FnOnce()
778 /// #![feature(fnbox)]
780 /// use std::boxed::FnBox;
781 /// use std::collections::HashMap;
783 /// fn make_map() -> HashMap<i32, Box<dyn FnBox() -> i32>> {
784 /// let mut map: HashMap<i32, Box<dyn FnBox() -> i32>> = HashMap::new();
785 /// map.insert(1, Box::new(|| 22));
786 /// map.insert(2, Box::new(|| 44));
791 /// let mut map = make_map();
792 /// for i in &[1, 2] {
793 /// let f = map.remove(&i).unwrap();
794 /// assert_eq!(f(), i * 22);
799 #[unstable(feature = "fnbox",
800 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
801 pub trait FnBox<A>: FnOnce<A> {
802 /// Performs the call operation.
803 fn call_box(self: Box<Self>, args: A) -> Self::Output;
806 #[unstable(feature = "fnbox",
807 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
808 impl<A, F> FnBox<A> for F
811 fn call_box(self: Box<F>, args: A) -> F::Output {
816 #[unstable(feature = "coerce_unsized", issue = "27732")]
817 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
819 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
820 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
822 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
823 impl<A> FromIterator<A> for Box<[A]> {
824 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
825 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
829 #[stable(feature = "box_slice_clone", since = "1.3.0")]
830 impl<T: Clone> Clone for Box<[T]> {
831 fn clone(&self) -> Self {
832 let mut new = BoxBuilder {
833 data: RawVec::with_capacity(self.len()),
837 let mut target = new.data.ptr();
839 for item in self.iter() {
841 ptr::write(target, item.clone());
842 target = target.offset(1);
848 return unsafe { new.into_box() };
850 // Helper type for responding to panics correctly.
851 struct BoxBuilder<T> {
856 impl<T> BoxBuilder<T> {
857 unsafe fn into_box(self) -> Box<[T]> {
858 let raw = ptr::read(&self.data);
864 impl<T> Drop for BoxBuilder<T> {
866 let mut data = self.data.ptr();
867 let max = unsafe { data.add(self.len) };
872 data = data.offset(1);
880 #[stable(feature = "box_borrow", since = "1.1.0")]
881 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
882 fn borrow(&self) -> &T {
887 #[stable(feature = "box_borrow", since = "1.1.0")]
888 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
889 fn borrow_mut(&mut self) -> &mut T {
894 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
895 impl<T: ?Sized> AsRef<T> for Box<T> {
896 fn as_ref(&self) -> &T {
901 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
902 impl<T: ?Sized> AsMut<T> for Box<T> {
903 fn as_mut(&mut self) -> &mut T {
910 * We could have chosen not to add this impl, and instead have written a
911 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
912 * because Box<T> implements Unpin even when T does not, as a result of
915 * We chose this API instead of the alternative for a few reasons:
916 * - Logically, it is helpful to understand pinning in regard to the
917 * memory region being pointed to. For this reason none of the
918 * standard library pointer types support projecting through a pin
919 * (Box<T> is the only pointer type in std for which this would be
921 * - It is in practice very useful to have Box<T> be unconditionally
922 * Unpin because of trait objects, for which the structural auto
923 * trait functionality does not apply (e.g., Box<dyn Foo> would
924 * otherwise not be Unpin).
926 * Another type with the same semantics as Box but only a conditional
927 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
928 * could have a method to project a Pin<T> from it.
930 #[stable(feature = "pin", since = "1.33.0")]
931 impl<T: ?Sized> Unpin for Box<T> { }
933 #[unstable(feature = "generator_trait", issue = "43122")]
934 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
935 type Yield = G::Yield;
936 type Return = G::Return;
938 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
939 G::resume(Pin::new(&mut *self))
943 #[unstable(feature = "generator_trait", issue = "43122")]
944 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
945 type Yield = G::Yield;
946 type Return = G::Return;
948 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
949 G::resume((*self).as_mut())
953 #[stable(feature = "futures_api", since = "1.36.0")]
954 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
955 type Output = F::Output;
957 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
958 F::poll(Pin::new(&mut *self), cx)