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