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