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