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