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