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