alloc/boxed.rs
1//! The `Box<T>` 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//! # #[allow(dead_code)]
28//! #[derive(Debug)]
29//! enum List<T> {
30//! Cons(T, Box<List<T>>),
31//! Nil,
32//! }
33//!
34//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
35//! println!("{list:?}");
36//! ```
37//!
38//! This will print `Cons(1, Cons(2, Nil))`.
39//!
40//! Recursive structures must be boxed, because if the definition of `Cons`
41//! looked like this:
42//!
43//! ```compile_fail,E0072
44//! # enum List<T> {
45//! Cons(T, List<T>),
46//! # }
47//! ```
48//!
49//! It wouldn't work. This is because the size of a `List` depends on how many
50//! elements are in the list, and so we don't know how much memory to allocate
51//! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
52//! big `Cons` needs to be.
53//!
54//! # Memory layout
55//!
56//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for its allocation. It is
57//! valid to convert both ways between a [`Box`] and a raw pointer allocated with the [`Global`]
58//! allocator, given that the [`Layout`] used with the allocator is correct for the type and the raw
59//! pointer points to a valid value of the right type. More precisely, a `value: *mut T` that has
60//! been allocated with the [`Global`] allocator with `Layout::for_value(&*value)` may be converted
61//! into a box using [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut T`
62//! obtained from [`Box::<T>::into_raw`] may be deallocated using the [`Global`] allocator with
63//! [`Layout::for_value(&*value)`].
64//!
65//! For zero-sized values, the `Box` pointer has to be non-null and sufficiently aligned. The
66//! recommended way to build a Box to a ZST if `Box::new` cannot be used is to use
67//! [`ptr::NonNull::dangling`].
68//!
69//! On top of these basic layout requirements, a `Box<T>` must point to a valid value of `T`.
70//!
71//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
72//! as a single pointer and is also ABI-compatible with C pointers
73//! (i.e. the C type `T*`). This means that if you have extern "C"
74//! Rust functions that will be called from C, you can define those
75//! Rust functions using `Box<T>` types, and use `T*` as corresponding
76//! type on the C side. As an example, consider this C header which
77//! declares functions that create and destroy some kind of `Foo`
78//! value:
79//!
80//! ```c
81//! /* C header */
82//!
83//! /* Returns ownership to the caller */
84//! struct Foo* foo_new(void);
85//!
86//! /* Takes ownership from the caller; no-op when invoked with null */
87//! void foo_delete(struct Foo*);
88//! ```
89//!
90//! These two functions might be implemented in Rust as follows. Here, the
91//! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
92//! the ownership constraints. Note also that the nullable argument to
93//! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
94//! cannot be null.
95//!
96//! ```
97//! #[repr(C)]
98//! pub struct Foo;
99//!
100//! #[unsafe(no_mangle)]
101//! pub extern "C" fn foo_new() -> Box<Foo> {
102//! Box::new(Foo)
103//! }
104//!
105//! #[unsafe(no_mangle)]
106//! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
107//! ```
108//!
109//! Even though `Box<T>` has the same representation and C ABI as a C pointer,
110//! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
111//! and expect things to work. `Box<T>` values will always be fully aligned,
112//! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
113//! free the value with the global allocator. In general, the best practice
114//! is to only use `Box<T>` for pointers that originated from the global
115//! allocator.
116//!
117//! **Important.** At least at present, you should avoid using
118//! `Box<T>` types for functions that are defined in C but invoked
119//! from Rust. In those cases, you should directly mirror the C types
120//! as closely as possible. Using types like `Box<T>` where the C
121//! definition is just using `T*` can lead to undefined behavior, as
122//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
123//!
124//! # Considerations for unsafe code
125//!
126//! **Warning: This section is not normative and is subject to change, possibly
127//! being relaxed in the future! It is a simplified summary of the rules
128//! currently implemented in the compiler.**
129//!
130//! The aliasing rules for `Box<T>` are the same as for `&mut T`. `Box<T>`
131//! asserts uniqueness over its content. Using raw pointers derived from a box
132//! after that box has been mutated through, moved or borrowed as `&mut T`
133//! is not allowed. For more guidance on working with box from unsafe code, see
134//! [rust-lang/unsafe-code-guidelines#326][ucg#326].
135//!
136//! # Editions
137//!
138//! A special case exists for the implementation of `IntoIterator` for arrays on the Rust 2021
139//! edition, as documented [here][array]. Unfortunately, it was later found that a similar
140//! workaround should be added for boxed slices, and this was applied in the 2024 edition.
141//!
142//! Specifically, `IntoIterator` is implemented for `Box<[T]>` on all editions, but specific calls
143//! to `into_iter()` for boxed slices will defer to the slice implementation on editions before
144//! 2024:
145//!
146//! ```rust,edition2021
147//! // Rust 2015, 2018, and 2021:
148//!
149//! # #![allow(boxed_slice_into_iter)] // override our `deny(warnings)`
150//! let boxed_slice: Box<[i32]> = vec![0; 3].into_boxed_slice();
151//!
152//! // This creates a slice iterator, producing references to each value.
153//! for item in boxed_slice.into_iter().enumerate() {
154//! let (i, x): (usize, &i32) = item;
155//! println!("boxed_slice[{i}] = {x}");
156//! }
157//!
158//! // The `boxed_slice_into_iter` lint suggests this change for future compatibility:
159//! for item in boxed_slice.iter().enumerate() {
160//! let (i, x): (usize, &i32) = item;
161//! println!("boxed_slice[{i}] = {x}");
162//! }
163//!
164//! // You can explicitly iterate a boxed slice by value using `IntoIterator::into_iter`
165//! for item in IntoIterator::into_iter(boxed_slice).enumerate() {
166//! let (i, x): (usize, i32) = item;
167//! println!("boxed_slice[{i}] = {x}");
168//! }
169//! ```
170//!
171//! Similar to the array implementation, this may be modified in the future to remove this override,
172//! and it's best to avoid relying on this edition-dependent behavior if you wish to preserve
173//! compatibility with future versions of the compiler.
174//!
175//! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
176//! [ucg#326]: https://github.com/rust-lang/unsafe-code-guidelines/issues/326
177//! [dereferencing]: core::ops::Deref
178//! [`Box::<T>::from_raw(value)`]: Box::from_raw
179//! [`Global`]: crate::alloc::Global
180//! [`Layout`]: crate::alloc::Layout
181//! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
182//! [valid]: ptr#safety
183
184#![stable(feature = "rust1", since = "1.0.0")]
185
186use core::borrow::{Borrow, BorrowMut};
187use core::clone::CloneToUninit;
188use core::cmp::Ordering;
189use core::error::{self, Error};
190use core::fmt;
191use core::future::Future;
192use core::hash::{Hash, Hasher};
193use core::marker::{Tuple, Unsize};
194#[cfg(not(no_global_oom_handling))]
195use core::mem::MaybeUninit;
196use core::mem::{self, SizedTypeProperties};
197use core::ops::{
198 AsyncFn, AsyncFnMut, AsyncFnOnce, CoerceUnsized, Coroutine, CoroutineState, Deref, DerefMut,
199 DerefPure, DispatchFromDyn, LegacyReceiver,
200};
201#[cfg(not(no_global_oom_handling))]
202use core::ops::{Residual, Try};
203use core::pin::{Pin, PinCoerceUnsized};
204use core::ptr::{self, NonNull, Unique};
205use core::task::{Context, Poll};
206
207#[cfg(not(no_global_oom_handling))]
208use crate::alloc::handle_alloc_error;
209use crate::alloc::{AllocError, Allocator, Global, Layout};
210use crate::raw_vec::RawVec;
211#[cfg(not(no_global_oom_handling))]
212use crate::str::from_boxed_utf8_unchecked;
213
214/// Conversion related impls for `Box<_>` (`From`, `downcast`, etc)
215mod convert;
216/// Iterator related impls for `Box<_>`.
217mod iter;
218/// [`ThinBox`] implementation.
219mod thin;
220
221#[stable(feature = "boxed_array_value_iter", since = "CURRENT_RUSTC_VERSION")]
222pub use iter::BoxedArrayIntoIter;
223#[unstable(feature = "thin_box", issue = "92791")]
224pub use thin::ThinBox;
225
226/// A pointer type that uniquely owns a heap allocation of type `T`.
227///
228/// See the [module-level documentation](../../std/boxed/index.html) for more.
229#[lang = "owned_box"]
230#[fundamental]
231#[stable(feature = "rust1", since = "1.0.0")]
232#[rustc_insignificant_dtor]
233#[doc(search_unbox)]
234// The declaration of the `Box` struct must be kept in sync with the
235// compiler or ICEs will happen.
236pub struct Box<
237 T: ?Sized,
238 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
239>(Unique<T>, A);
240
241/// Monomorphic function for allocating an uninit `Box`.
242#[inline]
243// The is a separate function to avoid doing it in every generic version, but it
244// looks small to the mir inliner (particularly in panic=abort) so leave it to
245// the backend to decide whether pulling it in everywhere is worth doing.
246#[rustc_no_mir_inline]
247#[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
248#[cfg(not(no_global_oom_handling))]
249#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
250const fn box_new_uninit(layout: Layout) -> *mut u8 {
251 match Global.allocate(layout) {
252 Ok(ptr) => ptr.as_mut_ptr(),
253 Err(_) => handle_alloc_error(layout),
254 }
255}
256
257/// Helper for `vec!`.
258///
259/// This is unsafe, but has to be marked as safe or else we couldn't use it in `vec!`.
260#[doc(hidden)]
261#[unstable(feature = "liballoc_internals", issue = "none")]
262#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
263#[inline(always)]
264#[cfg(not(no_global_oom_handling))]
265#[rustc_diagnostic_item = "box_assume_init_into_vec_unsafe"]
266pub const fn box_assume_init_into_vec_unsafe<T, const N: usize>(
267 b: Box<MaybeUninit<[T; N]>>,
268) -> crate::vec::Vec<T> {
269 unsafe { (b.assume_init() as Box<[T]>).into_vec() }
270}
271
272impl<T> Box<T> {
273 /// Allocates memory on the heap and then places `x` into it.
274 ///
275 /// This doesn't actually allocate if `T` is zero-sized.
276 ///
277 /// # Examples
278 ///
279 /// ```
280 /// let five = Box::new(5);
281 /// ```
282 #[cfg(not(no_global_oom_handling))]
283 #[ferrocene::prevalidated]
284 #[inline(always)]
285 #[stable(feature = "rust1", since = "1.0.0")]
286 #[must_use]
287 #[rustc_diagnostic_item = "box_new"]
288 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
289 pub fn new(x: T) -> Self {
290 // This is `Box::new_uninit` but inlined to avoid build time regressions.
291 let ptr = box_new_uninit(<T as SizedTypeProperties>::LAYOUT) as *mut T;
292 // Nothing below can panic so we do not have to worry about deallocating `ptr`.
293 // SAFETY: we just allocated the box to store `x`.
294 unsafe { core::intrinsics::write_via_move(ptr, x) };
295 // SAFETY: we just initialized the memory `ptr` points to.
296 unsafe { mem::transmute(ptr) }
297 }
298
299 /// Constructs a new box with uninitialized contents.
300 ///
301 /// # Examples
302 ///
303 /// ```
304 /// let mut five = Box::<u32>::new_uninit();
305 /// // Deferred initialization:
306 /// five.write(5);
307 /// let five = unsafe { five.assume_init() };
308 ///
309 /// assert_eq!(*five, 5)
310 /// ```
311 #[cfg(not(no_global_oom_handling))]
312 #[stable(feature = "new_uninit", since = "1.82.0")]
313 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
314 #[must_use]
315 #[inline(always)]
316 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces
317 pub const fn new_uninit() -> Box<mem::MaybeUninit<T>> {
318 // This is the same as `Self::new_uninit_in(Global)`, but manually inlined (just like
319 // `Box::new`).
320
321 // SAFETY:
322 // - If `allocate` succeeds, the returned pointer exactly matches what `Box` needs.
323 unsafe { mem::transmute(box_new_uninit(<T as SizedTypeProperties>::LAYOUT)) }
324 }
325
326 /// Constructs a new `Box` with uninitialized contents, with the memory
327 /// being filled with `0` bytes.
328 ///
329 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
330 /// of this method.
331 ///
332 /// # Examples
333 ///
334 /// ```
335 /// let zero = Box::<u32>::new_zeroed();
336 /// let zero = unsafe { zero.assume_init() };
337 ///
338 /// assert_eq!(*zero, 0)
339 /// ```
340 ///
341 /// [zeroed]: mem::MaybeUninit::zeroed
342 #[cfg(not(no_global_oom_handling))]
343 #[inline]
344 #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
345 #[must_use]
346 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
347 Self::new_zeroed_in(Global)
348 }
349
350 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
351 /// `x` will be pinned in memory and unable to be moved.
352 ///
353 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
354 /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
355 /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
356 /// construct a (pinned) `Box` in a different way than with [`Box::new`].
357 #[cfg(not(no_global_oom_handling))]
358 #[stable(feature = "pin", since = "1.33.0")]
359 #[must_use]
360 #[inline(always)]
361 pub fn pin(x: T) -> Pin<Box<T>> {
362 Box::new(x).into()
363 }
364
365 /// Allocates memory on the heap then places `x` into it,
366 /// returning an error if the allocation fails
367 ///
368 /// This doesn't actually allocate if `T` is zero-sized.
369 ///
370 /// # Examples
371 ///
372 /// ```
373 /// #![feature(allocator_api)]
374 ///
375 /// let five = Box::try_new(5)?;
376 /// # Ok::<(), std::alloc::AllocError>(())
377 /// ```
378 #[unstable(feature = "allocator_api", issue = "32838")]
379 #[inline]
380 pub fn try_new(x: T) -> Result<Self, AllocError> {
381 Self::try_new_in(x, Global)
382 }
383
384 /// Constructs a new box with uninitialized contents on the heap,
385 /// returning an error if the allocation fails
386 ///
387 /// # Examples
388 ///
389 /// ```
390 /// #![feature(allocator_api)]
391 ///
392 /// let mut five = Box::<u32>::try_new_uninit()?;
393 /// // Deferred initialization:
394 /// five.write(5);
395 /// let five = unsafe { five.assume_init() };
396 ///
397 /// assert_eq!(*five, 5);
398 /// # Ok::<(), std::alloc::AllocError>(())
399 /// ```
400 #[unstable(feature = "allocator_api", issue = "32838")]
401 #[inline]
402 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
403 Box::try_new_uninit_in(Global)
404 }
405
406 /// Constructs a new `Box` with uninitialized contents, with the memory
407 /// being filled with `0` bytes on the heap
408 ///
409 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
410 /// of this method.
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// #![feature(allocator_api)]
416 ///
417 /// let zero = Box::<u32>::try_new_zeroed()?;
418 /// let zero = unsafe { zero.assume_init() };
419 ///
420 /// assert_eq!(*zero, 0);
421 /// # Ok::<(), std::alloc::AllocError>(())
422 /// ```
423 ///
424 /// [zeroed]: mem::MaybeUninit::zeroed
425 #[unstable(feature = "allocator_api", issue = "32838")]
426 #[inline]
427 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
428 Box::try_new_zeroed_in(Global)
429 }
430
431 /// Maps the value in a box, reusing the allocation if possible.
432 ///
433 /// `f` is called on the value in the box, and the result is returned, also boxed.
434 ///
435 /// Note: this is an associated function, which means that you have
436 /// to call it as `Box::map(b, f)` instead of `b.map(f)`. This
437 /// is so that there is no conflict with a method on the inner type.
438 ///
439 /// # Examples
440 ///
441 /// ```
442 /// #![feature(smart_pointer_try_map)]
443 ///
444 /// let b = Box::new(7);
445 /// let new = Box::map(b, |i| i + 7);
446 /// assert_eq!(*new, 14);
447 /// ```
448 #[cfg(not(no_global_oom_handling))]
449 #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
450 pub fn map<U>(this: Self, f: impl FnOnce(T) -> U) -> Box<U> {
451 if size_of::<T>() == size_of::<U>() && align_of::<T>() == align_of::<U>() {
452 let (value, allocation) = Box::take(this);
453 Box::write(
454 unsafe { mem::transmute::<Box<MaybeUninit<T>>, Box<MaybeUninit<U>>>(allocation) },
455 f(value),
456 )
457 } else {
458 Box::new(f(*this))
459 }
460 }
461
462 /// Attempts to map the value in a box, reusing the allocation if possible.
463 ///
464 /// `f` is called on the value in the box, and if the operation succeeds, the result is
465 /// returned, also boxed.
466 ///
467 /// Note: this is an associated function, which means that you have
468 /// to call it as `Box::try_map(b, f)` instead of `b.try_map(f)`. This
469 /// is so that there is no conflict with a method on the inner type.
470 ///
471 /// # Examples
472 ///
473 /// ```
474 /// #![feature(smart_pointer_try_map)]
475 ///
476 /// let b = Box::new(7);
477 /// let new = Box::try_map(b, u32::try_from).unwrap();
478 /// assert_eq!(*new, 7);
479 /// ```
480 #[cfg(not(no_global_oom_handling))]
481 #[unstable(feature = "smart_pointer_try_map", issue = "144419")]
482 pub fn try_map<R>(
483 this: Self,
484 f: impl FnOnce(T) -> R,
485 ) -> <R::Residual as Residual<Box<R::Output>>>::TryType
486 where
487 R: Try,
488 R::Residual: Residual<Box<R::Output>>,
489 {
490 if size_of::<T>() == size_of::<R::Output>() && align_of::<T>() == align_of::<R::Output>() {
491 let (value, allocation) = Box::take(this);
492 try {
493 Box::write(
494 unsafe {
495 mem::transmute::<Box<MaybeUninit<T>>, Box<MaybeUninit<R::Output>>>(
496 allocation,
497 )
498 },
499 f(value)?,
500 )
501 }
502 } else {
503 try { Box::new(f(*this)?) }
504 }
505 }
506}
507
508impl<T, A: Allocator> Box<T, A> {
509 /// Allocates memory in the given allocator then places `x` into it.
510 ///
511 /// This doesn't actually allocate if `T` is zero-sized.
512 ///
513 /// # Examples
514 ///
515 /// ```
516 /// #![feature(allocator_api)]
517 ///
518 /// use std::alloc::System;
519 ///
520 /// let five = Box::new_in(5, System);
521 /// ```
522 #[cfg(not(no_global_oom_handling))]
523 #[unstable(feature = "allocator_api", issue = "32838")]
524 #[must_use]
525 #[inline]
526 pub fn new_in(x: T, alloc: A) -> Self
527 where
528 A: Allocator,
529 {
530 let mut boxed = Self::new_uninit_in(alloc);
531 boxed.write(x);
532 unsafe { boxed.assume_init() }
533 }
534
535 /// Allocates memory in the given allocator then places `x` into it,
536 /// returning an error if the allocation fails
537 ///
538 /// This doesn't actually allocate if `T` is zero-sized.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// #![feature(allocator_api)]
544 ///
545 /// use std::alloc::System;
546 ///
547 /// let five = Box::try_new_in(5, System)?;
548 /// # Ok::<(), std::alloc::AllocError>(())
549 /// ```
550 #[unstable(feature = "allocator_api", issue = "32838")]
551 #[inline]
552 pub fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
553 where
554 A: Allocator,
555 {
556 let mut boxed = Self::try_new_uninit_in(alloc)?;
557 boxed.write(x);
558 unsafe { Ok(boxed.assume_init()) }
559 }
560
561 /// Constructs a new box with uninitialized contents in the provided allocator.
562 ///
563 /// # Examples
564 ///
565 /// ```
566 /// #![feature(allocator_api)]
567 ///
568 /// use std::alloc::System;
569 ///
570 /// let mut five = Box::<u32, _>::new_uninit_in(System);
571 /// // Deferred initialization:
572 /// five.write(5);
573 /// let five = unsafe { five.assume_init() };
574 ///
575 /// assert_eq!(*five, 5)
576 /// ```
577 #[unstable(feature = "allocator_api", issue = "32838")]
578 #[cfg(not(no_global_oom_handling))]
579 #[must_use]
580 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
581 where
582 A: Allocator,
583 {
584 let layout = Layout::new::<mem::MaybeUninit<T>>();
585 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
586 // That would make code size bigger.
587 match Box::try_new_uninit_in(alloc) {
588 Ok(m) => m,
589 Err(_) => handle_alloc_error(layout),
590 }
591 }
592
593 /// Constructs a new box with uninitialized contents in the provided allocator,
594 /// returning an error if the allocation fails
595 ///
596 /// # Examples
597 ///
598 /// ```
599 /// #![feature(allocator_api)]
600 ///
601 /// use std::alloc::System;
602 ///
603 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
604 /// // Deferred initialization:
605 /// five.write(5);
606 /// let five = unsafe { five.assume_init() };
607 ///
608 /// assert_eq!(*five, 5);
609 /// # Ok::<(), std::alloc::AllocError>(())
610 /// ```
611 #[unstable(feature = "allocator_api", issue = "32838")]
612 pub fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
613 where
614 A: Allocator,
615 {
616 let ptr = if T::IS_ZST {
617 NonNull::dangling()
618 } else {
619 let layout = Layout::new::<mem::MaybeUninit<T>>();
620 alloc.allocate(layout)?.cast()
621 };
622 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
623 }
624
625 /// Constructs a new `Box` with uninitialized contents, with the memory
626 /// being filled with `0` bytes in the provided allocator.
627 ///
628 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
629 /// of this method.
630 ///
631 /// # Examples
632 ///
633 /// ```
634 /// #![feature(allocator_api)]
635 ///
636 /// use std::alloc::System;
637 ///
638 /// let zero = Box::<u32, _>::new_zeroed_in(System);
639 /// let zero = unsafe { zero.assume_init() };
640 ///
641 /// assert_eq!(*zero, 0)
642 /// ```
643 ///
644 /// [zeroed]: mem::MaybeUninit::zeroed
645 #[unstable(feature = "allocator_api", issue = "32838")]
646 #[cfg(not(no_global_oom_handling))]
647 #[must_use]
648 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
649 where
650 A: Allocator,
651 {
652 let layout = Layout::new::<mem::MaybeUninit<T>>();
653 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
654 // That would make code size bigger.
655 match Box::try_new_zeroed_in(alloc) {
656 Ok(m) => m,
657 Err(_) => handle_alloc_error(layout),
658 }
659 }
660
661 /// Constructs a new `Box` with uninitialized contents, with the memory
662 /// being filled with `0` bytes in the provided allocator,
663 /// returning an error if the allocation fails,
664 ///
665 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
666 /// of this method.
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// #![feature(allocator_api)]
672 ///
673 /// use std::alloc::System;
674 ///
675 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
676 /// let zero = unsafe { zero.assume_init() };
677 ///
678 /// assert_eq!(*zero, 0);
679 /// # Ok::<(), std::alloc::AllocError>(())
680 /// ```
681 ///
682 /// [zeroed]: mem::MaybeUninit::zeroed
683 #[unstable(feature = "allocator_api", issue = "32838")]
684 pub fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
685 where
686 A: Allocator,
687 {
688 let ptr = if T::IS_ZST {
689 NonNull::dangling()
690 } else {
691 let layout = Layout::new::<mem::MaybeUninit<T>>();
692 alloc.allocate_zeroed(layout)?.cast()
693 };
694 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
695 }
696
697 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
698 /// `x` will be pinned in memory and unable to be moved.
699 ///
700 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin_in(x, alloc)`
701 /// does the same as <code>[Box::into_pin]\([Box::new_in]\(x, alloc))</code>. Consider using
702 /// [`into_pin`](Box::into_pin) if you already have a `Box<T, A>`, or if you want to
703 /// construct a (pinned) `Box` in a different way than with [`Box::new_in`].
704 ///
705 /// # Examples
706 ///
707 /// ```
708 /// #![feature(allocator_api)]
709 /// use std::alloc::System;
710 ///
711 /// let x = Box::pin_in(1, System);
712 /// ```
713 #[cfg(not(no_global_oom_handling))]
714 #[unstable(feature = "allocator_api", issue = "32838")]
715 #[must_use]
716 #[inline(always)]
717 pub fn pin_in(x: T, alloc: A) -> Pin<Self>
718 where
719 A: 'static + Allocator,
720 {
721 Self::into_pin(Self::new_in(x, alloc))
722 }
723
724 /// Converts a `Box<T>` into a `Box<[T]>`
725 ///
726 /// This conversion does not allocate on the heap and happens in place.
727 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
728 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
729 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
730 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
731 }
732
733 /// Consumes the `Box`, returning the wrapped value.
734 ///
735 /// # Examples
736 ///
737 /// ```
738 /// #![feature(box_into_inner)]
739 ///
740 /// let c = Box::new(5);
741 ///
742 /// assert_eq!(Box::into_inner(c), 5);
743 /// ```
744 #[unstable(feature = "box_into_inner", issue = "80437")]
745 #[inline]
746 pub fn into_inner(boxed: Self) -> T {
747 *boxed
748 }
749
750 /// Consumes the `Box` without consuming its allocation, returning the wrapped value and a `Box`
751 /// to the uninitialized memory where the wrapped value used to live.
752 ///
753 /// This can be used together with [`write`](Box::write) to reuse the allocation for multiple
754 /// boxed values.
755 ///
756 /// # Examples
757 ///
758 /// ```
759 /// #![feature(box_take)]
760 ///
761 /// let c = Box::new(5);
762 ///
763 /// // take the value out of the box
764 /// let (value, uninit) = Box::take(c);
765 /// assert_eq!(value, 5);
766 ///
767 /// // reuse the box for a second value
768 /// let c = Box::write(uninit, 6);
769 /// assert_eq!(*c, 6);
770 /// ```
771 #[unstable(feature = "box_take", issue = "147212")]
772 pub fn take(boxed: Self) -> (T, Box<mem::MaybeUninit<T>, A>) {
773 unsafe {
774 let (raw, alloc) = Box::into_non_null_with_allocator(boxed);
775 let value = raw.read();
776 let uninit = Box::from_non_null_in(raw.cast_uninit(), alloc);
777 (value, uninit)
778 }
779 }
780}
781
782impl<T: ?Sized + CloneToUninit> Box<T> {
783 /// Allocates memory on the heap then clones `src` into it.
784 ///
785 /// This doesn't actually allocate if `src` is zero-sized.
786 ///
787 /// # Examples
788 ///
789 /// ```
790 /// #![feature(clone_from_ref)]
791 ///
792 /// let hello: Box<str> = Box::clone_from_ref("hello");
793 /// ```
794 #[cfg(not(no_global_oom_handling))]
795 #[unstable(feature = "clone_from_ref", issue = "149075")]
796 #[must_use]
797 #[inline]
798 pub fn clone_from_ref(src: &T) -> Box<T> {
799 Box::clone_from_ref_in(src, Global)
800 }
801
802 /// Allocates memory on the heap then clones `src` into it, returning an error if allocation fails.
803 ///
804 /// This doesn't actually allocate if `src` is zero-sized.
805 ///
806 /// # Examples
807 ///
808 /// ```
809 /// #![feature(clone_from_ref)]
810 /// #![feature(allocator_api)]
811 ///
812 /// let hello: Box<str> = Box::try_clone_from_ref("hello")?;
813 /// # Ok::<(), std::alloc::AllocError>(())
814 /// ```
815 #[unstable(feature = "clone_from_ref", issue = "149075")]
816 //#[unstable(feature = "allocator_api", issue = "32838")]
817 #[must_use]
818 #[inline]
819 pub fn try_clone_from_ref(src: &T) -> Result<Box<T>, AllocError> {
820 Box::try_clone_from_ref_in(src, Global)
821 }
822}
823
824impl<T: ?Sized + CloneToUninit, A: Allocator> Box<T, A> {
825 /// Allocates memory in the given allocator then clones `src` into it.
826 ///
827 /// This doesn't actually allocate if `src` is zero-sized.
828 ///
829 /// # Examples
830 ///
831 /// ```
832 /// #![feature(clone_from_ref)]
833 /// #![feature(allocator_api)]
834 ///
835 /// use std::alloc::System;
836 ///
837 /// let hello: Box<str, System> = Box::clone_from_ref_in("hello", System);
838 /// ```
839 #[cfg(not(no_global_oom_handling))]
840 #[unstable(feature = "clone_from_ref", issue = "149075")]
841 //#[unstable(feature = "allocator_api", issue = "32838")]
842 #[must_use]
843 #[inline]
844 pub fn clone_from_ref_in(src: &T, alloc: A) -> Box<T, A> {
845 let layout = Layout::for_value::<T>(src);
846 match Box::try_clone_from_ref_in(src, alloc) {
847 Ok(bx) => bx,
848 Err(_) => handle_alloc_error(layout),
849 }
850 }
851
852 /// Allocates memory in the given allocator then clones `src` into it, returning an error if allocation fails.
853 ///
854 /// This doesn't actually allocate if `src` is zero-sized.
855 ///
856 /// # Examples
857 ///
858 /// ```
859 /// #![feature(clone_from_ref)]
860 /// #![feature(allocator_api)]
861 ///
862 /// use std::alloc::System;
863 ///
864 /// let hello: Box<str, System> = Box::try_clone_from_ref_in("hello", System)?;
865 /// # Ok::<(), std::alloc::AllocError>(())
866 /// ```
867 #[unstable(feature = "clone_from_ref", issue = "149075")]
868 //#[unstable(feature = "allocator_api", issue = "32838")]
869 #[must_use]
870 #[inline]
871 pub fn try_clone_from_ref_in(src: &T, alloc: A) -> Result<Box<T, A>, AllocError> {
872 struct DeallocDropGuard<'a, A: Allocator>(Layout, &'a A, NonNull<u8>);
873 impl<'a, A: Allocator> Drop for DeallocDropGuard<'a, A> {
874 fn drop(&mut self) {
875 let &mut DeallocDropGuard(layout, alloc, ptr) = self;
876 // Safety: `ptr` was allocated by `*alloc` with layout `layout`
877 unsafe {
878 alloc.deallocate(ptr, layout);
879 }
880 }
881 }
882 let layout = Layout::for_value::<T>(src);
883 let (ptr, guard) = if layout.size() == 0 {
884 (layout.dangling_ptr(), None)
885 } else {
886 // Safety: layout is non-zero-sized
887 let ptr = alloc.allocate(layout)?.cast();
888 (ptr, Some(DeallocDropGuard(layout, &alloc, ptr)))
889 };
890 let ptr = ptr.as_ptr();
891 // Safety: `*ptr` is newly allocated, correctly aligned to `align_of_val(src)`,
892 // and is valid for writes for `size_of_val(src)`.
893 // If this panics, then `guard` will deallocate for us (if allocation occuured)
894 unsafe {
895 <T as CloneToUninit>::clone_to_uninit(src, ptr);
896 }
897 // Defuse the deallocate guard
898 core::mem::forget(guard);
899 // Safety: We just initialized `*ptr` as a clone of `src`
900 Ok(unsafe { Box::from_raw_in(ptr.with_metadata_of(src), alloc) })
901 }
902}
903
904impl<T> Box<[T]> {
905 /// Constructs a new boxed slice with uninitialized contents.
906 ///
907 /// # Examples
908 ///
909 /// ```
910 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
911 /// // Deferred initialization:
912 /// values[0].write(1);
913 /// values[1].write(2);
914 /// values[2].write(3);
915 /// let values = unsafe { values.assume_init() };
916 ///
917 /// assert_eq!(*values, [1, 2, 3])
918 /// ```
919 #[cfg(not(no_global_oom_handling))]
920 #[stable(feature = "new_uninit", since = "1.82.0")]
921 #[must_use]
922 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
923 unsafe { RawVec::with_capacity(len).into_box(len) }
924 }
925
926 /// Constructs a new boxed slice with uninitialized contents, with the memory
927 /// being filled with `0` bytes.
928 ///
929 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
930 /// of this method.
931 ///
932 /// # Examples
933 ///
934 /// ```
935 /// let values = Box::<[u32]>::new_zeroed_slice(3);
936 /// let values = unsafe { values.assume_init() };
937 ///
938 /// assert_eq!(*values, [0, 0, 0])
939 /// ```
940 ///
941 /// [zeroed]: mem::MaybeUninit::zeroed
942 #[cfg(not(no_global_oom_handling))]
943 #[stable(feature = "new_zeroed_alloc", since = "1.92.0")]
944 #[must_use]
945 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
946 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
947 }
948
949 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
950 /// the allocation fails.
951 ///
952 /// # Examples
953 ///
954 /// ```
955 /// #![feature(allocator_api)]
956 ///
957 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
958 /// // Deferred initialization:
959 /// values[0].write(1);
960 /// values[1].write(2);
961 /// values[2].write(3);
962 /// let values = unsafe { values.assume_init() };
963 ///
964 /// assert_eq!(*values, [1, 2, 3]);
965 /// # Ok::<(), std::alloc::AllocError>(())
966 /// ```
967 #[unstable(feature = "allocator_api", issue = "32838")]
968 #[inline]
969 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
970 let ptr = if T::IS_ZST || len == 0 {
971 NonNull::dangling()
972 } else {
973 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
974 Ok(l) => l,
975 Err(_) => return Err(AllocError),
976 };
977 Global.allocate(layout)?.cast()
978 };
979 unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
980 }
981
982 /// Constructs a new boxed slice with uninitialized contents, with the memory
983 /// being filled with `0` bytes. Returns an error if the allocation fails.
984 ///
985 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
986 /// of this method.
987 ///
988 /// # Examples
989 ///
990 /// ```
991 /// #![feature(allocator_api)]
992 ///
993 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
994 /// let values = unsafe { values.assume_init() };
995 ///
996 /// assert_eq!(*values, [0, 0, 0]);
997 /// # Ok::<(), std::alloc::AllocError>(())
998 /// ```
999 ///
1000 /// [zeroed]: mem::MaybeUninit::zeroed
1001 #[unstable(feature = "allocator_api", issue = "32838")]
1002 #[inline]
1003 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
1004 let ptr = if T::IS_ZST || len == 0 {
1005 NonNull::dangling()
1006 } else {
1007 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1008 Ok(l) => l,
1009 Err(_) => return Err(AllocError),
1010 };
1011 Global.allocate_zeroed(layout)?.cast()
1012 };
1013 unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, Global).into_box(len)) }
1014 }
1015}
1016
1017impl<T, A: Allocator> Box<[T], A> {
1018 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
1019 ///
1020 /// # Examples
1021 ///
1022 /// ```
1023 /// #![feature(allocator_api)]
1024 ///
1025 /// use std::alloc::System;
1026 ///
1027 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
1028 /// // Deferred initialization:
1029 /// values[0].write(1);
1030 /// values[1].write(2);
1031 /// values[2].write(3);
1032 /// let values = unsafe { values.assume_init() };
1033 ///
1034 /// assert_eq!(*values, [1, 2, 3])
1035 /// ```
1036 #[cfg(not(no_global_oom_handling))]
1037 #[unstable(feature = "allocator_api", issue = "32838")]
1038 #[must_use]
1039 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
1040 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
1041 }
1042
1043 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
1044 /// with the memory being filled with `0` bytes.
1045 ///
1046 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1047 /// of this method.
1048 ///
1049 /// # Examples
1050 ///
1051 /// ```
1052 /// #![feature(allocator_api)]
1053 ///
1054 /// use std::alloc::System;
1055 ///
1056 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
1057 /// let values = unsafe { values.assume_init() };
1058 ///
1059 /// assert_eq!(*values, [0, 0, 0])
1060 /// ```
1061 ///
1062 /// [zeroed]: mem::MaybeUninit::zeroed
1063 #[cfg(not(no_global_oom_handling))]
1064 #[unstable(feature = "allocator_api", issue = "32838")]
1065 #[must_use]
1066 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
1067 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
1068 }
1069
1070 /// Constructs a new boxed slice with uninitialized contents in the provided allocator. Returns an error if
1071 /// the allocation fails.
1072 ///
1073 /// # Examples
1074 ///
1075 /// ```
1076 /// #![feature(allocator_api)]
1077 ///
1078 /// use std::alloc::System;
1079 ///
1080 /// let mut values = Box::<[u32], _>::try_new_uninit_slice_in(3, System)?;
1081 /// // Deferred initialization:
1082 /// values[0].write(1);
1083 /// values[1].write(2);
1084 /// values[2].write(3);
1085 /// let values = unsafe { values.assume_init() };
1086 ///
1087 /// assert_eq!(*values, [1, 2, 3]);
1088 /// # Ok::<(), std::alloc::AllocError>(())
1089 /// ```
1090 #[unstable(feature = "allocator_api", issue = "32838")]
1091 #[inline]
1092 pub fn try_new_uninit_slice_in(
1093 len: usize,
1094 alloc: A,
1095 ) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError> {
1096 let ptr = if T::IS_ZST || len == 0 {
1097 NonNull::dangling()
1098 } else {
1099 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1100 Ok(l) => l,
1101 Err(_) => return Err(AllocError),
1102 };
1103 alloc.allocate(layout)?.cast()
1104 };
1105 unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) }
1106 }
1107
1108 /// Constructs a new boxed slice with uninitialized contents in the provided allocator, with the memory
1109 /// being filled with `0` bytes. Returns an error if the allocation fails.
1110 ///
1111 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
1112 /// of this method.
1113 ///
1114 /// # Examples
1115 ///
1116 /// ```
1117 /// #![feature(allocator_api)]
1118 ///
1119 /// use std::alloc::System;
1120 ///
1121 /// let values = Box::<[u32], _>::try_new_zeroed_slice_in(3, System)?;
1122 /// let values = unsafe { values.assume_init() };
1123 ///
1124 /// assert_eq!(*values, [0, 0, 0]);
1125 /// # Ok::<(), std::alloc::AllocError>(())
1126 /// ```
1127 ///
1128 /// [zeroed]: mem::MaybeUninit::zeroed
1129 #[unstable(feature = "allocator_api", issue = "32838")]
1130 #[inline]
1131 pub fn try_new_zeroed_slice_in(
1132 len: usize,
1133 alloc: A,
1134 ) -> Result<Box<[mem::MaybeUninit<T>], A>, AllocError> {
1135 let ptr = if T::IS_ZST || len == 0 {
1136 NonNull::dangling()
1137 } else {
1138 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
1139 Ok(l) => l,
1140 Err(_) => return Err(AllocError),
1141 };
1142 alloc.allocate_zeroed(layout)?.cast()
1143 };
1144 unsafe { Ok(RawVec::from_raw_parts_in(ptr.as_ptr(), len, alloc).into_box(len)) }
1145 }
1146
1147 /// Converts the boxed slice into a boxed array.
1148 ///
1149 /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type.
1150 ///
1151 /// # Errors
1152 ///
1153 /// Returns the original `Box<[T]>` in the `Err` variant if `self.len()` does not equal `N`.
1154 ///
1155 /// # Examples
1156 ///
1157 /// ```
1158 /// #![feature(alloc_slice_into_array)]
1159 /// let box_slice: Box<[i32]> = Box::new([1, 2, 3]);
1160 ///
1161 /// let box_array: Box<[i32; 3]> = box_slice.into_array().unwrap();
1162 /// ```
1163 #[unstable(feature = "alloc_slice_into_array", issue = "148082")]
1164 #[inline]
1165 #[must_use]
1166 pub fn into_array<const N: usize>(self) -> Result<Box<[T; N], A>, Self> {
1167 if self.len() == N {
1168 let (ptr, alloc) = Self::into_raw_with_allocator(self);
1169 let ptr = ptr as *mut [T; N];
1170
1171 // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length.
1172 let me = unsafe { Box::from_raw_in(ptr, alloc) };
1173 Ok(me)
1174 } else {
1175 Err(self)
1176 }
1177 }
1178}
1179
1180impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
1181 /// Converts to `Box<T, A>`.
1182 ///
1183 /// # Safety
1184 ///
1185 /// As with [`MaybeUninit::assume_init`],
1186 /// it is up to the caller to guarantee that the value
1187 /// really is in an initialized state.
1188 /// Calling this when the content is not yet fully initialized
1189 /// causes immediate undefined behavior.
1190 ///
1191 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1192 ///
1193 /// # Examples
1194 ///
1195 /// ```
1196 /// let mut five = Box::<u32>::new_uninit();
1197 /// // Deferred initialization:
1198 /// five.write(5);
1199 /// let five: Box<u32> = unsafe { five.assume_init() };
1200 ///
1201 /// assert_eq!(*five, 5)
1202 /// ```
1203 #[stable(feature = "new_uninit", since = "1.82.0")]
1204 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1205 #[inline(always)]
1206 pub const unsafe fn assume_init(self) -> Box<T, A> {
1207 // This is used in the `vec!` macro, so we optimize for minimal IR generation
1208 // even in debug builds.
1209 // SAFETY: `Box<T>` and `Box<MaybeUninit<T>>` have the same layout.
1210 unsafe { core::intrinsics::transmute_unchecked(self) }
1211 }
1212
1213 /// Writes the value and converts to `Box<T, A>`.
1214 ///
1215 /// This method converts the box similarly to [`Box::assume_init`] but
1216 /// writes `value` into it before conversion thus guaranteeing safety.
1217 /// In some scenarios use of this method may improve performance because
1218 /// the compiler may be able to optimize copying from stack.
1219 ///
1220 /// # Examples
1221 ///
1222 /// ```
1223 /// let big_box = Box::<[usize; 1024]>::new_uninit();
1224 ///
1225 /// let mut array = [0; 1024];
1226 /// for (i, place) in array.iter_mut().enumerate() {
1227 /// *place = i;
1228 /// }
1229 ///
1230 /// // The optimizer may be able to elide this copy, so previous code writes
1231 /// // to heap directly.
1232 /// let big_box = Box::write(big_box, array);
1233 ///
1234 /// for (i, x) in big_box.iter().enumerate() {
1235 /// assert_eq!(*x, i);
1236 /// }
1237 /// ```
1238 #[stable(feature = "box_uninit_write", since = "1.87.0")]
1239 #[inline]
1240 pub fn write(mut boxed: Self, value: T) -> Box<T, A> {
1241 unsafe {
1242 (*boxed).write(value);
1243 boxed.assume_init()
1244 }
1245 }
1246}
1247
1248impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
1249 /// Converts to `Box<[T], A>`.
1250 ///
1251 /// # Safety
1252 ///
1253 /// As with [`MaybeUninit::assume_init`],
1254 /// it is up to the caller to guarantee that the values
1255 /// really are in an initialized state.
1256 /// Calling this when the content is not yet fully initialized
1257 /// causes immediate undefined behavior.
1258 ///
1259 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
1260 ///
1261 /// # Examples
1262 ///
1263 /// ```
1264 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
1265 /// // Deferred initialization:
1266 /// values[0].write(1);
1267 /// values[1].write(2);
1268 /// values[2].write(3);
1269 /// let values = unsafe { values.assume_init() };
1270 ///
1271 /// assert_eq!(*values, [1, 2, 3])
1272 /// ```
1273 #[stable(feature = "new_uninit", since = "1.82.0")]
1274 #[inline]
1275 pub unsafe fn assume_init(self) -> Box<[T], A> {
1276 let (raw, alloc) = Box::into_raw_with_allocator(self);
1277 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
1278 }
1279}
1280
1281impl<T: ?Sized> Box<T> {
1282 /// Constructs a box from a raw pointer.
1283 ///
1284 /// After calling this function, the raw pointer is owned by the
1285 /// resulting `Box`. Specifically, the `Box` destructor will call
1286 /// the destructor of `T` and free the allocated memory. For this
1287 /// to be safe, the memory must have been allocated in accordance
1288 /// with the [memory layout] used by `Box` .
1289 ///
1290 /// # Safety
1291 ///
1292 /// This function is unsafe because improper use may lead to
1293 /// memory problems. For example, a double-free may occur if the
1294 /// function is called twice on the same raw pointer.
1295 ///
1296 /// The raw pointer must point to a block of memory allocated by the global allocator.
1297 ///
1298 /// The safety conditions are described in the [memory layout] section.
1299 /// Note that the [considerations for unsafe code] apply to all `Box<T>` values.
1300 ///
1301 /// # Examples
1302 ///
1303 /// Recreate a `Box` which was previously converted to a raw pointer
1304 /// using [`Box::into_raw`]:
1305 /// ```
1306 /// let x = Box::new(5);
1307 /// let ptr = Box::into_raw(x);
1308 /// let x = unsafe { Box::from_raw(ptr) };
1309 /// ```
1310 /// Manually create a `Box` from scratch by using the global allocator:
1311 /// ```
1312 /// use std::alloc::{alloc, Layout};
1313 ///
1314 /// unsafe {
1315 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
1316 /// // In general .write is required to avoid attempting to destruct
1317 /// // the (uninitialized) previous contents of `ptr`, though for this
1318 /// // simple example `*ptr = 5` would have worked as well.
1319 /// ptr.write(5);
1320 /// let x = Box::from_raw(ptr);
1321 /// }
1322 /// ```
1323 ///
1324 /// [memory layout]: self#memory-layout
1325 /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1326 #[stable(feature = "box_raw", since = "1.4.0")]
1327 #[inline]
1328 #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
1329 pub unsafe fn from_raw(raw: *mut T) -> Self {
1330 unsafe { Self::from_raw_in(raw, Global) }
1331 }
1332
1333 /// Constructs a box from a `NonNull` pointer.
1334 ///
1335 /// After calling this function, the `NonNull` pointer is owned by
1336 /// the resulting `Box`. Specifically, the `Box` destructor will call
1337 /// the destructor of `T` and free the allocated memory. For this
1338 /// to be safe, the memory must have been allocated in accordance
1339 /// with the [memory layout] used by `Box` .
1340 ///
1341 /// # Safety
1342 ///
1343 /// This function is unsafe because improper use may lead to
1344 /// memory problems. For example, a double-free may occur if the
1345 /// function is called twice on the same `NonNull` pointer.
1346 ///
1347 /// The non-null pointer must point to a block of memory allocated by the global allocator.
1348 ///
1349 /// The safety conditions are described in the [memory layout] section.
1350 /// Note that the [considerations for unsafe code] apply to all `Box<T>` values.
1351 ///
1352 /// # Examples
1353 ///
1354 /// Recreate a `Box` which was previously converted to a `NonNull`
1355 /// pointer using [`Box::into_non_null`]:
1356 /// ```
1357 /// let x = Box::new(5);
1358 /// let non_null = Box::into_non_null(x);
1359 /// let x = unsafe { Box::from_non_null(non_null) };
1360 /// ```
1361 /// Manually create a `Box` from scratch by using the global allocator:
1362 /// ```
1363 /// use std::alloc::{alloc, Layout};
1364 /// use std::ptr::NonNull;
1365 ///
1366 /// unsafe {
1367 /// let non_null = NonNull::new(alloc(Layout::new::<i32>()).cast::<i32>())
1368 /// .expect("alloc should have successfully allocated memory");
1369 /// // In general .write is required to avoid attempting to destruct
1370 /// // the (uninitialized) previous contents of `non_null`.
1371 /// non_null.write(5);
1372 /// let x = Box::from_non_null(non_null);
1373 /// }
1374 /// ```
1375 ///
1376 /// [memory layout]: self#memory-layout
1377 /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1378 #[stable(feature = "box_vec_non_null", since = "CURRENT_RUSTC_VERSION")]
1379 #[inline]
1380 #[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"]
1381 pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self {
1382 unsafe { Self::from_raw(ptr.as_ptr()) }
1383 }
1384
1385 /// Consumes the `Box`, returning a wrapped raw pointer.
1386 ///
1387 /// The pointer will be properly aligned and non-null.
1388 ///
1389 /// After calling this function, the caller is responsible for the
1390 /// memory previously managed by the `Box`. In particular, the
1391 /// caller should properly destroy `T` and release the memory, taking
1392 /// into account the [memory layout] used by `Box`. The easiest way to
1393 /// do this is to convert the raw pointer back into a `Box` with the
1394 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1395 /// the cleanup.
1396 ///
1397 /// Note: this is an associated function, which means that you have
1398 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1399 /// is so that there is no conflict with a method on the inner type.
1400 ///
1401 /// # Examples
1402 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1403 /// for automatic cleanup:
1404 /// ```
1405 /// let x = Box::new(String::from("Hello"));
1406 /// let ptr = Box::into_raw(x);
1407 /// let x = unsafe { Box::from_raw(ptr) };
1408 /// ```
1409 /// Manual cleanup by explicitly running the destructor and deallocating
1410 /// the memory:
1411 /// ```
1412 /// use std::alloc::{dealloc, Layout};
1413 /// use std::ptr;
1414 ///
1415 /// let x = Box::new(String::from("Hello"));
1416 /// let ptr = Box::into_raw(x);
1417 /// unsafe {
1418 /// ptr::drop_in_place(ptr);
1419 /// dealloc(ptr as *mut u8, Layout::new::<String>());
1420 /// }
1421 /// ```
1422 /// Note: This is equivalent to the following:
1423 /// ```
1424 /// let x = Box::new(String::from("Hello"));
1425 /// let ptr = Box::into_raw(x);
1426 /// unsafe {
1427 /// drop(Box::from_raw(ptr));
1428 /// }
1429 /// ```
1430 ///
1431 /// [memory layout]: self#memory-layout
1432 #[must_use = "losing the pointer will leak memory"]
1433 #[stable(feature = "box_raw", since = "1.4.0")]
1434 #[inline]
1435 pub fn into_raw(b: Self) -> *mut T {
1436 // Avoid `into_raw_with_allocator` as that interacts poorly with Miri's Stacked Borrows.
1437 let mut b = mem::ManuallyDrop::new(b);
1438 // We need to give Miri (specifically, Stacked Borrows) a chance to recognize this as a
1439 // safe-to-raw-pointer cast. To achieve this, we first create a mutable reference, and then
1440 // cast that to a raw pointer -- this cast is recognized by the aliasing model and leads to
1441 // a suitable retag.
1442 // It would be wrong for `into_raw_with_allocator` to do the same as that would induce
1443 // uniqueness assumptions (from the `&mut`) that we only want with the default allocator.
1444 (&mut **b) as *mut T
1445 }
1446
1447 /// Consumes the `Box`, returning a wrapped `NonNull` pointer.
1448 ///
1449 /// The pointer will be properly aligned.
1450 ///
1451 /// After calling this function, the caller is responsible for the
1452 /// memory previously managed by the `Box`. In particular, the
1453 /// caller should properly destroy `T` and release the memory, taking
1454 /// into account the [memory layout] used by `Box`. The easiest way to
1455 /// do this is to convert the `NonNull` pointer back into a `Box` with the
1456 /// [`Box::from_non_null`] function, allowing the `Box` destructor to
1457 /// perform the cleanup.
1458 ///
1459 /// Note: this is an associated function, which means that you have
1460 /// to call it as `Box::into_non_null(b)` instead of `b.into_non_null()`.
1461 /// This is so that there is no conflict with a method on the inner type.
1462 ///
1463 /// # Examples
1464 /// Converting the `NonNull` pointer back into a `Box` with [`Box::from_non_null`]
1465 /// for automatic cleanup:
1466 /// ```
1467 /// let x = Box::new(String::from("Hello"));
1468 /// let non_null = Box::into_non_null(x);
1469 /// let x = unsafe { Box::from_non_null(non_null) };
1470 /// ```
1471 /// Manual cleanup by explicitly running the destructor and deallocating
1472 /// the memory:
1473 /// ```
1474 /// use std::alloc::{dealloc, Layout};
1475 ///
1476 /// let x = Box::new(String::from("Hello"));
1477 /// let non_null = Box::into_non_null(x);
1478 /// unsafe {
1479 /// non_null.drop_in_place();
1480 /// dealloc(non_null.as_ptr().cast::<u8>(), Layout::new::<String>());
1481 /// }
1482 /// ```
1483 /// Note: This is equivalent to the following:
1484 /// ```
1485 /// let x = Box::new(String::from("Hello"));
1486 /// let non_null = Box::into_non_null(x);
1487 /// unsafe {
1488 /// drop(Box::from_non_null(non_null));
1489 /// }
1490 /// ```
1491 ///
1492 /// [memory layout]: self#memory-layout
1493 #[must_use = "losing the pointer will leak memory"]
1494 #[stable(feature = "box_vec_non_null", since = "CURRENT_RUSTC_VERSION")]
1495 #[inline]
1496 pub fn into_non_null(b: Self) -> NonNull<T> {
1497 // As of August 2026, we cannot utilize `Box::leak`
1498 // because whether or not you can reconstruct the `Box`
1499 // later using `Box::from_raw` or `Box::from_non_null` is
1500 // an open question.
1501 // SAFETY: `Box` is guaranteed to be non-null.
1502 unsafe { NonNull::new_unchecked(Self::into_raw(b)) }
1503 }
1504}
1505
1506impl<T: ?Sized, A: Allocator> Box<T, A> {
1507 /// Constructs a box from a raw pointer in the given allocator.
1508 ///
1509 /// After calling this function, the raw pointer is owned by the
1510 /// resulting `Box`. Specifically, the `Box` destructor will call
1511 /// the destructor of `T` and free the allocated memory. For this
1512 /// to be safe, the memory must have been allocated in accordance
1513 /// with the [memory layout] used by `Box` .
1514 ///
1515 /// # Safety
1516 ///
1517 /// This function is unsafe because improper use may lead to
1518 /// memory problems. For example, a double-free may occur if the
1519 /// function is called twice on the same raw pointer.
1520 ///
1521 /// The raw pointer must point to a block of memory allocated by `alloc`.
1522 ///
1523 /// The safety conditions are described in the [memory layout] section.
1524 /// Note that the [considerations for unsafe code] apply to all `Box<T, A>` values.
1525 ///
1526 /// # Examples
1527 ///
1528 /// Recreate a `Box` which was previously converted to a raw pointer
1529 /// using [`Box::into_raw_with_allocator`]:
1530 /// ```
1531 /// #![feature(allocator_api)]
1532 ///
1533 /// use std::alloc::System;
1534 ///
1535 /// let x = Box::new_in(5, System);
1536 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1537 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1538 /// ```
1539 /// Manually create a `Box` from scratch by using the system allocator:
1540 /// ```
1541 /// #![feature(allocator_api, slice_ptr_get)]
1542 ///
1543 /// use std::alloc::{Allocator, Layout, System};
1544 ///
1545 /// unsafe {
1546 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1547 /// // In general .write is required to avoid attempting to destruct
1548 /// // the (uninitialized) previous contents of `ptr`, though for this
1549 /// // simple example `*ptr = 5` would have worked as well.
1550 /// ptr.write(5);
1551 /// let x = Box::from_raw_in(ptr, System);
1552 /// }
1553 /// # Ok::<(), std::alloc::AllocError>(())
1554 /// ```
1555 ///
1556 /// [memory layout]: self#memory-layout
1557 /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1558 #[unstable(feature = "allocator_api", issue = "32838")]
1559 #[inline]
1560 pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1561 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1562 }
1563
1564 /// Constructs a box from a `NonNull` pointer in the given allocator.
1565 ///
1566 /// After calling this function, the `NonNull` pointer is owned by
1567 /// the resulting `Box`. Specifically, the `Box` destructor will call
1568 /// the destructor of `T` and free the allocated memory. For this
1569 /// to be safe, the memory must have been allocated in accordance
1570 /// with the [memory layout] used by `Box` .
1571 ///
1572 /// # Safety
1573 ///
1574 /// This function is unsafe because improper use may lead to
1575 /// memory problems. For example, a double-free may occur if the
1576 /// function is called twice on the same raw pointer.
1577 ///
1578 /// The non-null pointer must point to a block of memory allocated by `alloc`.
1579 ///
1580 /// The safety conditions are described in the [memory layout] section.
1581 /// Note that the [considerations for unsafe code] apply to all `Box<T, A>` values.
1582 ///
1583 /// # Examples
1584 ///
1585 /// Recreate a `Box` which was previously converted to a `NonNull` pointer
1586 /// using [`Box::into_non_null_with_allocator`]:
1587 /// ```
1588 /// #![feature(allocator_api)]
1589 ///
1590 /// use std::alloc::System;
1591 ///
1592 /// let x = Box::new_in(5, System);
1593 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1594 /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1595 /// ```
1596 /// Manually create a `Box` from scratch by using the system allocator:
1597 /// ```
1598 /// #![feature(allocator_api)]
1599 ///
1600 /// use std::alloc::{Allocator, Layout, System};
1601 ///
1602 /// unsafe {
1603 /// let non_null = System.allocate(Layout::new::<i32>())?.cast::<i32>();
1604 /// // In general .write is required to avoid attempting to destruct
1605 /// // the (uninitialized) previous contents of `non_null`.
1606 /// non_null.write(5);
1607 /// let x = Box::from_non_null_in(non_null, System);
1608 /// }
1609 /// # Ok::<(), std::alloc::AllocError>(())
1610 /// ```
1611 ///
1612 /// [memory layout]: self#memory-layout
1613 /// [considerations for unsafe code]: self#considerations-for-unsafe-code
1614 #[unstable(feature = "allocator_api", issue = "32838")]
1615 #[inline]
1616 pub unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Self {
1617 // SAFETY: guaranteed by the caller.
1618 unsafe { Box::from_raw_in(raw.as_ptr(), alloc) }
1619 }
1620
1621 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1622 ///
1623 /// The pointer will be properly aligned and non-null.
1624 ///
1625 /// After calling this function, the caller is responsible for the
1626 /// memory previously managed by the `Box`. In particular, the
1627 /// caller should properly destroy `T` and release the memory, taking
1628 /// into account the [memory layout] used by `Box`. The easiest way to
1629 /// do this is to convert the raw pointer back into a `Box` with the
1630 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1631 /// the cleanup.
1632 ///
1633 /// Note: this is an associated function, which means that you have
1634 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1635 /// is so that there is no conflict with a method on the inner type.
1636 ///
1637 /// # Examples
1638 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1639 /// for automatic cleanup:
1640 /// ```
1641 /// #![feature(allocator_api)]
1642 ///
1643 /// use std::alloc::System;
1644 ///
1645 /// let x = Box::new_in(String::from("Hello"), System);
1646 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1647 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1648 /// ```
1649 /// Manual cleanup by explicitly running the destructor and deallocating
1650 /// the memory:
1651 /// ```
1652 /// #![feature(allocator_api)]
1653 ///
1654 /// use std::alloc::{Allocator, Layout, System};
1655 /// use std::ptr::{self, NonNull};
1656 ///
1657 /// let x = Box::new_in(String::from("Hello"), System);
1658 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1659 /// unsafe {
1660 /// ptr::drop_in_place(ptr);
1661 /// let non_null = NonNull::new_unchecked(ptr);
1662 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1663 /// }
1664 /// ```
1665 ///
1666 /// [memory layout]: self#memory-layout
1667 #[must_use = "losing the pointer will leak memory"]
1668 #[unstable(feature = "allocator_api", issue = "32838")]
1669 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1670 #[inline]
1671 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1672 let mut b = mem::ManuallyDrop::new(b);
1673 // We carefully get the raw pointer out in a way that Miri's aliasing model understands what
1674 // is happening: using the primitive "deref" of `Box`. In case `A` is *not* `Global`, we
1675 // want *no* aliasing requirements here!
1676 // In case `A` *is* `Global`, this does not quite have the right behavior; `into_raw`
1677 // works around that.
1678 let ptr = &raw mut **b;
1679 let alloc = unsafe { ptr::read(&b.1) };
1680 (ptr, alloc)
1681 }
1682
1683 /// Consumes the `Box`, returning a wrapped `NonNull` pointer and the allocator.
1684 ///
1685 /// The pointer will be properly aligned.
1686 ///
1687 /// After calling this function, the caller is responsible for the
1688 /// memory previously managed by the `Box`. In particular, the
1689 /// caller should properly destroy `T` and release the memory, taking
1690 /// into account the [memory layout] used by `Box`. The easiest way to
1691 /// do this is to convert the `NonNull` pointer back into a `Box` with the
1692 /// [`Box::from_non_null_in`] function, allowing the `Box` destructor to
1693 /// perform the cleanup.
1694 ///
1695 /// Note: this is an associated function, which means that you have
1696 /// to call it as `Box::into_non_null_with_allocator(b)` instead of
1697 /// `b.into_non_null_with_allocator()`. This is so that there is no
1698 /// conflict with a method on the inner type.
1699 ///
1700 /// # Examples
1701 /// Converting the `NonNull` pointer back into a `Box` with
1702 /// [`Box::from_non_null_in`] for automatic cleanup:
1703 /// ```
1704 /// #![feature(allocator_api)]
1705 ///
1706 /// use std::alloc::System;
1707 ///
1708 /// let x = Box::new_in(String::from("Hello"), System);
1709 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1710 /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1711 /// ```
1712 /// Manual cleanup by explicitly running the destructor and deallocating
1713 /// the memory:
1714 /// ```
1715 /// #![feature(allocator_api)]
1716 ///
1717 /// use std::alloc::{Allocator, Layout, System};
1718 ///
1719 /// let x = Box::new_in(String::from("Hello"), System);
1720 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1721 /// unsafe {
1722 /// non_null.drop_in_place();
1723 /// alloc.deallocate(non_null.cast::<u8>(), Layout::new::<String>());
1724 /// }
1725 /// ```
1726 ///
1727 /// [memory layout]: self#memory-layout
1728 #[must_use = "losing the pointer will leak memory"]
1729 #[unstable(feature = "allocator_api", issue = "32838")]
1730 #[inline]
1731 pub fn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A) {
1732 let (ptr, alloc) = Box::into_raw_with_allocator(b);
1733 // SAFETY: `Box` is guaranteed to be non-null.
1734 unsafe { (NonNull::new_unchecked(ptr), alloc) }
1735 }
1736
1737 #[unstable(
1738 feature = "ptr_internals",
1739 issue = "none",
1740 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1741 )]
1742 #[inline]
1743 #[doc(hidden)]
1744 pub fn into_unique(b: Self) -> (Unique<T>, A) {
1745 let (ptr, alloc) = Box::into_raw_with_allocator(b);
1746 unsafe { (Unique::from(&mut *ptr), alloc) }
1747 }
1748
1749 /// Returns a raw mutable pointer to the `Box`'s contents.
1750 ///
1751 /// The caller must ensure that the `Box` outlives the pointer this
1752 /// function returns, or else it will end up dangling.
1753 ///
1754 /// This method guarantees that for the purpose of the aliasing model, this method
1755 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1756 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], and [`as_non_null`].
1757 /// Note that calling other methods that materialize references to the memory
1758 /// may still invalidate this pointer.
1759 /// See the example below for how this guarantee can be used.
1760 ///
1761 /// # Examples
1762 ///
1763 /// Due to the aliasing guarantee, the following code is legal:
1764 ///
1765 /// ```rust
1766 /// unsafe {
1767 /// let mut b = Box::new(0);
1768 /// let ptr1 = Box::as_mut_ptr(&mut b);
1769 /// ptr1.write(1);
1770 /// let ptr2 = Box::as_mut_ptr(&mut b);
1771 /// ptr2.write(2);
1772 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1773 /// ptr1.write(3);
1774 /// }
1775 /// ```
1776 ///
1777 /// [`as_mut_ptr`]: Self::as_mut_ptr
1778 /// [`as_ptr`]: Self::as_ptr
1779 /// [`as_non_null`]: Self::as_non_null
1780 #[must_use]
1781 #[stable(feature = "box_as_ptr", since = "1.98.0")]
1782 #[rustc_never_returns_null_ptr]
1783 #[rustc_as_ptr]
1784 #[inline]
1785 pub fn as_mut_ptr(b: &mut Self) -> *mut T {
1786 // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1787 // any references.
1788 &raw mut **b
1789 }
1790
1791 /// Returns a raw pointer to the `Box`'s contents.
1792 ///
1793 /// The caller must ensure that the `Box` outlives the pointer this
1794 /// function returns, or else it will end up dangling.
1795 ///
1796 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1797 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1798 /// derived from it. If you need to mutate the contents of the `Box`, use [`as_mut_ptr`].
1799 ///
1800 /// This method guarantees that for the purpose of the aliasing model, this method
1801 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1802 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], and [`as_non_null`].
1803 /// Note that calling other methods that materialize mutable references to the memory,
1804 /// as well as writing to this memory, may still invalidate this pointer.
1805 /// See the example below for how this guarantee can be used.
1806 ///
1807 /// # Examples
1808 ///
1809 /// Due to the aliasing guarantee, the following code is legal:
1810 ///
1811 /// ```rust
1812 /// unsafe {
1813 /// let mut v = Box::new(0);
1814 /// let ptr1 = Box::as_ptr(&v);
1815 /// let ptr2 = Box::as_mut_ptr(&mut v);
1816 /// let _val = ptr2.read();
1817 /// // No write to this memory has happened yet, so `ptr1` is still valid.
1818 /// let _val = ptr1.read();
1819 /// // However, once we do a write...
1820 /// ptr2.write(1);
1821 /// // ... `ptr1` is no longer valid.
1822 /// // This would be UB: let _val = ptr1.read();
1823 /// }
1824 /// ```
1825 ///
1826 /// [`as_mut_ptr`]: Self::as_mut_ptr
1827 /// [`as_ptr`]: Self::as_ptr
1828 /// [`as_non_null`]: Self::as_non_null
1829 #[must_use]
1830 #[stable(feature = "box_as_ptr", since = "1.98.0")]
1831 #[rustc_never_returns_null_ptr]
1832 #[rustc_as_ptr]
1833 #[inline]
1834 pub fn as_ptr(b: &Self) -> *const T {
1835 // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1836 // any references.
1837 &raw const **b
1838 }
1839
1840 /// Returns a `NonNull` pointer to the `Box`'s contents.
1841 ///
1842 /// The caller must ensure that the `Box` outlives the pointer this
1843 /// function returns, or else it will end up dangling.
1844 ///
1845 /// This method guarantees that for the purpose of the aliasing model, this method
1846 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1847 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`], and [`as_non_null`].
1848 /// Note that calling other methods that materialize references to the memory
1849 /// may still invalidate this pointer.
1850 /// See the example below for how this guarantee can be used.
1851 ///
1852 /// # Examples
1853 ///
1854 /// Due to the aliasing guarantee, the following code is legal:
1855 ///
1856 /// ```rust
1857 /// #![feature(box_as_non_null)]
1858 ///
1859 /// unsafe {
1860 /// let mut b = Box::new(0);
1861 /// let ptr1 = Box::as_non_null(&mut b);
1862 /// ptr1.write(1);
1863 /// let ptr2 = Box::as_non_null(&mut b);
1864 /// ptr2.write(2);
1865 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1866 /// ptr1.write(3);
1867 /// }
1868 /// ```
1869 ///
1870 /// [`as_mut_ptr`]: Self::as_mut_ptr
1871 /// [`as_ptr`]: Self::as_ptr
1872 /// [`as_non_null`]: Self::as_non_null
1873 #[must_use]
1874 #[unstable(feature = "box_as_non_null", issue = "157345")]
1875 #[rustc_as_ptr]
1876 #[inline]
1877 pub fn as_non_null(b: &mut Self) -> NonNull<T> {
1878 // SAFETY: `Box` is guaranteed to be non-null.
1879 unsafe { NonNull::new_unchecked(Self::as_mut_ptr(b)) }
1880 }
1881
1882 /// Returns a reference to the underlying allocator.
1883 ///
1884 /// Note: this is an associated function, which means that you have
1885 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1886 /// is so that there is no conflict with a method on the inner type.
1887 #[unstable(feature = "allocator_api", issue = "32838")]
1888 #[inline]
1889 pub fn allocator(b: &Self) -> &A {
1890 &b.1
1891 }
1892
1893 /// Consumes and leaks the `Box`, returning a mutable reference,
1894 /// `&'a mut T`.
1895 ///
1896 /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
1897 /// has only static references, or none at all, then this may be chosen to be
1898 /// `'static`.
1899 ///
1900 /// This function is mainly useful for data that lives for the remainder of the program's life,
1901 /// i.e., memory that is meant to leak. Reconstructing ("unleaking") a `Box` from the mutable
1902 /// reference returned here (e.g. via [`Box::from_raw`]) is a grey area (meaning it is possible
1903 /// under specific circumstances but many seemingly harmless ways of doing it are undefined
1904 /// behavior) and should be avoided. If the memory should eventually be freed, prefer to use
1905 /// [`Box::into_raw`] or [`Box::into_non_null`] instead.
1906 ///
1907 /// Note: this is an associated function, which means that you have
1908 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1909 /// is so that there is no conflict with a method on the inner type.
1910 ///
1911 /// # Examples
1912 ///
1913 /// Simple usage:
1914 ///
1915 /// ```
1916 /// let x = Box::new(41);
1917 /// let static_ref: &'static mut usize = Box::leak(x);
1918 /// *static_ref += 1;
1919 /// assert_eq!(*static_ref, 42);
1920 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1921 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1922 /// # drop(unsafe { Box::from_raw(static_ref) });
1923 /// ```
1924 ///
1925 /// Unsized data:
1926 ///
1927 /// ```
1928 /// let x = vec![1, 2, 3].into_boxed_slice();
1929 /// let static_ref = Box::leak(x);
1930 /// static_ref[0] = 4;
1931 /// assert_eq!(*static_ref, [4, 2, 3]);
1932 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1933 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1934 /// # drop(unsafe { Box::from_raw(static_ref) });
1935 /// ```
1936 #[stable(feature = "box_leak", since = "1.26.0")]
1937 #[inline]
1938 pub fn leak<'a>(b: Self) -> &'a mut T
1939 where
1940 A: 'a,
1941 {
1942 let (ptr, alloc) = Box::into_raw_with_allocator(b);
1943 mem::forget(alloc);
1944 unsafe { &mut *ptr }
1945 }
1946
1947 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1948 /// `*boxed` will be pinned in memory and unable to be moved.
1949 ///
1950 /// This conversion does not allocate on the heap and happens in place.
1951 ///
1952 /// This is also available via [`From`].
1953 ///
1954 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1955 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1956 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1957 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1958 ///
1959 /// # Notes
1960 ///
1961 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1962 /// as it'll introduce an ambiguity when calling `Pin::from`.
1963 /// A demonstration of such a poor impl is shown below.
1964 ///
1965 /// ```compile_fail
1966 /// # use std::pin::Pin;
1967 /// struct Foo; // A type defined in this crate.
1968 /// impl From<Box<()>> for Pin<Foo> {
1969 /// fn from(_: Box<()>) -> Pin<Foo> {
1970 /// Pin::new(Foo)
1971 /// }
1972 /// }
1973 ///
1974 /// let foo = Box::new(());
1975 /// let bar = Pin::from(foo);
1976 /// ```
1977 #[stable(feature = "box_into_pin", since = "1.63.0")]
1978 pub fn into_pin(boxed: Self) -> Pin<Self>
1979 where
1980 A: 'static,
1981 {
1982 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1983 // when `T: !Unpin`, so it's safe to pin it directly without any
1984 // additional requirements.
1985 unsafe { Pin::new_unchecked(boxed) }
1986 }
1987}
1988
1989#[stable(feature = "rust1", since = "1.0.0")]
1990unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1991 #[inline]
1992 fn drop(&mut self) {
1993 // the T in the Box is dropped by the compiler before the destructor is run
1994
1995 let ptr = self.0;
1996
1997 unsafe {
1998 let layout = Layout::for_value_raw(ptr.as_ptr());
1999 if layout.size() != 0 {
2000 self.1.deallocate(From::from(ptr.cast()), layout);
2001 }
2002 }
2003 }
2004}
2005
2006#[cfg(not(no_global_oom_handling))]
2007#[stable(feature = "rust1", since = "1.0.0")]
2008impl<T: Default> Default for Box<T> {
2009 /// Creates a `Box<T>`, with the `Default` value for `T`.
2010 #[inline]
2011 fn default() -> Self {
2012 let mut x: Box<mem::MaybeUninit<T>> = Box::new_uninit();
2013 unsafe {
2014 // SAFETY: `x` is valid for writing and has the same layout as `T`.
2015 // If `T::default()` panics, dropping `x` will just deallocate the Box as `MaybeUninit<T>`
2016 // does not have a destructor.
2017 //
2018 // We use `ptr::write` as `MaybeUninit::write` creates
2019 // extra stack copies of `T` in debug mode.
2020 //
2021 // See https://github.com/rust-lang/rust/issues/136043 for more context.
2022 ptr::write(&raw mut *x as *mut T, T::default());
2023 // SAFETY: `x` was just initialized above.
2024 x.assume_init()
2025 }
2026 }
2027}
2028
2029#[cfg(not(no_global_oom_handling))]
2030#[stable(feature = "rust1", since = "1.0.0")]
2031impl<T> Default for Box<[T]> {
2032 /// Creates an empty `[T]` inside a `Box`.
2033 #[inline]
2034 fn default() -> Self {
2035 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
2036 Box(ptr, Global)
2037 }
2038}
2039
2040#[cfg(not(no_global_oom_handling))]
2041#[stable(feature = "default_box_extra", since = "1.17.0")]
2042impl Default for Box<str> {
2043 #[inline]
2044 fn default() -> Self {
2045 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
2046 let ptr: Unique<str> = unsafe {
2047 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
2048 Unique::new_unchecked(bytes.as_ptr() as *mut str)
2049 };
2050 Box(ptr, Global)
2051 }
2052}
2053
2054#[cfg(not(no_global_oom_handling))]
2055#[stable(feature = "pin_default_impls", since = "1.91.0")]
2056impl<T> Default for Pin<Box<T>>
2057where
2058 T: ?Sized,
2059 Box<T>: Default,
2060{
2061 #[inline]
2062 fn default() -> Self {
2063 Box::into_pin(Box::<T>::default())
2064 }
2065}
2066
2067#[cfg(not(no_global_oom_handling))]
2068#[stable(feature = "rust1", since = "1.0.0")]
2069impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
2070 /// Returns a new box with a `clone()` of this box's contents.
2071 ///
2072 /// # Examples
2073 ///
2074 /// ```
2075 /// let x = Box::new(5);
2076 /// let y = x.clone();
2077 ///
2078 /// // The value is the same
2079 /// assert_eq!(x, y);
2080 ///
2081 /// // But they are unique objects
2082 /// assert_ne!(&*x as *const i32, &*y as *const i32);
2083 /// ```
2084 #[inline]
2085 fn clone(&self) -> Self {
2086 // Pre-allocate memory to allow writing the cloned value directly.
2087 let mut boxed = Self::new_uninit_in(self.1.clone());
2088 unsafe {
2089 (**self).clone_to_uninit(boxed.as_mut_ptr().cast());
2090 boxed.assume_init()
2091 }
2092 }
2093
2094 /// Copies `source`'s contents into `self` without creating a new allocation.
2095 ///
2096 /// # Examples
2097 ///
2098 /// ```
2099 /// let x = Box::new(5);
2100 /// let mut y = Box::new(10);
2101 /// let yp: *const i32 = &*y;
2102 ///
2103 /// y.clone_from(&x);
2104 ///
2105 /// // The value is the same
2106 /// assert_eq!(x, y);
2107 ///
2108 /// // And no allocation occurred
2109 /// assert_eq!(yp, &*y);
2110 /// ```
2111 #[inline]
2112 fn clone_from(&mut self, source: &Self) {
2113 (**self).clone_from(&(**source));
2114 }
2115}
2116
2117#[cfg(not(no_global_oom_handling))]
2118#[stable(feature = "box_slice_clone", since = "1.3.0")]
2119impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2120 fn clone(&self) -> Self {
2121 let alloc = Box::allocator(self).clone();
2122 self.to_vec_in(alloc).into_boxed_slice()
2123 }
2124
2125 /// Copies `source`'s contents into `self` without creating a new allocation,
2126 /// so long as the two are of the same length.
2127 ///
2128 /// # Examples
2129 ///
2130 /// ```
2131 /// let x = Box::new([5, 6, 7]);
2132 /// let mut y = Box::new([8, 9, 10]);
2133 /// let yp: *const [i32] = &*y;
2134 ///
2135 /// y.clone_from(&x);
2136 ///
2137 /// // The value is the same
2138 /// assert_eq!(x, y);
2139 ///
2140 /// // And no allocation occurred
2141 /// assert_eq!(yp, &*y);
2142 /// ```
2143 fn clone_from(&mut self, source: &Self) {
2144 if self.len() == source.len() {
2145 self.clone_from_slice(&source);
2146 } else {
2147 *self = source.clone();
2148 }
2149 }
2150}
2151
2152#[cfg(not(no_global_oom_handling))]
2153#[stable(feature = "box_slice_clone", since = "1.3.0")]
2154impl Clone for Box<str> {
2155 fn clone(&self) -> Self {
2156 // this makes a copy of the data
2157 let buf: Box<[u8]> = self.as_bytes().into();
2158 unsafe { from_boxed_utf8_unchecked(buf) }
2159 }
2160}
2161
2162#[stable(feature = "rust1", since = "1.0.0")]
2163impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
2164 #[inline]
2165 fn eq(&self, other: &Self) -> bool {
2166 PartialEq::eq(&**self, &**other)
2167 }
2168 #[inline]
2169 fn ne(&self, other: &Self) -> bool {
2170 PartialEq::ne(&**self, &**other)
2171 }
2172}
2173
2174#[stable(feature = "rust1", since = "1.0.0")]
2175impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
2176 #[inline]
2177 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2178 PartialOrd::partial_cmp(&**self, &**other)
2179 }
2180 #[inline]
2181 fn lt(&self, other: &Self) -> bool {
2182 PartialOrd::lt(&**self, &**other)
2183 }
2184 #[inline]
2185 fn le(&self, other: &Self) -> bool {
2186 PartialOrd::le(&**self, &**other)
2187 }
2188 #[inline]
2189 fn ge(&self, other: &Self) -> bool {
2190 PartialOrd::ge(&**self, &**other)
2191 }
2192 #[inline]
2193 fn gt(&self, other: &Self) -> bool {
2194 PartialOrd::gt(&**self, &**other)
2195 }
2196}
2197
2198#[stable(feature = "rust1", since = "1.0.0")]
2199impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
2200 #[inline]
2201 fn cmp(&self, other: &Self) -> Ordering {
2202 Ord::cmp(&**self, &**other)
2203 }
2204}
2205
2206#[stable(feature = "rust1", since = "1.0.0")]
2207impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
2208
2209#[stable(feature = "rust1", since = "1.0.0")]
2210impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
2211 fn hash<H: Hasher>(&self, state: &mut H) {
2212 (**self).hash(state);
2213 }
2214}
2215
2216#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
2217impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
2218 fn finish(&self) -> u64 {
2219 (**self).finish()
2220 }
2221 fn write(&mut self, bytes: &[u8]) {
2222 (**self).write(bytes)
2223 }
2224 fn write_u8(&mut self, i: u8) {
2225 (**self).write_u8(i)
2226 }
2227 fn write_u16(&mut self, i: u16) {
2228 (**self).write_u16(i)
2229 }
2230 fn write_u32(&mut self, i: u32) {
2231 (**self).write_u32(i)
2232 }
2233 fn write_u64(&mut self, i: u64) {
2234 (**self).write_u64(i)
2235 }
2236 fn write_u128(&mut self, i: u128) {
2237 (**self).write_u128(i)
2238 }
2239 fn write_usize(&mut self, i: usize) {
2240 (**self).write_usize(i)
2241 }
2242 fn write_i8(&mut self, i: i8) {
2243 (**self).write_i8(i)
2244 }
2245 fn write_i16(&mut self, i: i16) {
2246 (**self).write_i16(i)
2247 }
2248 fn write_i32(&mut self, i: i32) {
2249 (**self).write_i32(i)
2250 }
2251 fn write_i64(&mut self, i: i64) {
2252 (**self).write_i64(i)
2253 }
2254 fn write_i128(&mut self, i: i128) {
2255 (**self).write_i128(i)
2256 }
2257 fn write_isize(&mut self, i: isize) {
2258 (**self).write_isize(i)
2259 }
2260 fn write_length_prefix(&mut self, len: usize) {
2261 (**self).write_length_prefix(len)
2262 }
2263 fn write_str(&mut self, s: &str) {
2264 (**self).write_str(s)
2265 }
2266}
2267
2268#[stable(feature = "rust1", since = "1.0.0")]
2269impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
2270 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2271 fmt::Display::fmt(&**self, f)
2272 }
2273}
2274
2275#[stable(feature = "rust1", since = "1.0.0")]
2276impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
2277 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2278 fmt::Debug::fmt(&**self, f)
2279 }
2280}
2281
2282#[stable(feature = "rust1", since = "1.0.0")]
2283impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
2284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2285 // It's not possible to extract the inner Uniq directly from the Box,
2286 // instead we cast it to a *const which aliases the Unique
2287 let ptr: *const T = &**self;
2288 fmt::Pointer::fmt(&ptr, f)
2289 }
2290}
2291
2292#[stable(feature = "rust1", since = "1.0.0")]
2293impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
2294 type Target = T;
2295
2296 fn deref(&self) -> &T {
2297 &**self
2298 }
2299}
2300
2301#[stable(feature = "rust1", since = "1.0.0")]
2302impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
2303 fn deref_mut(&mut self) -> &mut T {
2304 &mut **self
2305 }
2306}
2307
2308#[unstable(feature = "deref_pure_trait", issue = "87121")]
2309unsafe impl<T: ?Sized, A: Allocator> DerefPure for Box<T, A> {}
2310
2311#[unstable(feature = "legacy_receiver_trait", issue = "none")]
2312impl<T: ?Sized, A: Allocator> LegacyReceiver for Box<T, A> {}
2313
2314#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2315impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
2316 type Output = <F as FnOnce<Args>>::Output;
2317
2318 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
2319 <F as FnOnce<Args>>::call_once(*self, args)
2320 }
2321}
2322
2323#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2324impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
2325 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
2326 <F as FnMut<Args>>::call_mut(self, args)
2327 }
2328}
2329
2330#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2331impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2332 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2333 <F as Fn<Args>>::call(self, args)
2334 }
2335}
2336
2337#[stable(feature = "async_closure", since = "1.85.0")]
2338impl<Args: Tuple, F: AsyncFnOnce<Args> + ?Sized, A: Allocator> AsyncFnOnce<Args> for Box<F, A> {
2339 type Output = F::Output;
2340 type CallOnceFuture = F::CallOnceFuture;
2341
2342 extern "rust-call" fn async_call_once(self, args: Args) -> Self::CallOnceFuture {
2343 F::async_call_once(*self, args)
2344 }
2345}
2346
2347#[stable(feature = "async_closure", since = "1.85.0")]
2348impl<Args: Tuple, F: AsyncFnMut<Args> + ?Sized, A: Allocator> AsyncFnMut<Args> for Box<F, A> {
2349 type CallRefFuture<'a>
2350 = F::CallRefFuture<'a>
2351 where
2352 Self: 'a;
2353
2354 extern "rust-call" fn async_call_mut(&mut self, args: Args) -> Self::CallRefFuture<'_> {
2355 F::async_call_mut(self, args)
2356 }
2357}
2358
2359#[stable(feature = "async_closure", since = "1.85.0")]
2360impl<Args: Tuple, F: AsyncFn<Args> + ?Sized, A: Allocator> AsyncFn<Args> for Box<F, A> {
2361 extern "rust-call" fn async_call(&self, args: Args) -> Self::CallRefFuture<'_> {
2362 F::async_call(self, args)
2363 }
2364}
2365
2366#[unstable(feature = "coerce_unsized", issue = "18598")]
2367impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2368
2369#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")]
2370unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Box<T, A> {}
2371
2372// It is quite crucial that we only allow the `Global` allocator here.
2373// Handling arbitrary custom allocators (which can affect the `Box` layout heavily!)
2374// would need a lot of codegen and interpreter adjustments.
2375#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2376impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2377
2378#[stable(feature = "box_borrow", since = "1.1.0")]
2379impl<T: ?Sized, A: Allocator> Borrow<T> for Box<T, A> {
2380 fn borrow(&self) -> &T {
2381 &**self
2382 }
2383}
2384
2385#[stable(feature = "box_borrow", since = "1.1.0")]
2386impl<T: ?Sized, A: Allocator> BorrowMut<T> for Box<T, A> {
2387 fn borrow_mut(&mut self) -> &mut T {
2388 &mut **self
2389 }
2390}
2391
2392#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2393impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2394 fn as_ref(&self) -> &T {
2395 &**self
2396 }
2397}
2398
2399#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2400impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2401 fn as_mut(&mut self) -> &mut T {
2402 &mut **self
2403 }
2404}
2405
2406/* Nota bene
2407 *
2408 * We could have chosen not to add this impl, and instead have written a
2409 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2410 * because Box<T> implements Unpin even when T does not, as a result of
2411 * this impl.
2412 *
2413 * We chose this API instead of the alternative for a few reasons:
2414 * - Logically, it is helpful to understand pinning in regard to the
2415 * memory region being pointed to. For this reason none of the
2416 * standard library pointer types support projecting through a pin
2417 * (Box<T> is the only pointer type in std for which this would be
2418 * safe.)
2419 * - It is in practice very useful to have Box<T> be unconditionally
2420 * Unpin because of trait objects, for which the structural auto
2421 * trait functionality does not apply (e.g., Box<dyn Foo> would
2422 * otherwise not be Unpin).
2423 *
2424 * Another type with the same semantics as Box but only a conditional
2425 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2426 * could have a method to project a Pin<T> from it.
2427 */
2428#[stable(feature = "pin", since = "1.33.0")]
2429impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> {}
2430
2431#[unstable(feature = "coroutine_trait", issue = "43122")]
2432impl<G: ?Sized + Coroutine<R> + Unpin, R, A: Allocator> Coroutine<R> for Box<G, A> {
2433 type Yield = G::Yield;
2434 type Return = G::Return;
2435
2436 fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2437 G::resume(Pin::new(&mut *self), arg)
2438 }
2439}
2440
2441#[unstable(feature = "coroutine_trait", issue = "43122")]
2442impl<G: ?Sized + Coroutine<R>, R, A: Allocator> Coroutine<R> for Pin<Box<G, A>>
2443where
2444 A: 'static,
2445{
2446 type Yield = G::Yield;
2447 type Return = G::Return;
2448
2449 fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2450 G::resume((*self).as_mut(), arg)
2451 }
2452}
2453
2454#[stable(feature = "futures_api", since = "1.36.0")]
2455impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A> {
2456 type Output = F::Output;
2457
2458 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2459 F::poll(Pin::new(&mut *self), cx)
2460 }
2461}
2462
2463#[stable(feature = "box_error", since = "1.8.0")]
2464impl<E: Error> Error for Box<E> {
2465 #[allow(deprecated)]
2466 fn cause(&self) -> Option<&dyn Error> {
2467 Error::cause(&**self)
2468 }
2469
2470 fn source(&self) -> Option<&(dyn Error + 'static)> {
2471 Error::source(&**self)
2472 }
2473
2474 fn provide<'b>(&'b self, request: &mut error::Request<'b>) {
2475 Error::provide(&**self, request);
2476 }
2477}
2478
2479#[unstable(feature = "allocator_api", issue = "32838")]
2480unsafe impl<T: ?Sized + Allocator, A: Allocator> Allocator for Box<T, A> {
2481 #[inline]
2482 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2483 (**self).allocate(layout)
2484 }
2485
2486 #[inline]
2487 fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
2488 (**self).allocate_zeroed(layout)
2489 }
2490
2491 #[inline]
2492 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
2493 // SAFETY: the safety contract must be upheld by the caller
2494 unsafe { (**self).deallocate(ptr, layout) }
2495 }
2496
2497 #[inline]
2498 unsafe fn grow(
2499 &self,
2500 ptr: NonNull<u8>,
2501 old_layout: Layout,
2502 new_layout: Layout,
2503 ) -> Result<NonNull<[u8]>, AllocError> {
2504 // SAFETY: the safety contract must be upheld by the caller
2505 unsafe { (**self).grow(ptr, old_layout, new_layout) }
2506 }
2507
2508 #[inline]
2509 unsafe fn grow_zeroed(
2510 &self,
2511 ptr: NonNull<u8>,
2512 old_layout: Layout,
2513 new_layout: Layout,
2514 ) -> Result<NonNull<[u8]>, AllocError> {
2515 // SAFETY: the safety contract must be upheld by the caller
2516 unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) }
2517 }
2518
2519 #[inline]
2520 unsafe fn shrink(
2521 &self,
2522 ptr: NonNull<u8>,
2523 old_layout: Layout,
2524 new_layout: Layout,
2525 ) -> Result<NonNull<[u8]>, AllocError> {
2526 // SAFETY: the safety contract must be upheld by the caller
2527 unsafe { (**self).shrink(ptr, old_layout, new_layout) }
2528 }
2529}