]> git.lizzy.rs Git - rust.git/blob - src/liballoc/boxed.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / liballoc / boxed.rs
1 //! A pointer type for heap allocation.
2 //!
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. Boxes also ensure that they
6 //! never allocate more than `isize::MAX` bytes.
7 //!
8 //! # Examples
9 //!
10 //! Move a value from the stack to the heap by creating a [`Box`]:
11 //!
12 //! ```
13 //! let val: u8 = 5;
14 //! let boxed: Box<u8> = Box::new(val);
15 //! ```
16 //!
17 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
18 //!
19 //! ```
20 //! let boxed: Box<u8> = Box::new(5);
21 //! let val: u8 = *boxed;
22 //! ```
23 //!
24 //! Creating a recursive data structure:
25 //!
26 //! ```
27 //! #[derive(Debug)]
28 //! enum List<T> {
29 //!     Cons(T, Box<List<T>>),
30 //!     Nil,
31 //! }
32 //!
33 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //! println!("{:?}", list);
35 //! ```
36 //!
37 //! This will print `Cons(1, Cons(2, Nil))`.
38 //!
39 //! Recursive structures must be boxed, because if the definition of `Cons`
40 //! looked like this:
41 //!
42 //! ```compile_fail,E0072
43 //! # enum List<T> {
44 //! Cons(T, List<T>),
45 //! # }
46 //! ```
47 //!
48 //! It wouldn't work. This is because the size of a `List` depends on how many
49 //! elements are in the list, and so we don't know how much memory to allocate
50 //! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
51 //! big `Cons` needs to be.
52 //!
53 //! # Memory layout
54 //!
55 //! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
56 //! its allocation. It is valid to convert both ways between a [`Box`] and a
57 //! raw pointer allocated with the [`Global`] allocator, given that the
58 //! [`Layout`] used with the allocator is correct for the type. More precisely,
59 //! a `value: *mut T` that has been allocated with the [`Global`] allocator
60 //! with `Layout::for_value(&*value)` may be converted into a box using
61 //! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
62 //! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
63 //! [`Global`] allocator with [`Layout::for_value(&*value)`].
64 //!
65 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
66 //! as a single pointer and is also ABI-compatible with C pointers
67 //! (i.e. the C type `T*`). This means that if you have extern "C"
68 //! Rust functions that will be called from C, you can define those
69 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
70 //! type on the C side. As an example, consider this C header which
71 //! declares functions that create and destroy some kind of `Foo`
72 //! value:
73 //!
74 //! ```c
75 //! /* C header */
76 //!
77 //! /* Returns ownership to the caller */
78 //! struct Foo* foo_new(void);
79 //!
80 //! /* Takes ownership from the caller; no-op when invoked with NULL */
81 //! void foo_delete(struct Foo*);
82 //! ```
83 //!
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>`
88 //! cannot be null.
89 //!
90 //! ```
91 //! #[repr(C)]
92 //! pub struct Foo;
93 //!
94 //! #[no_mangle]
95 //! pub extern "C" fn foo_new() -> Box<Foo> {
96 //!     Box::new(Foo)
97 //! }
98 //!
99 //! #[no_mangle]
100 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
101 //! ```
102 //!
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
109 //! allocator.
110 //!
111 //! **Important.** At least at present, you should avoid using
112 //! `Box<T>` types for functions that are defined in C but invoked
113 //! from Rust. In those cases, you should directly mirror the C types
114 //! as closely as possible. Using types like `Box<T>` where the C
115 //! definition is just using `T*` can lead to undefined behavior, as
116 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
117 //!
118 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
119 //! [dereferencing]: ../../std/ops/trait.Deref.html
120 //! [`Box`]: struct.Box.html
121 //! [`Box<T>`]: struct.Box.html
122 //! [`Box::<T>::from_raw(value)`]: struct.Box.html#method.from_raw
123 //! [`Box::<T>::into_raw`]: struct.Box.html#method.into_raw
124 //! [`Global`]: ../alloc/struct.Global.html
125 //! [`Layout`]: ../alloc/struct.Layout.html
126 //! [`Layout::for_value(&*value)`]: ../alloc/struct.Layout.html#method.for_value
127
128 #![stable(feature = "rust1", since = "1.0.0")]
129
130 use core::any::Any;
131 use core::array::LengthAtMost32;
132 use core::borrow;
133 use core::cmp::Ordering;
134 use core::convert::{From, TryFrom};
135 use core::fmt;
136 use core::future::Future;
137 use core::hash::{Hash, Hasher};
138 use core::iter::{FromIterator, FusedIterator, Iterator};
139 use core::marker::{Unpin, Unsize};
140 use core::mem;
141 use core::ops::{
142     CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
143 };
144 use core::pin::Pin;
145 use core::ptr::{self, NonNull, Unique};
146 use core::slice;
147 use core::task::{Context, Poll};
148
149 use crate::alloc::{self, AllocRef, Global};
150 use crate::raw_vec::RawVec;
151 use crate::str::from_boxed_utf8_unchecked;
152 use crate::vec::Vec;
153
154 /// A pointer type for heap allocation.
155 ///
156 /// See the [module-level documentation](../../std/boxed/index.html) for more.
157 #[lang = "owned_box"]
158 #[fundamental]
159 #[stable(feature = "rust1", since = "1.0.0")]
160 pub struct Box<T: ?Sized>(Unique<T>);
161
162 impl<T> Box<T> {
163     /// Allocates memory on the heap and then places `x` into it.
164     ///
165     /// This doesn't actually allocate if `T` is zero-sized.
166     ///
167     /// # Examples
168     ///
169     /// ```
170     /// let five = Box::new(5);
171     /// ```
172     #[stable(feature = "rust1", since = "1.0.0")]
173     #[inline(always)]
174     pub fn new(x: T) -> Box<T> {
175         box x
176     }
177
178     /// Constructs a new box with uninitialized contents.
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// #![feature(new_uninit)]
184     ///
185     /// let mut five = Box::<u32>::new_uninit();
186     ///
187     /// let five = unsafe {
188     ///     // Deferred initialization:
189     ///     five.as_mut_ptr().write(5);
190     ///
191     ///     five.assume_init()
192     /// };
193     ///
194     /// assert_eq!(*five, 5)
195     /// ```
196     #[unstable(feature = "new_uninit", issue = "63291")]
197     pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
198         let layout = alloc::Layout::new::<mem::MaybeUninit<T>>();
199         unsafe {
200             let ptr = if layout.size() == 0 {
201                 NonNull::dangling()
202             } else {
203                 Global.alloc(layout).unwrap_or_else(|_| alloc::handle_alloc_error(layout)).0.cast()
204             };
205             Box::from_raw(ptr.as_ptr())
206         }
207     }
208
209     /// Constructs a new `Box` with uninitialized contents, with the memory
210     /// being filled with `0` bytes.
211     ///
212     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
213     /// of this method.
214     ///
215     /// # Examples
216     ///
217     /// ```
218     /// #![feature(new_uninit)]
219     ///
220     /// let zero = Box::<u32>::new_zeroed();
221     /// let zero = unsafe { zero.assume_init() };
222     ///
223     /// assert_eq!(*zero, 0)
224     /// ```
225     ///
226     /// [zeroed]: ../../std/mem/union.MaybeUninit.html#method.zeroed
227     #[unstable(feature = "new_uninit", issue = "63291")]
228     pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
229         unsafe {
230             let mut uninit = Self::new_uninit();
231             ptr::write_bytes::<T>(uninit.as_mut_ptr(), 0, 1);
232             uninit
233         }
234     }
235
236     /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
237     /// `x` will be pinned in memory and unable to be moved.
238     #[stable(feature = "pin", since = "1.33.0")]
239     #[inline(always)]
240     pub fn pin(x: T) -> Pin<Box<T>> {
241         (box x).into()
242     }
243 }
244
245 impl<T> Box<[T]> {
246     /// Constructs a new boxed slice with uninitialized contents.
247     ///
248     /// # Examples
249     ///
250     /// ```
251     /// #![feature(new_uninit)]
252     ///
253     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
254     ///
255     /// let values = unsafe {
256     ///     // Deferred initialization:
257     ///     values[0].as_mut_ptr().write(1);
258     ///     values[1].as_mut_ptr().write(2);
259     ///     values[2].as_mut_ptr().write(3);
260     ///
261     ///     values.assume_init()
262     /// };
263     ///
264     /// assert_eq!(*values, [1, 2, 3])
265     /// ```
266     #[unstable(feature = "new_uninit", issue = "63291")]
267     pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
268         let layout = alloc::Layout::array::<mem::MaybeUninit<T>>(len).unwrap();
269         unsafe {
270             let ptr = if layout.size() == 0 {
271                 NonNull::dangling()
272             } else {
273                 Global.alloc(layout).unwrap_or_else(|_| alloc::handle_alloc_error(layout)).0.cast()
274             };
275             Box::from_raw(slice::from_raw_parts_mut(ptr.as_ptr(), len))
276         }
277     }
278 }
279
280 impl<T> Box<mem::MaybeUninit<T>> {
281     /// Converts to `Box<T>`.
282     ///
283     /// # Safety
284     ///
285     /// As with [`MaybeUninit::assume_init`],
286     /// it is up to the caller to guarantee that the value
287     /// really is in an initialized state.
288     /// Calling this when the content is not yet fully initialized
289     /// causes immediate undefined behavior.
290     ///
291     /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
292     ///
293     /// # Examples
294     ///
295     /// ```
296     /// #![feature(new_uninit)]
297     ///
298     /// let mut five = Box::<u32>::new_uninit();
299     ///
300     /// let five: Box<u32> = unsafe {
301     ///     // Deferred initialization:
302     ///     five.as_mut_ptr().write(5);
303     ///
304     ///     five.assume_init()
305     /// };
306     ///
307     /// assert_eq!(*five, 5)
308     /// ```
309     #[unstable(feature = "new_uninit", issue = "63291")]
310     #[inline]
311     pub unsafe fn assume_init(self) -> Box<T> {
312         Box::from_raw(Box::into_raw(self) as *mut T)
313     }
314 }
315
316 impl<T> Box<[mem::MaybeUninit<T>]> {
317     /// Converts to `Box<[T]>`.
318     ///
319     /// # Safety
320     ///
321     /// As with [`MaybeUninit::assume_init`],
322     /// it is up to the caller to guarantee that the values
323     /// really are in an initialized state.
324     /// Calling this when the content is not yet fully initialized
325     /// causes immediate undefined behavior.
326     ///
327     /// [`MaybeUninit::assume_init`]: ../../std/mem/union.MaybeUninit.html#method.assume_init
328     ///
329     /// # Examples
330     ///
331     /// ```
332     /// #![feature(new_uninit)]
333     ///
334     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
335     ///
336     /// let values = unsafe {
337     ///     // Deferred initialization:
338     ///     values[0].as_mut_ptr().write(1);
339     ///     values[1].as_mut_ptr().write(2);
340     ///     values[2].as_mut_ptr().write(3);
341     ///
342     ///     values.assume_init()
343     /// };
344     ///
345     /// assert_eq!(*values, [1, 2, 3])
346     /// ```
347     #[unstable(feature = "new_uninit", issue = "63291")]
348     #[inline]
349     pub unsafe fn assume_init(self) -> Box<[T]> {
350         Box::from_raw(Box::into_raw(self) as *mut [T])
351     }
352 }
353
354 impl<T: ?Sized> Box<T> {
355     /// Constructs a box from a raw pointer.
356     ///
357     /// After calling this function, the raw pointer is owned by the
358     /// resulting `Box`. Specifically, the `Box` destructor will call
359     /// the destructor of `T` and free the allocated memory. For this
360     /// to be safe, the memory must have been allocated in accordance
361     /// with the [memory layout] used by `Box` .
362     ///
363     /// # Safety
364     ///
365     /// This function is unsafe because improper use may lead to
366     /// memory problems. For example, a double-free may occur if the
367     /// function is called twice on the same raw pointer.
368     ///
369     /// # Examples
370     /// Recreate a `Box` which was previously converted to a raw pointer
371     /// using [`Box::into_raw`]:
372     /// ```
373     /// let x = Box::new(5);
374     /// let ptr = Box::into_raw(x);
375     /// let x = unsafe { Box::from_raw(ptr) };
376     /// ```
377     /// Manually create a `Box` from scratch by using the global allocator:
378     /// ```
379     /// use std::alloc::{alloc, Layout};
380     ///
381     /// unsafe {
382     ///     let ptr = alloc(Layout::new::<i32>()) as *mut i32;
383     ///     *ptr = 5;
384     ///     let x = Box::from_raw(ptr);
385     /// }
386     /// ```
387     ///
388     /// [memory layout]: index.html#memory-layout
389     /// [`Layout`]: ../alloc/struct.Layout.html
390     /// [`Box::into_raw`]: struct.Box.html#method.into_raw
391     #[stable(feature = "box_raw", since = "1.4.0")]
392     #[inline]
393     pub unsafe fn from_raw(raw: *mut T) -> Self {
394         Box(Unique::new_unchecked(raw))
395     }
396
397     /// Consumes the `Box`, returning a wrapped raw pointer.
398     ///
399     /// The pointer will be properly aligned and non-null.
400     ///
401     /// After calling this function, the caller is responsible for the
402     /// memory previously managed by the `Box`. In particular, the
403     /// caller should properly destroy `T` and release the memory, taking
404     /// into account the [memory layout] used by `Box`. The easiest way to
405     /// do this is to convert the raw pointer back into a `Box` with the
406     /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
407     /// the cleanup.
408     ///
409     /// Note: this is an associated function, which means that you have
410     /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
411     /// is so that there is no conflict with a method on the inner type.
412     ///
413     /// # Examples
414     /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
415     /// for automatic cleanup:
416     /// ```
417     /// let x = Box::new(String::from("Hello"));
418     /// let ptr = Box::into_raw(x);
419     /// let x = unsafe { Box::from_raw(ptr) };
420     /// ```
421     /// Manual cleanup by explicitly running the destructor and deallocating
422     /// the memory:
423     /// ```
424     /// use std::alloc::{dealloc, Layout};
425     /// use std::ptr;
426     ///
427     /// let x = Box::new(String::from("Hello"));
428     /// let p = Box::into_raw(x);
429     /// unsafe {
430     ///     ptr::drop_in_place(p);
431     ///     dealloc(p as *mut u8, Layout::new::<String>());
432     /// }
433     /// ```
434     ///
435     /// [memory layout]: index.html#memory-layout
436     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
437     #[stable(feature = "box_raw", since = "1.4.0")]
438     #[inline]
439     pub fn into_raw(b: Box<T>) -> *mut T {
440         Box::into_raw_non_null(b).as_ptr()
441     }
442
443     /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
444     ///
445     /// After calling this function, the caller is responsible for the
446     /// memory previously managed by the `Box`. In particular, the
447     /// caller should properly destroy `T` and release the memory. The
448     /// easiest way to do so is to convert the `NonNull<T>` pointer
449     /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
450     /// function.
451     ///
452     /// Note: this is an associated function, which means that you have
453     /// to call it as `Box::into_raw_non_null(b)`
454     /// instead of `b.into_raw_non_null()`. This
455     /// is so that there is no conflict with a method on the inner type.
456     ///
457     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
458     ///
459     /// # Examples
460     ///
461     /// ```
462     /// #![feature(box_into_raw_non_null)]
463     ///
464     /// let x = Box::new(5);
465     /// let ptr = Box::into_raw_non_null(x);
466     ///
467     /// // Clean up the memory by converting the NonNull pointer back
468     /// // into a Box and letting the Box be dropped.
469     /// let x = unsafe { Box::from_raw(ptr.as_ptr()) };
470     /// ```
471     #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
472     #[inline]
473     pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
474         Box::into_unique(b).into()
475     }
476
477     #[unstable(feature = "ptr_internals", issue = "none", reason = "use into_raw_non_null instead")]
478     #[inline]
479     #[doc(hidden)]
480     pub fn into_unique(b: Box<T>) -> Unique<T> {
481         let mut unique = b.0;
482         mem::forget(b);
483         // Box is kind-of a library type, but recognized as a "unique pointer" by
484         // Stacked Borrows.  This function here corresponds to "reborrowing to
485         // a raw pointer", but there is no actual reborrow here -- so
486         // without some care, the pointer we are returning here still carries
487         // the tag of `b`, with `Unique` permission.
488         // We round-trip through a mutable reference to avoid that.
489         unsafe { Unique::new_unchecked(unique.as_mut() as *mut T) }
490     }
491
492     /// Consumes and leaks the `Box`, returning a mutable reference,
493     /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
494     /// `'a`. If the type has only static references, or none at all, then this
495     /// may be chosen to be `'static`.
496     ///
497     /// This function is mainly useful for data that lives for the remainder of
498     /// the program's life. Dropping the returned reference will cause a memory
499     /// leak. If this is not acceptable, the reference should first be wrapped
500     /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
501     /// then be dropped which will properly destroy `T` and release the
502     /// allocated memory.
503     ///
504     /// Note: this is an associated function, which means that you have
505     /// to call it as `Box::leak(b)` instead of `b.leak()`. This
506     /// is so that there is no conflict with a method on the inner type.
507     ///
508     /// [`Box::from_raw`]: struct.Box.html#method.from_raw
509     ///
510     /// # Examples
511     ///
512     /// Simple usage:
513     ///
514     /// ```
515     /// let x = Box::new(41);
516     /// let static_ref: &'static mut usize = Box::leak(x);
517     /// *static_ref += 1;
518     /// assert_eq!(*static_ref, 42);
519     /// ```
520     ///
521     /// Unsized data:
522     ///
523     /// ```
524     /// let x = vec![1, 2, 3].into_boxed_slice();
525     /// let static_ref = Box::leak(x);
526     /// static_ref[0] = 4;
527     /// assert_eq!(*static_ref, [4, 2, 3]);
528     /// ```
529     #[stable(feature = "box_leak", since = "1.26.0")]
530     #[inline]
531     pub fn leak<'a>(b: Box<T>) -> &'a mut T
532     where
533         T: 'a, // Technically not needed, but kept to be explicit.
534     {
535         unsafe { &mut *Box::into_raw(b) }
536     }
537
538     /// Converts a `Box<T>` into a `Pin<Box<T>>`
539     ///
540     /// This conversion does not allocate on the heap and happens in place.
541     ///
542     /// This is also available via [`From`].
543     #[unstable(feature = "box_into_pin", issue = "62370")]
544     pub fn into_pin(boxed: Box<T>) -> Pin<Box<T>> {
545         // It's not possible to move or replace the insides of a `Pin<Box<T>>`
546         // when `T: !Unpin`,  so it's safe to pin it directly without any
547         // additional requirements.
548         unsafe { Pin::new_unchecked(boxed) }
549     }
550 }
551
552 #[stable(feature = "rust1", since = "1.0.0")]
553 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
554     fn drop(&mut self) {
555         // FIXME: Do nothing, drop is currently performed by compiler.
556     }
557 }
558
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl<T: Default> Default for Box<T> {
561     /// Creates a `Box<T>`, with the `Default` value for T.
562     fn default() -> Box<T> {
563         box Default::default()
564     }
565 }
566
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl<T> Default for Box<[T]> {
569     fn default() -> Box<[T]> {
570         Box::<[T; 0]>::new([])
571     }
572 }
573
574 #[stable(feature = "default_box_extra", since = "1.17.0")]
575 impl Default for Box<str> {
576     fn default() -> Box<str> {
577         unsafe { from_boxed_utf8_unchecked(Default::default()) }
578     }
579 }
580
581 #[stable(feature = "rust1", since = "1.0.0")]
582 impl<T: Clone> Clone for Box<T> {
583     /// Returns a new box with a `clone()` of this box's contents.
584     ///
585     /// # Examples
586     ///
587     /// ```
588     /// let x = Box::new(5);
589     /// let y = x.clone();
590     ///
591     /// // The value is the same
592     /// assert_eq!(x, y);
593     ///
594     /// // But they are unique objects
595     /// assert_ne!(&*x as *const i32, &*y as *const i32);
596     /// ```
597     #[rustfmt::skip]
598     #[inline]
599     fn clone(&self) -> Box<T> {
600         box { (**self).clone() }
601     }
602
603     /// Copies `source`'s contents into `self` without creating a new allocation.
604     ///
605     /// # Examples
606     ///
607     /// ```
608     /// let x = Box::new(5);
609     /// let mut y = Box::new(10);
610     /// let yp: *const i32 = &*y;
611     ///
612     /// y.clone_from(&x);
613     ///
614     /// // The value is the same
615     /// assert_eq!(x, y);
616     ///
617     /// // And no allocation occurred
618     /// assert_eq!(yp, &*y);
619     /// ```
620     #[inline]
621     fn clone_from(&mut self, source: &Box<T>) {
622         (**self).clone_from(&(**source));
623     }
624 }
625
626 #[stable(feature = "box_slice_clone", since = "1.3.0")]
627 impl Clone for Box<str> {
628     fn clone(&self) -> Self {
629         // this makes a copy of the data
630         let buf: Box<[u8]> = self.as_bytes().into();
631         unsafe { from_boxed_utf8_unchecked(buf) }
632     }
633 }
634
635 #[stable(feature = "rust1", since = "1.0.0")]
636 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
637     #[inline]
638     fn eq(&self, other: &Box<T>) -> bool {
639         PartialEq::eq(&**self, &**other)
640     }
641     #[inline]
642     fn ne(&self, other: &Box<T>) -> bool {
643         PartialEq::ne(&**self, &**other)
644     }
645 }
646 #[stable(feature = "rust1", since = "1.0.0")]
647 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
648     #[inline]
649     fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
650         PartialOrd::partial_cmp(&**self, &**other)
651     }
652     #[inline]
653     fn lt(&self, other: &Box<T>) -> bool {
654         PartialOrd::lt(&**self, &**other)
655     }
656     #[inline]
657     fn le(&self, other: &Box<T>) -> bool {
658         PartialOrd::le(&**self, &**other)
659     }
660     #[inline]
661     fn ge(&self, other: &Box<T>) -> bool {
662         PartialOrd::ge(&**self, &**other)
663     }
664     #[inline]
665     fn gt(&self, other: &Box<T>) -> bool {
666         PartialOrd::gt(&**self, &**other)
667     }
668 }
669 #[stable(feature = "rust1", since = "1.0.0")]
670 impl<T: ?Sized + Ord> Ord for Box<T> {
671     #[inline]
672     fn cmp(&self, other: &Box<T>) -> Ordering {
673         Ord::cmp(&**self, &**other)
674     }
675 }
676 #[stable(feature = "rust1", since = "1.0.0")]
677 impl<T: ?Sized + Eq> Eq for Box<T> {}
678
679 #[stable(feature = "rust1", since = "1.0.0")]
680 impl<T: ?Sized + Hash> Hash for Box<T> {
681     fn hash<H: Hasher>(&self, state: &mut H) {
682         (**self).hash(state);
683     }
684 }
685
686 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
687 impl<T: ?Sized + Hasher> Hasher for Box<T> {
688     fn finish(&self) -> u64 {
689         (**self).finish()
690     }
691     fn write(&mut self, bytes: &[u8]) {
692         (**self).write(bytes)
693     }
694     fn write_u8(&mut self, i: u8) {
695         (**self).write_u8(i)
696     }
697     fn write_u16(&mut self, i: u16) {
698         (**self).write_u16(i)
699     }
700     fn write_u32(&mut self, i: u32) {
701         (**self).write_u32(i)
702     }
703     fn write_u64(&mut self, i: u64) {
704         (**self).write_u64(i)
705     }
706     fn write_u128(&mut self, i: u128) {
707         (**self).write_u128(i)
708     }
709     fn write_usize(&mut self, i: usize) {
710         (**self).write_usize(i)
711     }
712     fn write_i8(&mut self, i: i8) {
713         (**self).write_i8(i)
714     }
715     fn write_i16(&mut self, i: i16) {
716         (**self).write_i16(i)
717     }
718     fn write_i32(&mut self, i: i32) {
719         (**self).write_i32(i)
720     }
721     fn write_i64(&mut self, i: i64) {
722         (**self).write_i64(i)
723     }
724     fn write_i128(&mut self, i: i128) {
725         (**self).write_i128(i)
726     }
727     fn write_isize(&mut self, i: isize) {
728         (**self).write_isize(i)
729     }
730 }
731
732 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
733 impl<T> From<T> for Box<T> {
734     /// Converts a generic type `T` into a `Box<T>`
735     ///
736     /// The conversion allocates on the heap and moves `t`
737     /// from the stack into it.
738     ///
739     /// # Examples
740     /// ```rust
741     /// let x = 5;
742     /// let boxed = Box::new(5);
743     ///
744     /// assert_eq!(Box::from(x), boxed);
745     /// ```
746     fn from(t: T) -> Self {
747         Box::new(t)
748     }
749 }
750
751 #[stable(feature = "pin", since = "1.33.0")]
752 impl<T: ?Sized> From<Box<T>> for Pin<Box<T>> {
753     /// Converts a `Box<T>` into a `Pin<Box<T>>`
754     ///
755     /// This conversion does not allocate on the heap and happens in place.
756     fn from(boxed: Box<T>) -> Self {
757         Box::into_pin(boxed)
758     }
759 }
760
761 #[stable(feature = "box_from_slice", since = "1.17.0")]
762 impl<T: Copy> From<&[T]> for Box<[T]> {
763     /// Converts a `&[T]` into a `Box<[T]>`
764     ///
765     /// This conversion allocates on the heap
766     /// and performs a copy of `slice`.
767     ///
768     /// # Examples
769     /// ```rust
770     /// // create a &[u8] which will be used to create a Box<[u8]>
771     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
772     /// let boxed_slice: Box<[u8]> = Box::from(slice);
773     ///
774     /// println!("{:?}", boxed_slice);
775     /// ```
776     fn from(slice: &[T]) -> Box<[T]> {
777         let len = slice.len();
778         let buf = RawVec::with_capacity(len);
779         unsafe {
780             ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
781             buf.into_box()
782         }
783     }
784 }
785
786 #[stable(feature = "box_from_slice", since = "1.17.0")]
787 impl From<&str> for Box<str> {
788     /// Converts a `&str` into a `Box<str>`
789     ///
790     /// This conversion allocates on the heap
791     /// and performs a copy of `s`.
792     ///
793     /// # Examples
794     /// ```rust
795     /// let boxed: Box<str> = Box::from("hello");
796     /// println!("{}", boxed);
797     /// ```
798     #[inline]
799     fn from(s: &str) -> Box<str> {
800         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
801     }
802 }
803
804 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
805 impl From<Box<str>> for Box<[u8]> {
806     /// Converts a `Box<str>>` into a `Box<[u8]>`
807     ///
808     /// This conversion does not allocate on the heap and happens in place.
809     ///
810     /// # Examples
811     /// ```rust
812     /// // create a Box<str> which will be used to create a Box<[u8]>
813     /// let boxed: Box<str> = Box::from("hello");
814     /// let boxed_str: Box<[u8]> = Box::from(boxed);
815     ///
816     /// // create a &[u8] which will be used to create a Box<[u8]>
817     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
818     /// let boxed_slice = Box::from(slice);
819     ///
820     /// assert_eq!(boxed_slice, boxed_str);
821     /// ```
822     #[inline]
823     fn from(s: Box<str>) -> Self {
824         unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
825     }
826 }
827
828 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
829 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]>
830 where
831     [T; N]: LengthAtMost32,
832 {
833     type Error = Box<[T]>;
834
835     fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
836         if boxed_slice.len() == N {
837             Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
838         } else {
839             Err(boxed_slice)
840         }
841     }
842 }
843
844 impl Box<dyn Any> {
845     #[inline]
846     #[stable(feature = "rust1", since = "1.0.0")]
847     /// Attempt to downcast the box to a concrete type.
848     ///
849     /// # Examples
850     ///
851     /// ```
852     /// use std::any::Any;
853     ///
854     /// fn print_if_string(value: Box<dyn Any>) {
855     ///     if let Ok(string) = value.downcast::<String>() {
856     ///         println!("String ({}): {}", string.len(), string);
857     ///     }
858     /// }
859     ///
860     /// let my_string = "Hello World".to_string();
861     /// print_if_string(Box::new(my_string));
862     /// print_if_string(Box::new(0i8));
863     /// ```
864     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
865         if self.is::<T>() {
866             unsafe {
867                 let raw: *mut dyn Any = Box::into_raw(self);
868                 Ok(Box::from_raw(raw as *mut T))
869             }
870         } else {
871             Err(self)
872         }
873     }
874 }
875
876 impl Box<dyn Any + Send> {
877     #[inline]
878     #[stable(feature = "rust1", since = "1.0.0")]
879     /// Attempt to downcast the box to a concrete type.
880     ///
881     /// # Examples
882     ///
883     /// ```
884     /// use std::any::Any;
885     ///
886     /// fn print_if_string(value: Box<dyn Any + Send>) {
887     ///     if let Ok(string) = value.downcast::<String>() {
888     ///         println!("String ({}): {}", string.len(), string);
889     ///     }
890     /// }
891     ///
892     /// let my_string = "Hello World".to_string();
893     /// print_if_string(Box::new(my_string));
894     /// print_if_string(Box::new(0i8));
895     /// ```
896     pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
897         <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
898             // reapply the Send marker
899             Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
900         })
901     }
902 }
903
904 #[stable(feature = "rust1", since = "1.0.0")]
905 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
906     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
907         fmt::Display::fmt(&**self, f)
908     }
909 }
910
911 #[stable(feature = "rust1", since = "1.0.0")]
912 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
913     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
914         fmt::Debug::fmt(&**self, f)
915     }
916 }
917
918 #[stable(feature = "rust1", since = "1.0.0")]
919 impl<T: ?Sized> fmt::Pointer for Box<T> {
920     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921         // It's not possible to extract the inner Uniq directly from the Box,
922         // instead we cast it to a *const which aliases the Unique
923         let ptr: *const T = &**self;
924         fmt::Pointer::fmt(&ptr, f)
925     }
926 }
927
928 #[stable(feature = "rust1", since = "1.0.0")]
929 impl<T: ?Sized> Deref for Box<T> {
930     type Target = T;
931
932     fn deref(&self) -> &T {
933         &**self
934     }
935 }
936
937 #[stable(feature = "rust1", since = "1.0.0")]
938 impl<T: ?Sized> DerefMut for Box<T> {
939     fn deref_mut(&mut self) -> &mut T {
940         &mut **self
941     }
942 }
943
944 #[unstable(feature = "receiver_trait", issue = "none")]
945 impl<T: ?Sized> Receiver for Box<T> {}
946
947 #[stable(feature = "rust1", since = "1.0.0")]
948 impl<I: Iterator + ?Sized> Iterator for Box<I> {
949     type Item = I::Item;
950     fn next(&mut self) -> Option<I::Item> {
951         (**self).next()
952     }
953     fn size_hint(&self) -> (usize, Option<usize>) {
954         (**self).size_hint()
955     }
956     fn nth(&mut self, n: usize) -> Option<I::Item> {
957         (**self).nth(n)
958     }
959     fn last(self) -> Option<I::Item> {
960         BoxIter::last(self)
961     }
962 }
963
964 trait BoxIter {
965     type Item;
966     fn last(self) -> Option<Self::Item>;
967 }
968
969 impl<I: Iterator + ?Sized> BoxIter for Box<I> {
970     type Item = I::Item;
971     default fn last(self) -> Option<I::Item> {
972         #[inline]
973         fn some<T>(_: Option<T>, x: T) -> Option<T> {
974             Some(x)
975         }
976
977         self.fold(None, some)
978     }
979 }
980
981 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
982 /// instead of the default.
983 #[stable(feature = "rust1", since = "1.0.0")]
984 impl<I: Iterator> BoxIter for Box<I> {
985     fn last(self) -> Option<I::Item> {
986         (*self).last()
987     }
988 }
989
990 #[stable(feature = "rust1", since = "1.0.0")]
991 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
992     fn next_back(&mut self) -> Option<I::Item> {
993         (**self).next_back()
994     }
995     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
996         (**self).nth_back(n)
997     }
998 }
999 #[stable(feature = "rust1", since = "1.0.0")]
1000 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
1001     fn len(&self) -> usize {
1002         (**self).len()
1003     }
1004     fn is_empty(&self) -> bool {
1005         (**self).is_empty()
1006     }
1007 }
1008
1009 #[stable(feature = "fused", since = "1.26.0")]
1010 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
1011
1012 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1013 impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
1014     type Output = <F as FnOnce<A>>::Output;
1015
1016     extern "rust-call" fn call_once(self, args: A) -> Self::Output {
1017         <F as FnOnce<A>>::call_once(*self, args)
1018     }
1019 }
1020
1021 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1022 impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
1023     extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
1024         <F as FnMut<A>>::call_mut(self, args)
1025     }
1026 }
1027
1028 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1029 impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
1030     extern "rust-call" fn call(&self, args: A) -> Self::Output {
1031         <F as Fn<A>>::call(self, args)
1032     }
1033 }
1034
1035 #[unstable(feature = "coerce_unsized", issue = "27732")]
1036 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
1037
1038 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1039 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T> {}
1040
1041 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1042 impl<A> FromIterator<A> for Box<[A]> {
1043     fn from_iter<T: IntoIterator<Item = A>>(iter: T) -> Self {
1044         iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1045     }
1046 }
1047
1048 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1049 impl<T: Clone> Clone for Box<[T]> {
1050     fn clone(&self) -> Self {
1051         self.to_vec().into_boxed_slice()
1052     }
1053 }
1054
1055 #[stable(feature = "box_borrow", since = "1.1.0")]
1056 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
1057     fn borrow(&self) -> &T {
1058         &**self
1059     }
1060 }
1061
1062 #[stable(feature = "box_borrow", since = "1.1.0")]
1063 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
1064     fn borrow_mut(&mut self) -> &mut T {
1065         &mut **self
1066     }
1067 }
1068
1069 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1070 impl<T: ?Sized> AsRef<T> for Box<T> {
1071     fn as_ref(&self) -> &T {
1072         &**self
1073     }
1074 }
1075
1076 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1077 impl<T: ?Sized> AsMut<T> for Box<T> {
1078     fn as_mut(&mut self) -> &mut T {
1079         &mut **self
1080     }
1081 }
1082
1083 /* Nota bene
1084  *
1085  *  We could have chosen not to add this impl, and instead have written a
1086  *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1087  *  because Box<T> implements Unpin even when T does not, as a result of
1088  *  this impl.
1089  *
1090  *  We chose this API instead of the alternative for a few reasons:
1091  *      - Logically, it is helpful to understand pinning in regard to the
1092  *        memory region being pointed to. For this reason none of the
1093  *        standard library pointer types support projecting through a pin
1094  *        (Box<T> is the only pointer type in std for which this would be
1095  *        safe.)
1096  *      - It is in practice very useful to have Box<T> be unconditionally
1097  *        Unpin because of trait objects, for which the structural auto
1098  *        trait functionality does not apply (e.g., Box<dyn Foo> would
1099  *        otherwise not be Unpin).
1100  *
1101  *  Another type with the same semantics as Box but only a conditional
1102  *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1103  *  could have a method to project a Pin<T> from it.
1104  */
1105 #[stable(feature = "pin", since = "1.33.0")]
1106 impl<T: ?Sized> Unpin for Box<T> {}
1107
1108 #[unstable(feature = "generator_trait", issue = "43122")]
1109 impl<G: ?Sized + Generator<R> + Unpin, R> Generator<R> for Box<G> {
1110     type Yield = G::Yield;
1111     type Return = G::Return;
1112
1113     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1114         G::resume(Pin::new(&mut *self), arg)
1115     }
1116 }
1117
1118 #[unstable(feature = "generator_trait", issue = "43122")]
1119 impl<G: ?Sized + Generator<R>, R> Generator<R> for Pin<Box<G>> {
1120     type Yield = G::Yield;
1121     type Return = G::Return;
1122
1123     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1124         G::resume((*self).as_mut(), arg)
1125     }
1126 }
1127
1128 #[stable(feature = "futures_api", since = "1.36.0")]
1129 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
1130     type Output = F::Output;
1131
1132     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1133         F::poll(Pin::new(&mut *self), cx)
1134     }
1135 }