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