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