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