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