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