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