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