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