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