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