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