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)`.
66 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented as a
67 //! single pointer and is also ABI-compatible with C pointers (i.e. the C type
68 //! `T*`). This means that you can have Rust code which passes ownership of a
69 //! `Box<T>` to C code by using `Box<T>` as the type on the Rust side, and
70 //! `T*` as the corresponding type on the C side. As an example, consider this
71 //! C header which declares functions that create and destroy some kind of
77 //! /* Returns ownership to the caller */
78 //! struct Foo* foo_new(void);
80 //! /* Takes ownership from the caller; no-op when invoked with NULL */
81 //! void foo_delete(struct Foo*);
84 //! These two functions might be implemented in Rust as follows. Here, the
85 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
86 //! the ownership constraints. Note also that the nullable argument to
87 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
95 //! pub extern "C" fn foo_new() -> Box<Foo> {
100 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
103 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
104 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
105 //! and expect things to work. `Box<T>` values will always be fully aligned,
106 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
107 //! free the value with the global allocator. In general, the best practice
108 //! is to only use `Box<T>` for pointers that originated from the global
111 //! [dereferencing]: ../../std/ops/trait.Deref.html
112 //! [`Box`]: struct.Box.html
113 //! [`Global`]: ../alloc/struct.Global.html
114 //! [`Layout`]: ../alloc/struct.Layout.html
116 #![stable(feature = "rust1", since = "1.0.0")]
120 use core::cmp::Ordering;
121 use core::convert::From;
123 use core::future::Future;
124 use core::hash::{Hash, Hasher};
125 use core::iter::{Iterator, FromIterator, FusedIterator};
126 use core::marker::{Unpin, Unsize};
130 CoerceUnsized, DispatchFromDyn, Deref, DerefMut, Receiver, Generator, GeneratorState
132 use core::ptr::{self, NonNull, Unique};
133 use core::task::{Context, Poll};
136 use crate::raw_vec::RawVec;
137 use crate::str::from_boxed_utf8_unchecked;
139 /// A pointer type for heap allocation.
141 /// See the [module-level documentation](../../std/boxed/index.html) for more.
142 #[lang = "owned_box"]
144 #[stable(feature = "rust1", since = "1.0.0")]
145 pub struct Box<T: ?Sized>(Unique<T>);
148 /// Allocates memory on the heap and then places `x` into it.
150 /// This doesn't actually allocate if `T` is zero-sized.
155 /// let five = Box::new(5);
157 #[stable(feature = "rust1", since = "1.0.0")]
159 pub fn new(x: T) -> Box<T> {
163 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
164 /// `x` will be pinned in memory and unable to be moved.
165 #[stable(feature = "pin", since = "1.33.0")]
167 pub fn pin(x: T) -> Pin<Box<T>> {
172 impl<T: ?Sized> Box<T> {
173 /// Constructs a box from a raw pointer.
175 /// After calling this function, the raw pointer is owned by the
176 /// resulting `Box`. Specifically, the `Box` destructor will call
177 /// the destructor of `T` and free the allocated memory. For this
178 /// to be safe, the memory must have been allocated in accordance
179 /// with the [memory layout] used by `Box` .
183 /// This function is unsafe because improper use may lead to
184 /// memory problems. For example, a double-free may occur if the
185 /// function is called twice on the same raw pointer.
188 /// Recreate a `Box` which was previously converted to a raw pointer
189 /// using [`Box::into_raw`]:
191 /// let x = Box::new(5);
192 /// let ptr = Box::into_raw(x);
193 /// let x = unsafe { Box::from_raw(ptr) };
195 /// Manually create a `Box` from scratch by using the global allocator:
197 /// use std::alloc::{alloc, Layout};
200 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
202 /// let x = Box::from_raw(ptr);
206 /// [memory layout]: index.html#memory-layout
207 /// [`Layout`]: ../alloc/struct.Layout.html
208 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
209 #[stable(feature = "box_raw", since = "1.4.0")]
211 pub unsafe fn from_raw(raw: *mut T) -> Self {
212 Box(Unique::new_unchecked(raw))
215 /// Consumes the `Box`, returning a wrapped raw pointer.
217 /// The pointer will be properly aligned and non-null.
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, taking
222 /// into account the [memory layout] used by `Box`. The easiest way to
223 /// do this is to convert the raw pointer back into a `Box` with the
224 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
227 /// Note: this is an associated function, which means that you have
228 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
229 /// is so that there is no conflict with a method on the inner type.
232 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
233 /// for automatic cleanup:
235 /// let x = Box::new(String::from("Hello"));
236 /// let ptr = Box::into_raw(x);
237 /// let x = unsafe { Box::from_raw(ptr) };
239 /// Manual cleanup by explicitly running the destructor and deallocating
242 /// use std::alloc::{dealloc, Layout};
245 /// let x = Box::new(String::from("Hello"));
246 /// let p = Box::into_raw(x);
248 /// ptr::drop_in_place(p);
249 /// dealloc(p as *mut u8, Layout::new::<String>());
253 /// [memory layout]: index.html#memory-layout
254 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
255 #[stable(feature = "box_raw", since = "1.4.0")]
257 pub fn into_raw(b: Box<T>) -> *mut T {
258 Box::into_raw_non_null(b).as_ptr()
261 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
263 /// After calling this function, the caller is responsible for the
264 /// memory previously managed by the `Box`. In particular, the
265 /// caller should properly destroy `T` and release the memory. The
266 /// easiest way to do so is to convert the `NonNull<T>` pointer
267 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
270 /// Note: this is an associated function, which means that you have
271 /// to call it as `Box::into_raw_non_null(b)`
272 /// instead of `b.into_raw_non_null()`. This
273 /// is so that there is no conflict with a method on the inner type.
275 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
280 /// #![feature(box_into_raw_non_null)]
283 /// let x = Box::new(5);
284 /// let ptr = Box::into_raw_non_null(x);
286 /// // Clean up the memory by converting the NonNull pointer back
287 /// // into a Box and letting the Box be dropped.
288 /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
291 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
293 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
294 Box::into_unique(b).into()
297 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
300 pub fn into_unique(b: Box<T>) -> Unique<T> {
301 let mut unique = b.0;
303 // Box is kind-of a library type, but recognized as a "unique pointer" by
304 // Stacked Borrows. This function here corresponds to "reborrowing to
305 // a raw pointer", but there is no actual reborrow here -- so
306 // without some care, the pointer we are returning here still carries
307 // the tag of `b`, with `Unique` permission.
308 // We round-trip through a mutable reference to avoid that.
309 unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
312 /// Consumes and leaks the `Box`, returning a mutable reference,
313 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
314 /// `'a`. If the type has only static references, or none at all, then this
315 /// may be chosen to be `'static`.
317 /// This function is mainly useful for data that lives for the remainder of
318 /// the program's life. Dropping the returned reference will cause a memory
319 /// leak. If this is not acceptable, the reference should first be wrapped
320 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
321 /// then be dropped which will properly destroy `T` and release the
322 /// allocated memory.
324 /// Note: this is an associated function, which means that you have
325 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
326 /// is so that there is no conflict with a method on the inner type.
328 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
336 /// let x = Box::new(41);
337 /// let static_ref: &'static mut usize = Box::leak(x);
338 /// *static_ref += 1;
339 /// assert_eq!(*static_ref, 42);
347 /// let x = vec![1, 2, 3].into_boxed_slice();
348 /// let static_ref = Box::leak(x);
349 /// static_ref[0] = 4;
350 /// assert_eq!(*static_ref, [4, 2, 3]);
353 #[stable(feature = "box_leak", since = "1.26.0")]
355 pub fn leak<'a>(b: Box<T>) -> &'a mut T
357 T: 'a // Technically not needed, but kept to be explicit.
359 unsafe { &mut *Box::into_raw(b) }
362 /// Converts a `Box<T>` into a `Pin<Box<T>>`
364 /// This conversion does not allocate on the heap and happens in place.
366 /// This is also available via [`From`].
367 #[unstable(feature = "box_into_pin", issue = "62370")]
368 pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
369 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
370 // when `T: !Unpin`, so it's safe to pin it directly without any
371 // additional requirements.
372 unsafe { Pin::new_unchecked(boxed) }
376 #[stable(feature = "rust1", since = "1.0.0")]
377 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
379 // FIXME: Do nothing, drop is currently performed by compiler.
383 #[stable(feature = "rust1", since = "1.0.0")]
384 impl<T: Default> Default for Box<T> {
385 /// Creates a `Box<T>`, with the `Default` value for T.
386 fn default() -> Box<T> {
387 box Default::default()
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl<T> Default for Box<[T]> {
393 fn default() -> Box<[T]> {
394 Box::<[T; 0]>::new([])
398 #[stable(feature = "default_box_extra", since = "1.17.0")]
399 impl Default for Box<str> {
400 fn default() -> Box<str> {
401 unsafe { from_boxed_utf8_unchecked(Default::default()) }
405 #[stable(feature = "rust1", since = "1.0.0")]
406 impl<T: Clone> Clone for Box<T> {
407 /// Returns a new box with a `clone()` of this box's contents.
412 /// let x = Box::new(5);
413 /// let y = x.clone();
415 /// // The value is the same
416 /// assert_eq!(x, y);
418 /// // But they are unique objects
419 /// assert_ne!(&*x as *const i32, &*y as *const i32);
423 fn clone(&self) -> Box<T> {
424 box { (**self).clone() }
427 /// Copies `source`'s contents into `self` without creating a new allocation.
432 /// let x = Box::new(5);
433 /// let mut y = Box::new(10);
434 /// let yp: *const i32 = &*y;
436 /// y.clone_from(&x);
438 /// // The value is the same
439 /// assert_eq!(x, y);
441 /// // And no allocation occurred
442 /// assert_eq!(yp, &*y);
445 fn clone_from(&mut self, source: &Box<T>) {
446 (**self).clone_from(&(**source));
451 #[stable(feature = "box_slice_clone", since = "1.3.0")]
452 impl Clone for Box<str> {
453 fn clone(&self) -> Self {
454 // this makes a copy of the data
455 let buf: Box<[u8]> = self.as_bytes().into();
457 from_boxed_utf8_unchecked(buf)
462 #[stable(feature = "rust1", since = "1.0.0")]
463 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
465 fn eq(&self, other: &Box<T>) -> bool {
466 PartialEq::eq(&**self, &**other)
469 fn ne(&self, other: &Box<T>) -> bool {
470 PartialEq::ne(&**self, &**other)
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
476 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
477 PartialOrd::partial_cmp(&**self, &**other)
480 fn lt(&self, other: &Box<T>) -> bool {
481 PartialOrd::lt(&**self, &**other)
484 fn le(&self, other: &Box<T>) -> bool {
485 PartialOrd::le(&**self, &**other)
488 fn ge(&self, other: &Box<T>) -> bool {
489 PartialOrd::ge(&**self, &**other)
492 fn gt(&self, other: &Box<T>) -> bool {
493 PartialOrd::gt(&**self, &**other)
496 #[stable(feature = "rust1", since = "1.0.0")]
497 impl<T: ?Sized + Ord> Ord for Box<T> {
499 fn cmp(&self, other: &Box<T>) -> Ordering {
500 Ord::cmp(&**self, &**other)
503 #[stable(feature = "rust1", since = "1.0.0")]
504 impl<T: ?Sized + Eq> Eq for Box<T> {}
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl<T: ?Sized + Hash> Hash for Box<T> {
508 fn hash<H: Hasher>(&self, state: &mut H) {
509 (**self).hash(state);
513 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
514 impl<T: ?Sized + Hasher> Hasher for Box<T> {
515 fn finish(&self) -> u64 {
518 fn write(&mut self, bytes: &[u8]) {
519 (**self).write(bytes)
521 fn write_u8(&mut self, i: u8) {
524 fn write_u16(&mut self, i: u16) {
525 (**self).write_u16(i)
527 fn write_u32(&mut self, i: u32) {
528 (**self).write_u32(i)
530 fn write_u64(&mut self, i: u64) {
531 (**self).write_u64(i)
533 fn write_u128(&mut self, i: u128) {
534 (**self).write_u128(i)
536 fn write_usize(&mut self, i: usize) {
537 (**self).write_usize(i)
539 fn write_i8(&mut self, i: i8) {
542 fn write_i16(&mut self, i: i16) {
543 (**self).write_i16(i)
545 fn write_i32(&mut self, i: i32) {
546 (**self).write_i32(i)
548 fn write_i64(&mut self, i: i64) {
549 (**self).write_i64(i)
551 fn write_i128(&mut self, i: i128) {
552 (**self).write_i128(i)
554 fn write_isize(&mut self, i: isize) {
555 (**self).write_isize(i)
559 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
560 impl<T> From<T> for Box<T> {
561 /// Converts a generic type `T` into a `Box<T>`
563 /// The conversion allocates on the heap and moves `t`
564 /// from the stack into it.
569 /// let boxed = Box::new(5);
571 /// assert_eq!(Box::from(x), boxed);
573 fn from(t: T) -> Self {
578 #[stable(feature = "pin", since = "1.33.0")]
579 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
580 /// Converts a `Box<T>` into a `Pin<Box<T>>`
582 /// This conversion does not allocate on the heap and happens in place.
583 fn from(boxed: Box<T>) -> Self {
588 #[stable(feature = "box_from_slice", since = "1.17.0")]
589 impl<T: Copy> From<&[T]> for Box<[T]> {
590 /// Converts a `&[T]` into a `Box<[T]>`
592 /// This conversion allocates on the heap
593 /// and performs a copy of `slice`.
597 /// // create a &[u8] which will be used to create a Box<[u8]>
598 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
599 /// let boxed_slice: Box<[u8]> = Box::from(slice);
601 /// println!("{:?}", boxed_slice);
603 fn from(slice: &[T]) -> Box<[T]> {
604 let len = slice.len();
605 let buf = RawVec::with_capacity(len);
607 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
613 #[stable(feature = "box_from_slice", since = "1.17.0")]
614 impl From<&str> for Box<str> {
615 /// Converts a `&str` into a `Box<str>`
617 /// This conversion allocates on the heap
618 /// and performs a copy of `s`.
622 /// let boxed: Box<str> = Box::from("hello");
623 /// println!("{}", boxed);
626 fn from(s: &str) -> Box<str> {
627 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
631 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
632 impl From<Box<str>> for Box<[u8]> {
633 /// Converts a `Box<str>>` into a `Box<[u8]>`
635 /// This conversion does not allocate on the heap and happens in place.
639 /// // create a Box<str> which will be used to create a Box<[u8]>
640 /// let boxed: Box<str> = Box::from("hello");
641 /// let boxed_str: Box<[u8]> = Box::from(boxed);
643 /// // create a &[u8] which will be used to create a Box<[u8]>
644 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
645 /// let boxed_slice = Box::from(slice);
647 /// assert_eq!(boxed_slice, boxed_str);
650 fn from(s: Box<str>) -> Self {
651 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
657 #[stable(feature = "rust1", since = "1.0.0")]
658 /// Attempt to downcast the box to a concrete type.
663 /// use std::any::Any;
665 /// fn print_if_string(value: Box<dyn Any>) {
666 /// if let Ok(string) = value.downcast::<String>() {
667 /// println!("String ({}): {}", string.len(), string);
672 /// let my_string = "Hello World".to_string();
673 /// print_if_string(Box::new(my_string));
674 /// print_if_string(Box::new(0i8));
677 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
680 let raw: *mut dyn Any = Box::into_raw(self);
681 Ok(Box::from_raw(raw as *mut T))
689 impl Box<dyn Any + Send> {
691 #[stable(feature = "rust1", since = "1.0.0")]
692 /// Attempt to downcast the box to a concrete type.
697 /// use std::any::Any;
699 /// fn print_if_string(value: Box<dyn Any + Send>) {
700 /// if let Ok(string) = value.downcast::<String>() {
701 /// println!("String ({}): {}", string.len(), string);
706 /// let my_string = "Hello World".to_string();
707 /// print_if_string(Box::new(my_string));
708 /// print_if_string(Box::new(0i8));
711 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
712 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
713 // reapply the Send marker
714 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
719 #[stable(feature = "rust1", since = "1.0.0")]
720 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
721 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
722 fmt::Display::fmt(&**self, f)
726 #[stable(feature = "rust1", since = "1.0.0")]
727 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
728 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
729 fmt::Debug::fmt(&**self, f)
733 #[stable(feature = "rust1", since = "1.0.0")]
734 impl<T: ?Sized> fmt::Pointer for Box<T> {
735 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
736 // It's not possible to extract the inner Uniq directly from the Box,
737 // instead we cast it to a *const which aliases the Unique
738 let ptr: *const T = &**self;
739 fmt::Pointer::fmt(&ptr, f)
743 #[stable(feature = "rust1", since = "1.0.0")]
744 impl<T: ?Sized> Deref for Box<T> {
747 fn deref(&self) -> &T {
752 #[stable(feature = "rust1", since = "1.0.0")]
753 impl<T: ?Sized> DerefMut for Box<T> {
754 fn deref_mut(&mut self) -> &mut T {
759 #[unstable(feature = "receiver_trait", issue = "0")]
760 impl<T: ?Sized> Receiver for Box<T> {}
762 #[stable(feature = "rust1", since = "1.0.0")]
763 impl<I: Iterator + ?Sized> Iterator for Box<I> {
765 fn next(&mut self) -> Option<I::Item> {
768 fn size_hint(&self) -> (usize, Option<usize>) {
771 fn nth(&mut self, n: usize) -> Option<I::Item> {
776 #[stable(feature = "rust1", since = "1.0.0")]
777 impl<I: Iterator + Sized> Iterator for Box<I> {
778 fn last(self) -> Option<I::Item> where I: Sized {
783 #[stable(feature = "rust1", since = "1.0.0")]
784 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
785 fn next_back(&mut self) -> Option<I::Item> {
788 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
792 #[stable(feature = "rust1", since = "1.0.0")]
793 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
794 fn len(&self) -> usize {
797 fn is_empty(&self) -> bool {
802 #[stable(feature = "fused", since = "1.26.0")]
803 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
805 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
806 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
807 type Output = <F as FnOnce<A>>::Output;
809 extern "rust-call" fn call_once(self, args: A) -> Self::Output {
810 <F as FnOnce<A>>::call_once(*self, args)
814 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
815 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
816 extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
817 <F as FnMut<A>>::call_mut(self, args)
821 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
822 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
823 extern "rust-call" fn call(&self, args: A) -> Self::Output {
824 <F as Fn<A>>::call(self, args)
828 #[unstable(feature = "coerce_unsized", issue = "27732")]
829 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
831 #[unstable(feature = "dispatch_from_dyn", issue = "0")]
832 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
834 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
835 impl<A> FromIterator<A> for Box<[A]> {
836 fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
837 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
841 #[stable(feature = "box_slice_clone", since = "1.3.0")]
842 impl<T: Clone> Clone for Box<[T]> {
843 fn clone(&self) -> Self {
844 let mut new = BoxBuilder {
845 data: RawVec::with_capacity(self.len()),
849 let mut target = new.data.ptr();
851 for item in self.iter() {
853 ptr::write(target, item.clone());
854 target = target.offset(1);
860 return unsafe { new.into_box() };
862 // Helper type for responding to panics correctly.
863 struct BoxBuilder<T> {
868 impl<T> BoxBuilder<T> {
869 unsafe fn into_box(self) -> Box<[T]> {
870 let raw = ptr::read(&self.data);
876 impl<T> Drop for BoxBuilder<T> {
878 let mut data = self.data.ptr();
879 let max = unsafe { data.add(self.len) };
884 data = data.offset(1);
892 #[stable(feature = "box_borrow", since = "1.1.0")]
893 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
894 fn borrow(&self) -> &T {
899 #[stable(feature = "box_borrow", since = "1.1.0")]
900 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
901 fn borrow_mut(&mut self) -> &mut T {
906 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
907 impl<T: ?Sized> AsRef<T> for Box<T> {
908 fn as_ref(&self) -> &T {
913 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
914 impl<T: ?Sized> AsMut<T> for Box<T> {
915 fn as_mut(&mut self) -> &mut T {
922 * We could have chosen not to add this impl, and instead have written a
923 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
924 * because Box<T> implements Unpin even when T does not, as a result of
927 * We chose this API instead of the alternative for a few reasons:
928 * - Logically, it is helpful to understand pinning in regard to the
929 * memory region being pointed to. For this reason none of the
930 * standard library pointer types support projecting through a pin
931 * (Box<T> is the only pointer type in std for which this would be
933 * - It is in practice very useful to have Box<T> be unconditionally
934 * Unpin because of trait objects, for which the structural auto
935 * trait functionality does not apply (e.g., Box<dyn Foo> would
936 * otherwise not be Unpin).
938 * Another type with the same semantics as Box but only a conditional
939 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
940 * could have a method to project a Pin<T> from it.
942 #[stable(feature = "pin", since = "1.33.0")]
943 impl<T: ?Sized> Unpin for Box<T> { }
945 #[unstable(feature = "generator_trait", issue = "43122")]
946 impl<G: ?Sized + Generator + Unpin> Generator for Box<G> {
947 type Yield = G::Yield;
948 type Return = G::Return;
950 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
951 G::resume(Pin::new(&mut *self))
955 #[unstable(feature = "generator_trait", issue = "43122")]
956 impl<G: ?Sized + Generator> Generator for Pin<Box<G>> {
957 type Yield = G::Yield;
958 type Return = G::Return;
960 fn resume(mut self: Pin<&mut Self>) -> GeneratorState<Self::Yield, Self::Return> {
961 G::resume((*self).as_mut())
965 #[stable(feature = "futures_api", since = "1.36.0")]
966 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
967 type Output = F::Output;
969 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
970 F::poll(Pin::new(&mut *self), cx)