]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/boxed.rs
Auto merge of #97575 - nnethercote:lazify-SourceFile-lines, r=Mark-Simulacrum
[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 //! For zero-sized values, the `Box` pointer still has to be [valid] for reads
66 //! and writes and sufficiently aligned. In particular, casting any aligned
67 //! non-zero integer literal to a raw pointer produces a valid pointer, but a
68 //! pointer pointing into previously allocated memory that since got freed is
69 //! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
70 //! be used is to use [`ptr::NonNull::dangling`].
71 //!
72 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
73 //! as a single pointer and is also ABI-compatible with C pointers
74 //! (i.e. the C type `T*`). This means that if you have extern "C"
75 //! Rust functions that will be called from C, you can define those
76 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
77 //! type on the C side. As an example, consider this C header which
78 //! declares functions that create and destroy some kind of `Foo`
79 //! value:
80 //!
81 //! ```c
82 //! /* C header */
83 //!
84 //! /* Returns ownership to the caller */
85 //! struct Foo* foo_new(void);
86 //!
87 //! /* Takes ownership from the caller; no-op when invoked with null */
88 //! void foo_delete(struct Foo*);
89 //! ```
90 //!
91 //! These two functions might be implemented in Rust as follows. Here, the
92 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
93 //! the ownership constraints. Note also that the nullable argument to
94 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
95 //! cannot be null.
96 //!
97 //! ```
98 //! #[repr(C)]
99 //! pub struct Foo;
100 //!
101 //! #[no_mangle]
102 //! pub extern "C" fn foo_new() -> Box<Foo> {
103 //!     Box::new(Foo)
104 //! }
105 //!
106 //! #[no_mangle]
107 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
108 //! ```
109 //!
110 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
111 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
112 //! and expect things to work. `Box<T>` values will always be fully aligned,
113 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
114 //! free the value with the global allocator. In general, the best practice
115 //! is to only use `Box<T>` for pointers that originated from the global
116 //! allocator.
117 //!
118 //! **Important.** At least at present, you should avoid using
119 //! `Box<T>` types for functions that are defined in C but invoked
120 //! from Rust. In those cases, you should directly mirror the C types
121 //! as closely as possible. Using types like `Box<T>` where the C
122 //! definition is just using `T*` can lead to undefined behavior, as
123 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
124 //!
125 //! # Considerations for unsafe code
126 //!
127 //! **Warning: This section is not normative and is subject to change, possibly
128 //! being relaxed in the future! It is a simplified summary of the rules
129 //! currently implemented in the compiler.**
130 //!
131 //! The aliasing rules for `Box<T>` are the same as for `&mut T`. `Box<T>`
132 //! asserts uniqueness over its content. Using raw pointers derived from a box
133 //! after that box has been mutated through, moved or borrowed as `&mut T`
134 //! is not allowed. For more guidance on working with box from unsafe code, see
135 //! [rust-lang/unsafe-code-guidelines#326][ucg#326].
136 //!
137 //!
138 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
139 //! [ucg#326]: https://github.com/rust-lang/unsafe-code-guidelines/issues/326
140 //! [dereferencing]: core::ops::Deref
141 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
142 //! [`Global`]: crate::alloc::Global
143 //! [`Layout`]: crate::alloc::Layout
144 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
145 //! [valid]: ptr#safety
146
147 #![stable(feature = "rust1", since = "1.0.0")]
148
149 use core::any::Any;
150 use core::async_iter::AsyncIterator;
151 use core::borrow;
152 use core::cmp::Ordering;
153 use core::convert::{From, TryFrom};
154 use core::fmt;
155 use core::future::Future;
156 use core::hash::{Hash, Hasher};
157 #[cfg(not(no_global_oom_handling))]
158 use core::iter::FromIterator;
159 use core::iter::{FusedIterator, Iterator};
160 use core::marker::{Destruct, Unpin, Unsize};
161 use core::mem;
162 use core::ops::{
163     CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
164 };
165 use core::pin::Pin;
166 use core::ptr::{self, Unique};
167 use core::task::{Context, Poll};
168
169 #[cfg(not(no_global_oom_handling))]
170 use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
171 use crate::alloc::{AllocError, Allocator, Global, Layout};
172 #[cfg(not(no_global_oom_handling))]
173 use crate::borrow::Cow;
174 use crate::raw_vec::RawVec;
175 #[cfg(not(no_global_oom_handling))]
176 use crate::str::from_boxed_utf8_unchecked;
177 #[cfg(not(no_global_oom_handling))]
178 use crate::vec::Vec;
179
180 #[unstable(feature = "thin_box", issue = "92791")]
181 pub use thin::ThinBox;
182
183 mod thin;
184
185 /// A pointer type for heap allocation.
186 ///
187 /// See the [module-level documentation](../../std/boxed/index.html) for more.
188 #[lang = "owned_box"]
189 #[fundamental]
190 #[stable(feature = "rust1", since = "1.0.0")]
191 // The declaration of the `Box` struct must be kept in sync with the
192 // `alloc::alloc::box_free` function or ICEs will happen. See the comment
193 // on `box_free` for more details.
194 pub struct Box<
195     T: ?Sized,
196     #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
197 >(Unique<T>, A);
198
199 impl<T> Box<T> {
200     /// Allocates memory on the heap and then places `x` into it.
201     ///
202     /// This doesn't actually allocate if `T` is zero-sized.
203     ///
204     /// # Examples
205     ///
206     /// ```
207     /// let five = Box::new(5);
208     /// ```
209     #[cfg(all(not(no_global_oom_handling), not(bootstrap)))]
210     #[inline(always)]
211     #[stable(feature = "rust1", since = "1.0.0")]
212     #[must_use]
213     pub fn new(x: T) -> Self {
214         #[rustc_box]
215         Box::new(x)
216     }
217
218     /// Allocates memory on the heap and then places `x` into it.
219     ///
220     /// This doesn't actually allocate if `T` is zero-sized.
221     ///
222     /// # Examples
223     ///
224     /// ```
225     /// let five = Box::new(5);
226     /// ```
227     #[cfg(all(not(no_global_oom_handling), bootstrap))]
228     #[inline(always)]
229     #[stable(feature = "rust1", since = "1.0.0")]
230     #[must_use]
231     pub fn new(x: T) -> Self {
232         box x
233     }
234
235     /// Constructs a new box with uninitialized contents.
236     ///
237     /// # Examples
238     ///
239     /// ```
240     /// #![feature(new_uninit)]
241     ///
242     /// let mut five = Box::<u32>::new_uninit();
243     ///
244     /// let five = unsafe {
245     ///     // Deferred initialization:
246     ///     five.as_mut_ptr().write(5);
247     ///
248     ///     five.assume_init()
249     /// };
250     ///
251     /// assert_eq!(*five, 5)
252     /// ```
253     #[cfg(not(no_global_oom_handling))]
254     #[unstable(feature = "new_uninit", issue = "63291")]
255     #[must_use]
256     #[inline]
257     pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
258         Self::new_uninit_in(Global)
259     }
260
261     /// Constructs a new `Box` with uninitialized contents, with the memory
262     /// being filled with `0` bytes.
263     ///
264     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
265     /// of this method.
266     ///
267     /// # Examples
268     ///
269     /// ```
270     /// #![feature(new_uninit)]
271     ///
272     /// let zero = Box::<u32>::new_zeroed();
273     /// let zero = unsafe { zero.assume_init() };
274     ///
275     /// assert_eq!(*zero, 0)
276     /// ```
277     ///
278     /// [zeroed]: mem::MaybeUninit::zeroed
279     #[cfg(not(no_global_oom_handling))]
280     #[inline]
281     #[unstable(feature = "new_uninit", issue = "63291")]
282     #[must_use]
283     pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
284         Self::new_zeroed_in(Global)
285     }
286
287     /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
288     /// `x` will be pinned in memory and unable to be moved.
289     #[cfg(not(no_global_oom_handling))]
290     #[stable(feature = "pin", since = "1.33.0")]
291     #[must_use]
292     #[inline(always)]
293     pub fn pin(x: T) -> Pin<Box<T>> {
294         (#[cfg_attr(not(bootstrap), rustc_box)]
295         Box::new(x))
296         .into()
297     }
298
299     /// Allocates memory on the heap then places `x` into it,
300     /// returning an error if the allocation fails
301     ///
302     /// This doesn't actually allocate if `T` is zero-sized.
303     ///
304     /// # Examples
305     ///
306     /// ```
307     /// #![feature(allocator_api)]
308     ///
309     /// let five = Box::try_new(5)?;
310     /// # Ok::<(), std::alloc::AllocError>(())
311     /// ```
312     #[unstable(feature = "allocator_api", issue = "32838")]
313     #[inline]
314     pub fn try_new(x: T) -> Result<Self, AllocError> {
315         Self::try_new_in(x, Global)
316     }
317
318     /// Constructs a new box with uninitialized contents on the heap,
319     /// returning an error if the allocation fails
320     ///
321     /// # Examples
322     ///
323     /// ```
324     /// #![feature(allocator_api, new_uninit)]
325     ///
326     /// let mut five = Box::<u32>::try_new_uninit()?;
327     ///
328     /// let five = unsafe {
329     ///     // Deferred initialization:
330     ///     five.as_mut_ptr().write(5);
331     ///
332     ///     five.assume_init()
333     /// };
334     ///
335     /// assert_eq!(*five, 5);
336     /// # Ok::<(), std::alloc::AllocError>(())
337     /// ```
338     #[unstable(feature = "allocator_api", issue = "32838")]
339     // #[unstable(feature = "new_uninit", issue = "63291")]
340     #[inline]
341     pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
342         Box::try_new_uninit_in(Global)
343     }
344
345     /// Constructs a new `Box` with uninitialized contents, with the memory
346     /// being filled with `0` bytes on the heap
347     ///
348     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
349     /// of this method.
350     ///
351     /// # Examples
352     ///
353     /// ```
354     /// #![feature(allocator_api, new_uninit)]
355     ///
356     /// let zero = Box::<u32>::try_new_zeroed()?;
357     /// let zero = unsafe { zero.assume_init() };
358     ///
359     /// assert_eq!(*zero, 0);
360     /// # Ok::<(), std::alloc::AllocError>(())
361     /// ```
362     ///
363     /// [zeroed]: mem::MaybeUninit::zeroed
364     #[unstable(feature = "allocator_api", issue = "32838")]
365     // #[unstable(feature = "new_uninit", issue = "63291")]
366     #[inline]
367     pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
368         Box::try_new_zeroed_in(Global)
369     }
370 }
371
372 impl<T, A: Allocator> Box<T, A> {
373     /// Allocates memory in the given allocator then places `x` into it.
374     ///
375     /// This doesn't actually allocate if `T` is zero-sized.
376     ///
377     /// # Examples
378     ///
379     /// ```
380     /// #![feature(allocator_api)]
381     ///
382     /// use std::alloc::System;
383     ///
384     /// let five = Box::new_in(5, System);
385     /// ```
386     #[cfg(not(no_global_oom_handling))]
387     #[unstable(feature = "allocator_api", issue = "32838")]
388     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
389     #[must_use]
390     #[inline]
391     pub const fn new_in(x: T, alloc: A) -> Self
392     where
393         A: ~const Allocator + ~const Destruct,
394     {
395         let mut boxed = Self::new_uninit_in(alloc);
396         unsafe {
397             boxed.as_mut_ptr().write(x);
398             boxed.assume_init()
399         }
400     }
401
402     /// Allocates memory in the given allocator then places `x` into it,
403     /// returning an error if the allocation fails
404     ///
405     /// This doesn't actually allocate if `T` is zero-sized.
406     ///
407     /// # Examples
408     ///
409     /// ```
410     /// #![feature(allocator_api)]
411     ///
412     /// use std::alloc::System;
413     ///
414     /// let five = Box::try_new_in(5, System)?;
415     /// # Ok::<(), std::alloc::AllocError>(())
416     /// ```
417     #[unstable(feature = "allocator_api", issue = "32838")]
418     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
419     #[inline]
420     pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
421     where
422         T: ~const Destruct,
423         A: ~const Allocator + ~const Destruct,
424     {
425         let mut boxed = Self::try_new_uninit_in(alloc)?;
426         unsafe {
427             boxed.as_mut_ptr().write(x);
428             Ok(boxed.assume_init())
429         }
430     }
431
432     /// Constructs a new box with uninitialized contents in the provided allocator.
433     ///
434     /// # Examples
435     ///
436     /// ```
437     /// #![feature(allocator_api, new_uninit)]
438     ///
439     /// use std::alloc::System;
440     ///
441     /// let mut five = Box::<u32, _>::new_uninit_in(System);
442     ///
443     /// let five = unsafe {
444     ///     // Deferred initialization:
445     ///     five.as_mut_ptr().write(5);
446     ///
447     ///     five.assume_init()
448     /// };
449     ///
450     /// assert_eq!(*five, 5)
451     /// ```
452     #[unstable(feature = "allocator_api", issue = "32838")]
453     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
454     #[cfg(not(no_global_oom_handling))]
455     #[must_use]
456     // #[unstable(feature = "new_uninit", issue = "63291")]
457     pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
458     where
459         A: ~const Allocator + ~const Destruct,
460     {
461         let layout = Layout::new::<mem::MaybeUninit<T>>();
462         // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
463         // That would make code size bigger.
464         match Box::try_new_uninit_in(alloc) {
465             Ok(m) => m,
466             Err(_) => handle_alloc_error(layout),
467         }
468     }
469
470     /// Constructs a new box with uninitialized contents in the provided allocator,
471     /// returning an error if the allocation fails
472     ///
473     /// # Examples
474     ///
475     /// ```
476     /// #![feature(allocator_api, new_uninit)]
477     ///
478     /// use std::alloc::System;
479     ///
480     /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
481     ///
482     /// let five = unsafe {
483     ///     // Deferred initialization:
484     ///     five.as_mut_ptr().write(5);
485     ///
486     ///     five.assume_init()
487     /// };
488     ///
489     /// assert_eq!(*five, 5);
490     /// # Ok::<(), std::alloc::AllocError>(())
491     /// ```
492     #[unstable(feature = "allocator_api", issue = "32838")]
493     // #[unstable(feature = "new_uninit", issue = "63291")]
494     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
495     pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
496     where
497         A: ~const Allocator + ~const Destruct,
498     {
499         let layout = Layout::new::<mem::MaybeUninit<T>>();
500         let ptr = alloc.allocate(layout)?.cast();
501         unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
502     }
503
504     /// Constructs a new `Box` with uninitialized contents, with the memory
505     /// being filled with `0` bytes in the provided allocator.
506     ///
507     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
508     /// of this method.
509     ///
510     /// # Examples
511     ///
512     /// ```
513     /// #![feature(allocator_api, new_uninit)]
514     ///
515     /// use std::alloc::System;
516     ///
517     /// let zero = Box::<u32, _>::new_zeroed_in(System);
518     /// let zero = unsafe { zero.assume_init() };
519     ///
520     /// assert_eq!(*zero, 0)
521     /// ```
522     ///
523     /// [zeroed]: mem::MaybeUninit::zeroed
524     #[unstable(feature = "allocator_api", issue = "32838")]
525     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
526     #[cfg(not(no_global_oom_handling))]
527     // #[unstable(feature = "new_uninit", issue = "63291")]
528     #[must_use]
529     pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
530     where
531         A: ~const Allocator + ~const Destruct,
532     {
533         let layout = Layout::new::<mem::MaybeUninit<T>>();
534         // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
535         // That would make code size bigger.
536         match Box::try_new_zeroed_in(alloc) {
537             Ok(m) => m,
538             Err(_) => handle_alloc_error(layout),
539         }
540     }
541
542     /// Constructs a new `Box` with uninitialized contents, with the memory
543     /// being filled with `0` bytes in the provided allocator,
544     /// returning an error if the allocation fails,
545     ///
546     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
547     /// of this method.
548     ///
549     /// # Examples
550     ///
551     /// ```
552     /// #![feature(allocator_api, new_uninit)]
553     ///
554     /// use std::alloc::System;
555     ///
556     /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
557     /// let zero = unsafe { zero.assume_init() };
558     ///
559     /// assert_eq!(*zero, 0);
560     /// # Ok::<(), std::alloc::AllocError>(())
561     /// ```
562     ///
563     /// [zeroed]: mem::MaybeUninit::zeroed
564     #[unstable(feature = "allocator_api", issue = "32838")]
565     // #[unstable(feature = "new_uninit", issue = "63291")]
566     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
567     pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
568     where
569         A: ~const Allocator + ~const Destruct,
570     {
571         let layout = Layout::new::<mem::MaybeUninit<T>>();
572         let ptr = alloc.allocate_zeroed(layout)?.cast();
573         unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
574     }
575
576     /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
577     /// `x` will be pinned in memory and unable to be moved.
578     #[cfg(not(no_global_oom_handling))]
579     #[unstable(feature = "allocator_api", issue = "32838")]
580     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
581     #[must_use]
582     #[inline(always)]
583     pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
584     where
585         A: 'static + ~const Allocator + ~const Destruct,
586     {
587         Self::into_pin(Self::new_in(x, alloc))
588     }
589
590     /// Converts a `Box<T>` into a `Box<[T]>`
591     ///
592     /// This conversion does not allocate on the heap and happens in place.
593     #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
594     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
595     pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
596         let (raw, alloc) = Box::into_raw_with_allocator(boxed);
597         unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
598     }
599
600     /// Consumes the `Box`, returning the wrapped value.
601     ///
602     /// # Examples
603     ///
604     /// ```
605     /// #![feature(box_into_inner)]
606     ///
607     /// let c = Box::new(5);
608     ///
609     /// assert_eq!(Box::into_inner(c), 5);
610     /// ```
611     #[unstable(feature = "box_into_inner", issue = "80437")]
612     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
613     #[inline]
614     pub const fn into_inner(boxed: Self) -> T
615     where
616         Self: ~const Destruct,
617     {
618         *boxed
619     }
620 }
621
622 impl<T> Box<[T]> {
623     /// Constructs a new boxed slice with uninitialized contents.
624     ///
625     /// # Examples
626     ///
627     /// ```
628     /// #![feature(new_uninit)]
629     ///
630     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
631     ///
632     /// let values = unsafe {
633     ///     // Deferred initialization:
634     ///     values[0].as_mut_ptr().write(1);
635     ///     values[1].as_mut_ptr().write(2);
636     ///     values[2].as_mut_ptr().write(3);
637     ///
638     ///     values.assume_init()
639     /// };
640     ///
641     /// assert_eq!(*values, [1, 2, 3])
642     /// ```
643     #[cfg(not(no_global_oom_handling))]
644     #[unstable(feature = "new_uninit", issue = "63291")]
645     #[must_use]
646     pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
647         unsafe { RawVec::with_capacity(len).into_box(len) }
648     }
649
650     /// Constructs a new boxed slice with uninitialized contents, with the memory
651     /// being filled with `0` bytes.
652     ///
653     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
654     /// of this method.
655     ///
656     /// # Examples
657     ///
658     /// ```
659     /// #![feature(new_uninit)]
660     ///
661     /// let values = Box::<[u32]>::new_zeroed_slice(3);
662     /// let values = unsafe { values.assume_init() };
663     ///
664     /// assert_eq!(*values, [0, 0, 0])
665     /// ```
666     ///
667     /// [zeroed]: mem::MaybeUninit::zeroed
668     #[cfg(not(no_global_oom_handling))]
669     #[unstable(feature = "new_uninit", issue = "63291")]
670     #[must_use]
671     pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
672         unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
673     }
674
675     /// Constructs a new boxed slice with uninitialized contents. Returns an error if
676     /// the allocation fails
677     ///
678     /// # Examples
679     ///
680     /// ```
681     /// #![feature(allocator_api, new_uninit)]
682     ///
683     /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
684     /// let values = unsafe {
685     ///     // Deferred initialization:
686     ///     values[0].as_mut_ptr().write(1);
687     ///     values[1].as_mut_ptr().write(2);
688     ///     values[2].as_mut_ptr().write(3);
689     ///     values.assume_init()
690     /// };
691     ///
692     /// assert_eq!(*values, [1, 2, 3]);
693     /// # Ok::<(), std::alloc::AllocError>(())
694     /// ```
695     #[unstable(feature = "allocator_api", issue = "32838")]
696     #[inline]
697     pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
698         unsafe {
699             let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
700                 Ok(l) => l,
701                 Err(_) => return Err(AllocError),
702             };
703             let ptr = Global.allocate(layout)?;
704             Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
705         }
706     }
707
708     /// Constructs a new boxed slice with uninitialized contents, with the memory
709     /// being filled with `0` bytes. Returns an error if the allocation fails
710     ///
711     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
712     /// of this method.
713     ///
714     /// # Examples
715     ///
716     /// ```
717     /// #![feature(allocator_api, new_uninit)]
718     ///
719     /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
720     /// let values = unsafe { values.assume_init() };
721     ///
722     /// assert_eq!(*values, [0, 0, 0]);
723     /// # Ok::<(), std::alloc::AllocError>(())
724     /// ```
725     ///
726     /// [zeroed]: mem::MaybeUninit::zeroed
727     #[unstable(feature = "allocator_api", issue = "32838")]
728     #[inline]
729     pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
730         unsafe {
731             let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
732                 Ok(l) => l,
733                 Err(_) => return Err(AllocError),
734             };
735             let ptr = Global.allocate_zeroed(layout)?;
736             Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
737         }
738     }
739 }
740
741 impl<T, A: Allocator> Box<[T], A> {
742     /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
743     ///
744     /// # Examples
745     ///
746     /// ```
747     /// #![feature(allocator_api, new_uninit)]
748     ///
749     /// use std::alloc::System;
750     ///
751     /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
752     ///
753     /// let values = unsafe {
754     ///     // Deferred initialization:
755     ///     values[0].as_mut_ptr().write(1);
756     ///     values[1].as_mut_ptr().write(2);
757     ///     values[2].as_mut_ptr().write(3);
758     ///
759     ///     values.assume_init()
760     /// };
761     ///
762     /// assert_eq!(*values, [1, 2, 3])
763     /// ```
764     #[cfg(not(no_global_oom_handling))]
765     #[unstable(feature = "allocator_api", issue = "32838")]
766     // #[unstable(feature = "new_uninit", issue = "63291")]
767     #[must_use]
768     pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
769         unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
770     }
771
772     /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
773     /// with the memory being filled with `0` bytes.
774     ///
775     /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
776     /// of this method.
777     ///
778     /// # Examples
779     ///
780     /// ```
781     /// #![feature(allocator_api, new_uninit)]
782     ///
783     /// use std::alloc::System;
784     ///
785     /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
786     /// let values = unsafe { values.assume_init() };
787     ///
788     /// assert_eq!(*values, [0, 0, 0])
789     /// ```
790     ///
791     /// [zeroed]: mem::MaybeUninit::zeroed
792     #[cfg(not(no_global_oom_handling))]
793     #[unstable(feature = "allocator_api", issue = "32838")]
794     // #[unstable(feature = "new_uninit", issue = "63291")]
795     #[must_use]
796     pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
797         unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
798     }
799 }
800
801 impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
802     /// Converts to `Box<T, A>`.
803     ///
804     /// # Safety
805     ///
806     /// As with [`MaybeUninit::assume_init`],
807     /// it is up to the caller to guarantee that the value
808     /// really is in an initialized state.
809     /// Calling this when the content is not yet fully initialized
810     /// causes immediate undefined behavior.
811     ///
812     /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
813     ///
814     /// # Examples
815     ///
816     /// ```
817     /// #![feature(new_uninit)]
818     ///
819     /// let mut five = Box::<u32>::new_uninit();
820     ///
821     /// let five: Box<u32> = unsafe {
822     ///     // Deferred initialization:
823     ///     five.as_mut_ptr().write(5);
824     ///
825     ///     five.assume_init()
826     /// };
827     ///
828     /// assert_eq!(*five, 5)
829     /// ```
830     #[unstable(feature = "new_uninit", issue = "63291")]
831     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
832     #[inline]
833     pub const unsafe fn assume_init(self) -> Box<T, A> {
834         let (raw, alloc) = Box::into_raw_with_allocator(self);
835         unsafe { Box::from_raw_in(raw as *mut T, alloc) }
836     }
837
838     /// Writes the value and converts to `Box<T, A>`.
839     ///
840     /// This method converts the box similarly to [`Box::assume_init`] but
841     /// writes `value` into it before conversion thus guaranteeing safety.
842     /// In some scenarios use of this method may improve performance because
843     /// the compiler may be able to optimize copying from stack.
844     ///
845     /// # Examples
846     ///
847     /// ```
848     /// #![feature(new_uninit)]
849     ///
850     /// let big_box = Box::<[usize; 1024]>::new_uninit();
851     ///
852     /// let mut array = [0; 1024];
853     /// for (i, place) in array.iter_mut().enumerate() {
854     ///     *place = i;
855     /// }
856     ///
857     /// // The optimizer may be able to elide this copy, so previous code writes
858     /// // to heap directly.
859     /// let big_box = Box::write(big_box, array);
860     ///
861     /// for (i, x) in big_box.iter().enumerate() {
862     ///     assert_eq!(*x, i);
863     /// }
864     /// ```
865     #[unstable(feature = "new_uninit", issue = "63291")]
866     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
867     #[inline]
868     pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
869         unsafe {
870             (*boxed).write(value);
871             boxed.assume_init()
872         }
873     }
874 }
875
876 impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
877     /// Converts to `Box<[T], A>`.
878     ///
879     /// # Safety
880     ///
881     /// As with [`MaybeUninit::assume_init`],
882     /// it is up to the caller to guarantee that the values
883     /// really are in an initialized state.
884     /// Calling this when the content is not yet fully initialized
885     /// causes immediate undefined behavior.
886     ///
887     /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
888     ///
889     /// # Examples
890     ///
891     /// ```
892     /// #![feature(new_uninit)]
893     ///
894     /// let mut values = Box::<[u32]>::new_uninit_slice(3);
895     ///
896     /// let values = unsafe {
897     ///     // Deferred initialization:
898     ///     values[0].as_mut_ptr().write(1);
899     ///     values[1].as_mut_ptr().write(2);
900     ///     values[2].as_mut_ptr().write(3);
901     ///
902     ///     values.assume_init()
903     /// };
904     ///
905     /// assert_eq!(*values, [1, 2, 3])
906     /// ```
907     #[unstable(feature = "new_uninit", issue = "63291")]
908     #[inline]
909     pub unsafe fn assume_init(self) -> Box<[T], A> {
910         let (raw, alloc) = Box::into_raw_with_allocator(self);
911         unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
912     }
913 }
914
915 impl<T: ?Sized> Box<T> {
916     /// Constructs a box from a raw pointer.
917     ///
918     /// After calling this function, the raw pointer is owned by the
919     /// resulting `Box`. Specifically, the `Box` destructor will call
920     /// the destructor of `T` and free the allocated memory. For this
921     /// to be safe, the memory must have been allocated in accordance
922     /// with the [memory layout] used by `Box` .
923     ///
924     /// # Safety
925     ///
926     /// This function is unsafe because improper use may lead to
927     /// memory problems. For example, a double-free may occur if the
928     /// function is called twice on the same raw pointer.
929     ///
930     /// The safety conditions are described in the [memory layout] section.
931     ///
932     /// # Examples
933     ///
934     /// Recreate a `Box` which was previously converted to a raw pointer
935     /// using [`Box::into_raw`]:
936     /// ```
937     /// let x = Box::new(5);
938     /// let ptr = Box::into_raw(x);
939     /// let x = unsafe { Box::from_raw(ptr) };
940     /// ```
941     /// Manually create a `Box` from scratch by using the global allocator:
942     /// ```
943     /// use std::alloc::{alloc, Layout};
944     ///
945     /// unsafe {
946     ///     let ptr = alloc(Layout::new::<i32>()) as *mut i32;
947     ///     // In general .write is required to avoid attempting to destruct
948     ///     // the (uninitialized) previous contents of `ptr`, though for this
949     ///     // simple example `*ptr = 5` would have worked as well.
950     ///     ptr.write(5);
951     ///     let x = Box::from_raw(ptr);
952     /// }
953     /// ```
954     ///
955     /// [memory layout]: self#memory-layout
956     /// [`Layout`]: crate::Layout
957     #[stable(feature = "box_raw", since = "1.4.0")]
958     #[inline]
959     pub unsafe fn from_raw(raw: *mut T) -> Self {
960         unsafe { Self::from_raw_in(raw, Global) }
961     }
962 }
963
964 impl<T: ?Sized, A: Allocator> Box<T, A> {
965     /// Constructs a box from a raw pointer in the given allocator.
966     ///
967     /// After calling this function, the raw pointer is owned by the
968     /// resulting `Box`. Specifically, the `Box` destructor will call
969     /// the destructor of `T` and free the allocated memory. For this
970     /// to be safe, the memory must have been allocated in accordance
971     /// with the [memory layout] used by `Box` .
972     ///
973     /// # Safety
974     ///
975     /// This function is unsafe because improper use may lead to
976     /// memory problems. For example, a double-free may occur if the
977     /// function is called twice on the same raw pointer.
978     ///
979     ///
980     /// # Examples
981     ///
982     /// Recreate a `Box` which was previously converted to a raw pointer
983     /// using [`Box::into_raw_with_allocator`]:
984     /// ```
985     /// #![feature(allocator_api)]
986     ///
987     /// use std::alloc::System;
988     ///
989     /// let x = Box::new_in(5, System);
990     /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
991     /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
992     /// ```
993     /// Manually create a `Box` from scratch by using the system allocator:
994     /// ```
995     /// #![feature(allocator_api, slice_ptr_get)]
996     ///
997     /// use std::alloc::{Allocator, Layout, System};
998     ///
999     /// unsafe {
1000     ///     let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1001     ///     // In general .write is required to avoid attempting to destruct
1002     ///     // the (uninitialized) previous contents of `ptr`, though for this
1003     ///     // simple example `*ptr = 5` would have worked as well.
1004     ///     ptr.write(5);
1005     ///     let x = Box::from_raw_in(ptr, System);
1006     /// }
1007     /// # Ok::<(), std::alloc::AllocError>(())
1008     /// ```
1009     ///
1010     /// [memory layout]: self#memory-layout
1011     /// [`Layout`]: crate::Layout
1012     #[unstable(feature = "allocator_api", issue = "32838")]
1013     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1014     #[inline]
1015     pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1016         Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1017     }
1018
1019     /// Consumes the `Box`, returning a wrapped raw pointer.
1020     ///
1021     /// The pointer will be properly aligned and non-null.
1022     ///
1023     /// After calling this function, the caller is responsible for the
1024     /// memory previously managed by the `Box`. In particular, the
1025     /// caller should properly destroy `T` and release the memory, taking
1026     /// into account the [memory layout] used by `Box`. The easiest way to
1027     /// do this is to convert the raw pointer back into a `Box` with the
1028     /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1029     /// the cleanup.
1030     ///
1031     /// Note: this is an associated function, which means that you have
1032     /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1033     /// is so that there is no conflict with a method on the inner type.
1034     ///
1035     /// # Examples
1036     /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1037     /// for automatic cleanup:
1038     /// ```
1039     /// let x = Box::new(String::from("Hello"));
1040     /// let ptr = Box::into_raw(x);
1041     /// let x = unsafe { Box::from_raw(ptr) };
1042     /// ```
1043     /// Manual cleanup by explicitly running the destructor and deallocating
1044     /// the memory:
1045     /// ```
1046     /// use std::alloc::{dealloc, Layout};
1047     /// use std::ptr;
1048     ///
1049     /// let x = Box::new(String::from("Hello"));
1050     /// let p = Box::into_raw(x);
1051     /// unsafe {
1052     ///     ptr::drop_in_place(p);
1053     ///     dealloc(p as *mut u8, Layout::new::<String>());
1054     /// }
1055     /// ```
1056     ///
1057     /// [memory layout]: self#memory-layout
1058     #[stable(feature = "box_raw", since = "1.4.0")]
1059     #[inline]
1060     pub fn into_raw(b: Self) -> *mut T {
1061         Self::into_raw_with_allocator(b).0
1062     }
1063
1064     /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1065     ///
1066     /// The pointer will be properly aligned and non-null.
1067     ///
1068     /// After calling this function, the caller is responsible for the
1069     /// memory previously managed by the `Box`. In particular, the
1070     /// caller should properly destroy `T` and release the memory, taking
1071     /// into account the [memory layout] used by `Box`. The easiest way to
1072     /// do this is to convert the raw pointer back into a `Box` with the
1073     /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1074     /// the cleanup.
1075     ///
1076     /// Note: this is an associated function, which means that you have
1077     /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1078     /// is so that there is no conflict with a method on the inner type.
1079     ///
1080     /// # Examples
1081     /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1082     /// for automatic cleanup:
1083     /// ```
1084     /// #![feature(allocator_api)]
1085     ///
1086     /// use std::alloc::System;
1087     ///
1088     /// let x = Box::new_in(String::from("Hello"), System);
1089     /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1090     /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1091     /// ```
1092     /// Manual cleanup by explicitly running the destructor and deallocating
1093     /// the memory:
1094     /// ```
1095     /// #![feature(allocator_api)]
1096     ///
1097     /// use std::alloc::{Allocator, Layout, System};
1098     /// use std::ptr::{self, NonNull};
1099     ///
1100     /// let x = Box::new_in(String::from("Hello"), System);
1101     /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1102     /// unsafe {
1103     ///     ptr::drop_in_place(ptr);
1104     ///     let non_null = NonNull::new_unchecked(ptr);
1105     ///     alloc.deallocate(non_null.cast(), Layout::new::<String>());
1106     /// }
1107     /// ```
1108     ///
1109     /// [memory layout]: self#memory-layout
1110     #[unstable(feature = "allocator_api", issue = "32838")]
1111     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1112     #[inline]
1113     pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1114         let (leaked, alloc) = Box::into_unique(b);
1115         (leaked.as_ptr(), alloc)
1116     }
1117
1118     #[unstable(
1119         feature = "ptr_internals",
1120         issue = "none",
1121         reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1122     )]
1123     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1124     #[inline]
1125     #[doc(hidden)]
1126     pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1127         // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1128         // raw pointer for the type system. Turning it directly into a raw pointer would not be
1129         // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1130         // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1131         // behaves correctly.
1132         let alloc = unsafe { ptr::read(&b.1) };
1133         (Unique::from(Box::leak(b)), alloc)
1134     }
1135
1136     /// Returns a reference to the underlying allocator.
1137     ///
1138     /// Note: this is an associated function, which means that you have
1139     /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1140     /// is so that there is no conflict with a method on the inner type.
1141     #[unstable(feature = "allocator_api", issue = "32838")]
1142     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1143     #[inline]
1144     pub const fn allocator(b: &Self) -> &A {
1145         &b.1
1146     }
1147
1148     /// Consumes and leaks the `Box`, returning a mutable reference,
1149     /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1150     /// `'a`. If the type has only static references, or none at all, then this
1151     /// may be chosen to be `'static`.
1152     ///
1153     /// This function is mainly useful for data that lives for the remainder of
1154     /// the program's life. Dropping the returned reference will cause a memory
1155     /// leak. If this is not acceptable, the reference should first be wrapped
1156     /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1157     /// then be dropped which will properly destroy `T` and release the
1158     /// allocated memory.
1159     ///
1160     /// Note: this is an associated function, which means that you have
1161     /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1162     /// is so that there is no conflict with a method on the inner type.
1163     ///
1164     /// # Examples
1165     ///
1166     /// Simple usage:
1167     ///
1168     /// ```
1169     /// let x = Box::new(41);
1170     /// let static_ref: &'static mut usize = Box::leak(x);
1171     /// *static_ref += 1;
1172     /// assert_eq!(*static_ref, 42);
1173     /// ```
1174     ///
1175     /// Unsized data:
1176     ///
1177     /// ```
1178     /// let x = vec![1, 2, 3].into_boxed_slice();
1179     /// let static_ref = Box::leak(x);
1180     /// static_ref[0] = 4;
1181     /// assert_eq!(*static_ref, [4, 2, 3]);
1182     /// ```
1183     #[stable(feature = "box_leak", since = "1.26.0")]
1184     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1185     #[inline]
1186     pub const fn leak<'a>(b: Self) -> &'a mut T
1187     where
1188         A: 'a,
1189     {
1190         unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1191     }
1192
1193     /// Converts a `Box<T>` into a `Pin<Box<T>>`
1194     ///
1195     /// This conversion does not allocate on the heap and happens in place.
1196     ///
1197     /// This is also available via [`From`].
1198     ///
1199     /// # Notes
1200     ///
1201     /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1202     /// as it'll introduce an ambiguity when calling `Pin::from`.
1203     /// A demonstration of such a poor impl is shown below.
1204     ///
1205     /// ```compile_fail
1206     /// # use std::pin::Pin;
1207     /// struct Foo; // A type defined in this crate.
1208     /// impl From<Box<()>> for Pin<Foo> {
1209     ///     fn from(_: Box<()>) -> Pin<Foo> {
1210     ///         Pin::new(Foo)
1211     ///     }
1212     /// }
1213     ///
1214     /// let foo = Box::new(());
1215     /// let bar = Pin::from(foo);
1216     /// ```
1217     #[stable(feature = "box_into_pin", since = "1.63.0")]
1218     #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1219     pub const fn into_pin(boxed: Self) -> Pin<Self>
1220     where
1221         A: 'static,
1222     {
1223         // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1224         // when `T: !Unpin`, so it's safe to pin it directly without any
1225         // additional requirements.
1226         unsafe { Pin::new_unchecked(boxed) }
1227     }
1228 }
1229
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1232     fn drop(&mut self) {
1233         // FIXME: Do nothing, drop is currently performed by compiler.
1234     }
1235 }
1236
1237 #[cfg(not(no_global_oom_handling))]
1238 #[stable(feature = "rust1", since = "1.0.0")]
1239 impl<T: Default> Default for Box<T> {
1240     /// Creates a `Box<T>`, with the `Default` value for T.
1241     fn default() -> Self {
1242         #[cfg_attr(not(bootstrap), rustc_box)]
1243         Box::new(T::default())
1244     }
1245 }
1246
1247 #[cfg(not(no_global_oom_handling))]
1248 #[stable(feature = "rust1", since = "1.0.0")]
1249 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1250 impl<T> const Default for Box<[T]> {
1251     fn default() -> Self {
1252         let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1253         Box(ptr, Global)
1254     }
1255 }
1256
1257 #[cfg(not(no_global_oom_handling))]
1258 #[stable(feature = "default_box_extra", since = "1.17.0")]
1259 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1260 impl const Default for Box<str> {
1261     fn default() -> Self {
1262         // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1263         let ptr: Unique<str> = unsafe {
1264             let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1265             Unique::new_unchecked(bytes.as_ptr() as *mut str)
1266         };
1267         Box(ptr, Global)
1268     }
1269 }
1270
1271 #[cfg(not(no_global_oom_handling))]
1272 #[stable(feature = "rust1", since = "1.0.0")]
1273 impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1274     /// Returns a new box with a `clone()` of this box's contents.
1275     ///
1276     /// # Examples
1277     ///
1278     /// ```
1279     /// let x = Box::new(5);
1280     /// let y = x.clone();
1281     ///
1282     /// // The value is the same
1283     /// assert_eq!(x, y);
1284     ///
1285     /// // But they are unique objects
1286     /// assert_ne!(&*x as *const i32, &*y as *const i32);
1287     /// ```
1288     #[inline]
1289     fn clone(&self) -> Self {
1290         // Pre-allocate memory to allow writing the cloned value directly.
1291         let mut boxed = Self::new_uninit_in(self.1.clone());
1292         unsafe {
1293             (**self).write_clone_into_raw(boxed.as_mut_ptr());
1294             boxed.assume_init()
1295         }
1296     }
1297
1298     /// Copies `source`'s contents into `self` without creating a new allocation.
1299     ///
1300     /// # Examples
1301     ///
1302     /// ```
1303     /// let x = Box::new(5);
1304     /// let mut y = Box::new(10);
1305     /// let yp: *const i32 = &*y;
1306     ///
1307     /// y.clone_from(&x);
1308     ///
1309     /// // The value is the same
1310     /// assert_eq!(x, y);
1311     ///
1312     /// // And no allocation occurred
1313     /// assert_eq!(yp, &*y);
1314     /// ```
1315     #[inline]
1316     fn clone_from(&mut self, source: &Self) {
1317         (**self).clone_from(&(**source));
1318     }
1319 }
1320
1321 #[cfg(not(no_global_oom_handling))]
1322 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1323 impl Clone for Box<str> {
1324     fn clone(&self) -> Self {
1325         // this makes a copy of the data
1326         let buf: Box<[u8]> = self.as_bytes().into();
1327         unsafe { from_boxed_utf8_unchecked(buf) }
1328     }
1329 }
1330
1331 #[stable(feature = "rust1", since = "1.0.0")]
1332 impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1333     #[inline]
1334     fn eq(&self, other: &Self) -> bool {
1335         PartialEq::eq(&**self, &**other)
1336     }
1337     #[inline]
1338     fn ne(&self, other: &Self) -> bool {
1339         PartialEq::ne(&**self, &**other)
1340     }
1341 }
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1344     #[inline]
1345     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1346         PartialOrd::partial_cmp(&**self, &**other)
1347     }
1348     #[inline]
1349     fn lt(&self, other: &Self) -> bool {
1350         PartialOrd::lt(&**self, &**other)
1351     }
1352     #[inline]
1353     fn le(&self, other: &Self) -> bool {
1354         PartialOrd::le(&**self, &**other)
1355     }
1356     #[inline]
1357     fn ge(&self, other: &Self) -> bool {
1358         PartialOrd::ge(&**self, &**other)
1359     }
1360     #[inline]
1361     fn gt(&self, other: &Self) -> bool {
1362         PartialOrd::gt(&**self, &**other)
1363     }
1364 }
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1367     #[inline]
1368     fn cmp(&self, other: &Self) -> Ordering {
1369         Ord::cmp(&**self, &**other)
1370     }
1371 }
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1374
1375 #[stable(feature = "rust1", since = "1.0.0")]
1376 impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1377     fn hash<H: Hasher>(&self, state: &mut H) {
1378         (**self).hash(state);
1379     }
1380 }
1381
1382 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1383 impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1384     fn finish(&self) -> u64 {
1385         (**self).finish()
1386     }
1387     fn write(&mut self, bytes: &[u8]) {
1388         (**self).write(bytes)
1389     }
1390     fn write_u8(&mut self, i: u8) {
1391         (**self).write_u8(i)
1392     }
1393     fn write_u16(&mut self, i: u16) {
1394         (**self).write_u16(i)
1395     }
1396     fn write_u32(&mut self, i: u32) {
1397         (**self).write_u32(i)
1398     }
1399     fn write_u64(&mut self, i: u64) {
1400         (**self).write_u64(i)
1401     }
1402     fn write_u128(&mut self, i: u128) {
1403         (**self).write_u128(i)
1404     }
1405     fn write_usize(&mut self, i: usize) {
1406         (**self).write_usize(i)
1407     }
1408     fn write_i8(&mut self, i: i8) {
1409         (**self).write_i8(i)
1410     }
1411     fn write_i16(&mut self, i: i16) {
1412         (**self).write_i16(i)
1413     }
1414     fn write_i32(&mut self, i: i32) {
1415         (**self).write_i32(i)
1416     }
1417     fn write_i64(&mut self, i: i64) {
1418         (**self).write_i64(i)
1419     }
1420     fn write_i128(&mut self, i: i128) {
1421         (**self).write_i128(i)
1422     }
1423     fn write_isize(&mut self, i: isize) {
1424         (**self).write_isize(i)
1425     }
1426     fn write_length_prefix(&mut self, len: usize) {
1427         (**self).write_length_prefix(len)
1428     }
1429     fn write_str(&mut self, s: &str) {
1430         (**self).write_str(s)
1431     }
1432 }
1433
1434 #[cfg(not(no_global_oom_handling))]
1435 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
1436 impl<T> From<T> for Box<T> {
1437     /// Converts a `T` into a `Box<T>`
1438     ///
1439     /// The conversion allocates on the heap and moves `t`
1440     /// from the stack into it.
1441     ///
1442     /// # Examples
1443     ///
1444     /// ```rust
1445     /// let x = 5;
1446     /// let boxed = Box::new(5);
1447     ///
1448     /// assert_eq!(Box::from(x), boxed);
1449     /// ```
1450     fn from(t: T) -> Self {
1451         Box::new(t)
1452     }
1453 }
1454
1455 #[stable(feature = "pin", since = "1.33.0")]
1456 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1457 impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1458 where
1459     A: 'static,
1460 {
1461     /// Converts a `Box<T>` into a `Pin<Box<T>>`
1462     ///
1463     /// This conversion does not allocate on the heap and happens in place.
1464     fn from(boxed: Box<T, A>) -> Self {
1465         Box::into_pin(boxed)
1466     }
1467 }
1468
1469 #[cfg(not(no_global_oom_handling))]
1470 #[stable(feature = "box_from_slice", since = "1.17.0")]
1471 impl<T: Copy> From<&[T]> for Box<[T]> {
1472     /// Converts a `&[T]` into a `Box<[T]>`
1473     ///
1474     /// This conversion allocates on the heap
1475     /// and performs a copy of `slice`.
1476     ///
1477     /// # Examples
1478     /// ```rust
1479     /// // create a &[u8] which will be used to create a Box<[u8]>
1480     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1481     /// let boxed_slice: Box<[u8]> = Box::from(slice);
1482     ///
1483     /// println!("{boxed_slice:?}");
1484     /// ```
1485     fn from(slice: &[T]) -> Box<[T]> {
1486         let len = slice.len();
1487         let buf = RawVec::with_capacity(len);
1488         unsafe {
1489             ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1490             buf.into_box(slice.len()).assume_init()
1491         }
1492     }
1493 }
1494
1495 #[cfg(not(no_global_oom_handling))]
1496 #[stable(feature = "box_from_cow", since = "1.45.0")]
1497 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1498     /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1499     ///
1500     /// When `cow` is the `Cow::Borrowed` variant, this
1501     /// conversion allocates on the heap and copies the
1502     /// underlying slice. Otherwise, it will try to reuse the owned
1503     /// `Vec`'s allocation.
1504     #[inline]
1505     fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1506         match cow {
1507             Cow::Borrowed(slice) => Box::from(slice),
1508             Cow::Owned(slice) => Box::from(slice),
1509         }
1510     }
1511 }
1512
1513 #[cfg(not(no_global_oom_handling))]
1514 #[stable(feature = "box_from_slice", since = "1.17.0")]
1515 impl From<&str> for Box<str> {
1516     /// Converts a `&str` into a `Box<str>`
1517     ///
1518     /// This conversion allocates on the heap
1519     /// and performs a copy of `s`.
1520     ///
1521     /// # Examples
1522     ///
1523     /// ```rust
1524     /// let boxed: Box<str> = Box::from("hello");
1525     /// println!("{boxed}");
1526     /// ```
1527     #[inline]
1528     fn from(s: &str) -> Box<str> {
1529         unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1530     }
1531 }
1532
1533 #[cfg(not(no_global_oom_handling))]
1534 #[stable(feature = "box_from_cow", since = "1.45.0")]
1535 impl From<Cow<'_, str>> for Box<str> {
1536     /// Converts a `Cow<'_, str>` into a `Box<str>`
1537     ///
1538     /// When `cow` is the `Cow::Borrowed` variant, this
1539     /// conversion allocates on the heap and copies the
1540     /// underlying `str`. Otherwise, it will try to reuse the owned
1541     /// `String`'s allocation.
1542     ///
1543     /// # Examples
1544     ///
1545     /// ```rust
1546     /// use std::borrow::Cow;
1547     ///
1548     /// let unboxed = Cow::Borrowed("hello");
1549     /// let boxed: Box<str> = Box::from(unboxed);
1550     /// println!("{boxed}");
1551     /// ```
1552     ///
1553     /// ```rust
1554     /// # use std::borrow::Cow;
1555     /// let unboxed = Cow::Owned("hello".to_string());
1556     /// let boxed: Box<str> = Box::from(unboxed);
1557     /// println!("{boxed}");
1558     /// ```
1559     #[inline]
1560     fn from(cow: Cow<'_, str>) -> Box<str> {
1561         match cow {
1562             Cow::Borrowed(s) => Box::from(s),
1563             Cow::Owned(s) => Box::from(s),
1564         }
1565     }
1566 }
1567
1568 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1569 impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1570     /// Converts a `Box<str>` into a `Box<[u8]>`
1571     ///
1572     /// This conversion does not allocate on the heap and happens in place.
1573     ///
1574     /// # Examples
1575     /// ```rust
1576     /// // create a Box<str> which will be used to create a Box<[u8]>
1577     /// let boxed: Box<str> = Box::from("hello");
1578     /// let boxed_str: Box<[u8]> = Box::from(boxed);
1579     ///
1580     /// // create a &[u8] which will be used to create a Box<[u8]>
1581     /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1582     /// let boxed_slice = Box::from(slice);
1583     ///
1584     /// assert_eq!(boxed_slice, boxed_str);
1585     /// ```
1586     #[inline]
1587     fn from(s: Box<str, A>) -> Self {
1588         let (raw, alloc) = Box::into_raw_with_allocator(s);
1589         unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1590     }
1591 }
1592
1593 #[cfg(not(no_global_oom_handling))]
1594 #[stable(feature = "box_from_array", since = "1.45.0")]
1595 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1596     /// Converts a `[T; N]` into a `Box<[T]>`
1597     ///
1598     /// This conversion moves the array to newly heap-allocated memory.
1599     ///
1600     /// # Examples
1601     ///
1602     /// ```rust
1603     /// let boxed: Box<[u8]> = Box::from([4, 2]);
1604     /// println!("{boxed:?}");
1605     /// ```
1606     fn from(array: [T; N]) -> Box<[T]> {
1607         #[cfg_attr(not(bootstrap), rustc_box)]
1608         Box::new(array)
1609     }
1610 }
1611
1612 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1613 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1614     type Error = Box<[T]>;
1615
1616     /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1617     ///
1618     /// The conversion occurs in-place and does not require a
1619     /// new memory allocation.
1620     ///
1621     /// # Errors
1622     ///
1623     /// Returns the old `Box<[T]>` in the `Err` variant if
1624     /// `boxed_slice.len()` does not equal `N`.
1625     fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1626         if boxed_slice.len() == N {
1627             Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1628         } else {
1629             Err(boxed_slice)
1630         }
1631     }
1632 }
1633
1634 impl<A: Allocator> Box<dyn Any, A> {
1635     /// Attempt to downcast the box to a concrete type.
1636     ///
1637     /// # Examples
1638     ///
1639     /// ```
1640     /// use std::any::Any;
1641     ///
1642     /// fn print_if_string(value: Box<dyn Any>) {
1643     ///     if let Ok(string) = value.downcast::<String>() {
1644     ///         println!("String ({}): {}", string.len(), string);
1645     ///     }
1646     /// }
1647     ///
1648     /// let my_string = "Hello World".to_string();
1649     /// print_if_string(Box::new(my_string));
1650     /// print_if_string(Box::new(0i8));
1651     /// ```
1652     #[inline]
1653     #[stable(feature = "rust1", since = "1.0.0")]
1654     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1655         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1656     }
1657
1658     /// Downcasts the box to a concrete type.
1659     ///
1660     /// For a safe alternative see [`downcast`].
1661     ///
1662     /// # Examples
1663     ///
1664     /// ```
1665     /// #![feature(downcast_unchecked)]
1666     ///
1667     /// use std::any::Any;
1668     ///
1669     /// let x: Box<dyn Any> = Box::new(1_usize);
1670     ///
1671     /// unsafe {
1672     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1673     /// }
1674     /// ```
1675     ///
1676     /// # Safety
1677     ///
1678     /// The contained value must be of type `T`. Calling this method
1679     /// with the incorrect type is *undefined behavior*.
1680     ///
1681     /// [`downcast`]: Self::downcast
1682     #[inline]
1683     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1684     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1685         debug_assert!(self.is::<T>());
1686         unsafe {
1687             let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1688             Box::from_raw_in(raw as *mut T, alloc)
1689         }
1690     }
1691 }
1692
1693 impl<A: Allocator> Box<dyn Any + Send, A> {
1694     /// Attempt to downcast the box to a concrete type.
1695     ///
1696     /// # Examples
1697     ///
1698     /// ```
1699     /// use std::any::Any;
1700     ///
1701     /// fn print_if_string(value: Box<dyn Any + Send>) {
1702     ///     if let Ok(string) = value.downcast::<String>() {
1703     ///         println!("String ({}): {}", string.len(), string);
1704     ///     }
1705     /// }
1706     ///
1707     /// let my_string = "Hello World".to_string();
1708     /// print_if_string(Box::new(my_string));
1709     /// print_if_string(Box::new(0i8));
1710     /// ```
1711     #[inline]
1712     #[stable(feature = "rust1", since = "1.0.0")]
1713     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1714         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1715     }
1716
1717     /// Downcasts the box to a concrete type.
1718     ///
1719     /// For a safe alternative see [`downcast`].
1720     ///
1721     /// # Examples
1722     ///
1723     /// ```
1724     /// #![feature(downcast_unchecked)]
1725     ///
1726     /// use std::any::Any;
1727     ///
1728     /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1729     ///
1730     /// unsafe {
1731     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1732     /// }
1733     /// ```
1734     ///
1735     /// # Safety
1736     ///
1737     /// The contained value must be of type `T`. Calling this method
1738     /// with the incorrect type is *undefined behavior*.
1739     ///
1740     /// [`downcast`]: Self::downcast
1741     #[inline]
1742     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1743     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1744         debug_assert!(self.is::<T>());
1745         unsafe {
1746             let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1747             Box::from_raw_in(raw as *mut T, alloc)
1748         }
1749     }
1750 }
1751
1752 impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1753     /// Attempt to downcast the box to a concrete type.
1754     ///
1755     /// # Examples
1756     ///
1757     /// ```
1758     /// use std::any::Any;
1759     ///
1760     /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1761     ///     if let Ok(string) = value.downcast::<String>() {
1762     ///         println!("String ({}): {}", string.len(), string);
1763     ///     }
1764     /// }
1765     ///
1766     /// let my_string = "Hello World".to_string();
1767     /// print_if_string(Box::new(my_string));
1768     /// print_if_string(Box::new(0i8));
1769     /// ```
1770     #[inline]
1771     #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1772     pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1773         if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1774     }
1775
1776     /// Downcasts the box to a concrete type.
1777     ///
1778     /// For a safe alternative see [`downcast`].
1779     ///
1780     /// # Examples
1781     ///
1782     /// ```
1783     /// #![feature(downcast_unchecked)]
1784     ///
1785     /// use std::any::Any;
1786     ///
1787     /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1788     ///
1789     /// unsafe {
1790     ///     assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1791     /// }
1792     /// ```
1793     ///
1794     /// # Safety
1795     ///
1796     /// The contained value must be of type `T`. Calling this method
1797     /// with the incorrect type is *undefined behavior*.
1798     ///
1799     /// [`downcast`]: Self::downcast
1800     #[inline]
1801     #[unstable(feature = "downcast_unchecked", issue = "90850")]
1802     pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1803         debug_assert!(self.is::<T>());
1804         unsafe {
1805             let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1806                 Box::into_raw_with_allocator(self);
1807             Box::from_raw_in(raw as *mut T, alloc)
1808         }
1809     }
1810 }
1811
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1814     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1815         fmt::Display::fmt(&**self, f)
1816     }
1817 }
1818
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1821     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1822         fmt::Debug::fmt(&**self, f)
1823     }
1824 }
1825
1826 #[stable(feature = "rust1", since = "1.0.0")]
1827 impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1828     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1829         // It's not possible to extract the inner Uniq directly from the Box,
1830         // instead we cast it to a *const which aliases the Unique
1831         let ptr: *const T = &**self;
1832         fmt::Pointer::fmt(&ptr, f)
1833     }
1834 }
1835
1836 #[stable(feature = "rust1", since = "1.0.0")]
1837 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1838 impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1839     type Target = T;
1840
1841     fn deref(&self) -> &T {
1842         &**self
1843     }
1844 }
1845
1846 #[stable(feature = "rust1", since = "1.0.0")]
1847 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1848 impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1849     fn deref_mut(&mut self) -> &mut T {
1850         &mut **self
1851     }
1852 }
1853
1854 #[unstable(feature = "receiver_trait", issue = "none")]
1855 impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1856
1857 #[stable(feature = "rust1", since = "1.0.0")]
1858 impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1859     type Item = I::Item;
1860     fn next(&mut self) -> Option<I::Item> {
1861         (**self).next()
1862     }
1863     fn size_hint(&self) -> (usize, Option<usize>) {
1864         (**self).size_hint()
1865     }
1866     fn nth(&mut self, n: usize) -> Option<I::Item> {
1867         (**self).nth(n)
1868     }
1869     fn last(self) -> Option<I::Item> {
1870         BoxIter::last(self)
1871     }
1872 }
1873
1874 trait BoxIter {
1875     type Item;
1876     fn last(self) -> Option<Self::Item>;
1877 }
1878
1879 impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1880     type Item = I::Item;
1881     default fn last(self) -> Option<I::Item> {
1882         #[inline]
1883         fn some<T>(_: Option<T>, x: T) -> Option<T> {
1884             Some(x)
1885         }
1886
1887         self.fold(None, some)
1888     }
1889 }
1890
1891 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1892 /// instead of the default.
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1895     fn last(self) -> Option<I::Item> {
1896         (*self).last()
1897     }
1898 }
1899
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1902     fn next_back(&mut self) -> Option<I::Item> {
1903         (**self).next_back()
1904     }
1905     fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1906         (**self).nth_back(n)
1907     }
1908 }
1909 #[stable(feature = "rust1", since = "1.0.0")]
1910 impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1911     fn len(&self) -> usize {
1912         (**self).len()
1913     }
1914     fn is_empty(&self) -> bool {
1915         (**self).is_empty()
1916     }
1917 }
1918
1919 #[stable(feature = "fused", since = "1.26.0")]
1920 impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1921
1922 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1923 impl<Args, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1924     type Output = <F as FnOnce<Args>>::Output;
1925
1926     extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1927         <F as FnOnce<Args>>::call_once(*self, args)
1928     }
1929 }
1930
1931 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1932 impl<Args, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1933     extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1934         <F as FnMut<Args>>::call_mut(self, args)
1935     }
1936 }
1937
1938 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1939 impl<Args, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1940     extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1941         <F as Fn<Args>>::call(self, args)
1942     }
1943 }
1944
1945 #[unstable(feature = "coerce_unsized", issue = "27732")]
1946 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1947
1948 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1949 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1950
1951 #[cfg(not(no_global_oom_handling))]
1952 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1953 impl<I> FromIterator<I> for Box<[I]> {
1954     fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1955         iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1956     }
1957 }
1958
1959 #[cfg(not(no_global_oom_handling))]
1960 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1961 impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1962     fn clone(&self) -> Self {
1963         let alloc = Box::allocator(self).clone();
1964         self.to_vec_in(alloc).into_boxed_slice()
1965     }
1966
1967     fn clone_from(&mut self, other: &Self) {
1968         if self.len() == other.len() {
1969             self.clone_from_slice(&other);
1970         } else {
1971             *self = other.clone();
1972         }
1973     }
1974 }
1975
1976 #[stable(feature = "box_borrow", since = "1.1.0")]
1977 impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
1978     fn borrow(&self) -> &T {
1979         &**self
1980     }
1981 }
1982
1983 #[stable(feature = "box_borrow", since = "1.1.0")]
1984 impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
1985     fn borrow_mut(&mut self) -> &mut T {
1986         &mut **self
1987     }
1988 }
1989
1990 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1991 impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
1992     fn as_ref(&self) -> &T {
1993         &**self
1994     }
1995 }
1996
1997 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1998 impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
1999     fn as_mut(&mut self) -> &mut T {
2000         &mut **self
2001     }
2002 }
2003
2004 /* Nota bene
2005  *
2006  *  We could have chosen not to add this impl, and instead have written a
2007  *  function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2008  *  because Box<T> implements Unpin even when T does not, as a result of
2009  *  this impl.
2010  *
2011  *  We chose this API instead of the alternative for a few reasons:
2012  *      - Logically, it is helpful to understand pinning in regard to the
2013  *        memory region being pointed to. For this reason none of the
2014  *        standard library pointer types support projecting through a pin
2015  *        (Box<T> is the only pointer type in std for which this would be
2016  *        safe.)
2017  *      - It is in practice very useful to have Box<T> be unconditionally
2018  *        Unpin because of trait objects, for which the structural auto
2019  *        trait functionality does not apply (e.g., Box<dyn Foo> would
2020  *        otherwise not be Unpin).
2021  *
2022  *  Another type with the same semantics as Box but only a conditional
2023  *  implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2024  *  could have a method to project a Pin<T> from it.
2025  */
2026 #[stable(feature = "pin", since = "1.33.0")]
2027 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
2028 impl<T: ?Sized, A: Allocator> const Unpin for Box<T, A> where A: 'static {}
2029
2030 #[unstable(feature = "generator_trait", issue = "43122")]
2031 impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2032 where
2033     A: 'static,
2034 {
2035     type Yield = G::Yield;
2036     type Return = G::Return;
2037
2038     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2039         G::resume(Pin::new(&mut *self), arg)
2040     }
2041 }
2042
2043 #[unstable(feature = "generator_trait", issue = "43122")]
2044 impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2045 where
2046     A: 'static,
2047 {
2048     type Yield = G::Yield;
2049     type Return = G::Return;
2050
2051     fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2052         G::resume((*self).as_mut(), arg)
2053     }
2054 }
2055
2056 #[stable(feature = "futures_api", since = "1.36.0")]
2057 impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2058 where
2059     A: 'static,
2060 {
2061     type Output = F::Output;
2062
2063     fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2064         F::poll(Pin::new(&mut *self), cx)
2065     }
2066 }
2067
2068 #[unstable(feature = "async_iterator", issue = "79024")]
2069 impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2070     type Item = S::Item;
2071
2072     fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2073         Pin::new(&mut **self).poll_next(cx)
2074     }
2075
2076     fn size_hint(&self) -> (usize, Option<usize>) {
2077         (**self).size_hint()
2078     }
2079 }