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