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