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