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