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 /// [`Layout`]: crate::Layout
1057 #[stable(feature = "box_raw", since = "1.4.0")]
1058 #[inline]
1059 #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
1060 pub unsafe fn from_raw(raw: *mut T) -> Self {
1061 unsafe { Self::from_raw_in(raw, Global) }
1062 }
1063
1064 /// Constructs a box from a `NonNull` pointer.
1065 ///
1066 /// After calling this function, the `NonNull` pointer is owned by
1067 /// the resulting `Box`. Specifically, the `Box` destructor will call
1068 /// the destructor of `T` and free the allocated memory. For this
1069 /// to be safe, the memory must have been allocated in accordance
1070 /// with the [memory layout] used by `Box` .
1071 ///
1072 /// # Safety
1073 ///
1074 /// This function is unsafe because improper use may lead to
1075 /// memory problems. For example, a double-free may occur if the
1076 /// function is called twice on the same `NonNull` pointer.
1077 ///
1078 /// The non-null pointer must point to a block of memory allocated by the global allocator.
1079 ///
1080 /// The safety conditions are described in the [memory layout] section.
1081 ///
1082 /// # Examples
1083 ///
1084 /// Recreate a `Box` which was previously converted to a `NonNull`
1085 /// pointer using [`Box::into_non_null`]:
1086 /// ```
1087 /// #![feature(box_vec_non_null)]
1088 ///
1089 /// let x = Box::new(5);
1090 /// let non_null = Box::into_non_null(x);
1091 /// let x = unsafe { Box::from_non_null(non_null) };
1092 /// ```
1093 /// Manually create a `Box` from scratch by using the global allocator:
1094 /// ```
1095 /// #![feature(box_vec_non_null)]
1096 ///
1097 /// use std::alloc::{alloc, Layout};
1098 /// use std::ptr::NonNull;
1099 ///
1100 /// unsafe {
1101 /// let non_null = NonNull::new(alloc(Layout::new::<i32>()).cast::<i32>())
1102 /// .expect("allocation failed");
1103 /// // In general .write is required to avoid attempting to destruct
1104 /// // the (uninitialized) previous contents of `non_null`.
1105 /// non_null.write(5);
1106 /// let x = Box::from_non_null(non_null);
1107 /// }
1108 /// ```
1109 ///
1110 /// [memory layout]: self#memory-layout
1111 /// [`Layout`]: crate::Layout
1112 #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")]
1113 #[inline]
1114 #[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"]
1115 pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self {
1116 unsafe { Self::from_raw(ptr.as_ptr()) }
1117 }
1118}
1119
1120impl<T: ?Sized, A: Allocator> Box<T, A> {
1121 /// Constructs a box from a raw pointer in the given allocator.
1122 ///
1123 /// After calling this function, the raw pointer is owned by the
1124 /// resulting `Box`. Specifically, the `Box` destructor will call
1125 /// the destructor of `T` and free the allocated memory. For this
1126 /// to be safe, the memory must have been allocated in accordance
1127 /// with the [memory layout] used by `Box` .
1128 ///
1129 /// # Safety
1130 ///
1131 /// This function is unsafe because improper use may lead to
1132 /// memory problems. For example, a double-free may occur if the
1133 /// function is called twice on the same raw pointer.
1134 ///
1135 /// The raw pointer must point to a block of memory allocated by `alloc`.
1136 ///
1137 /// # Examples
1138 ///
1139 /// Recreate a `Box` which was previously converted to a raw pointer
1140 /// using [`Box::into_raw_with_allocator`]:
1141 /// ```
1142 /// #![feature(allocator_api)]
1143 ///
1144 /// use std::alloc::System;
1145 ///
1146 /// let x = Box::new_in(5, System);
1147 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1148 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1149 /// ```
1150 /// Manually create a `Box` from scratch by using the system allocator:
1151 /// ```
1152 /// #![feature(allocator_api, slice_ptr_get)]
1153 ///
1154 /// use std::alloc::{Allocator, Layout, System};
1155 ///
1156 /// unsafe {
1157 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1158 /// // In general .write is required to avoid attempting to destruct
1159 /// // the (uninitialized) previous contents of `ptr`, though for this
1160 /// // simple example `*ptr = 5` would have worked as well.
1161 /// ptr.write(5);
1162 /// let x = Box::from_raw_in(ptr, System);
1163 /// }
1164 /// # Ok::<(), std::alloc::AllocError>(())
1165 /// ```
1166 ///
1167 /// [memory layout]: self#memory-layout
1168 /// [`Layout`]: crate::Layout
1169 #[unstable(feature = "allocator_api", issue = "32838")]
1170 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1171 #[inline]
1172 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1173 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1174 }
1175
1176 /// Constructs a box from a `NonNull` pointer in the given allocator.
1177 ///
1178 /// After calling this function, the `NonNull` pointer is owned by
1179 /// the resulting `Box`. Specifically, the `Box` destructor will call
1180 /// the destructor of `T` and free the allocated memory. For this
1181 /// to be safe, the memory must have been allocated in accordance
1182 /// with the [memory layout] used by `Box` .
1183 ///
1184 /// # Safety
1185 ///
1186 /// This function is unsafe because improper use may lead to
1187 /// memory problems. For example, a double-free may occur if the
1188 /// function is called twice on the same raw pointer.
1189 ///
1190 /// The non-null pointer must point to a block of memory allocated by `alloc`.
1191 ///
1192 /// # Examples
1193 ///
1194 /// Recreate a `Box` which was previously converted to a `NonNull` pointer
1195 /// using [`Box::into_non_null_with_allocator`]:
1196 /// ```
1197 /// #![feature(allocator_api, box_vec_non_null)]
1198 ///
1199 /// use std::alloc::System;
1200 ///
1201 /// let x = Box::new_in(5, System);
1202 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1203 /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1204 /// ```
1205 /// Manually create a `Box` from scratch by using the system allocator:
1206 /// ```
1207 /// #![feature(allocator_api, box_vec_non_null, slice_ptr_get)]
1208 ///
1209 /// use std::alloc::{Allocator, Layout, System};
1210 ///
1211 /// unsafe {
1212 /// let non_null = System.allocate(Layout::new::<i32>())?.cast::<i32>();
1213 /// // In general .write is required to avoid attempting to destruct
1214 /// // the (uninitialized) previous contents of `non_null`.
1215 /// non_null.write(5);
1216 /// let x = Box::from_non_null_in(non_null, System);
1217 /// }
1218 /// # Ok::<(), std::alloc::AllocError>(())
1219 /// ```
1220 ///
1221 /// [memory layout]: self#memory-layout
1222 /// [`Layout`]: crate::Layout
1223 #[unstable(feature = "allocator_api", issue = "32838")]
1224 // #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")]
1225 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1226 #[inline]
1227 pub const unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Self {
1228 // SAFETY: guaranteed by the caller.
1229 unsafe { Box::from_raw_in(raw.as_ptr(), alloc) }
1230 }
1231
1232 /// Consumes the `Box`, returning a wrapped raw pointer.
1233 ///
1234 /// The pointer will be properly aligned and non-null.
1235 ///
1236 /// After calling this function, the caller is responsible for the
1237 /// memory previously managed by the `Box`. In particular, the
1238 /// caller should properly destroy `T` and release the memory, taking
1239 /// into account the [memory layout] used by `Box`. The easiest way to
1240 /// do this is to convert the raw pointer back into a `Box` with the
1241 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1242 /// the cleanup.
1243 ///
1244 /// Note: this is an associated function, which means that you have
1245 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1246 /// is so that there is no conflict with a method on the inner type.
1247 ///
1248 /// # Examples
1249 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1250 /// for automatic cleanup:
1251 /// ```
1252 /// let x = Box::new(String::from("Hello"));
1253 /// let ptr = Box::into_raw(x);
1254 /// let x = unsafe { Box::from_raw(ptr) };
1255 /// ```
1256 /// Manual cleanup by explicitly running the destructor and deallocating
1257 /// the memory:
1258 /// ```
1259 /// use std::alloc::{dealloc, Layout};
1260 /// use std::ptr;
1261 ///
1262 /// let x = Box::new(String::from("Hello"));
1263 /// let ptr = Box::into_raw(x);
1264 /// unsafe {
1265 /// ptr::drop_in_place(ptr);
1266 /// dealloc(ptr as *mut u8, Layout::new::<String>());
1267 /// }
1268 /// ```
1269 /// Note: This is equivalent to the following:
1270 /// ```
1271 /// let x = Box::new(String::from("Hello"));
1272 /// let ptr = Box::into_raw(x);
1273 /// unsafe {
1274 /// drop(Box::from_raw(ptr));
1275 /// }
1276 /// ```
1277 ///
1278 /// [memory layout]: self#memory-layout
1279 #[must_use = "losing the pointer will leak memory"]
1280 #[stable(feature = "box_raw", since = "1.4.0")]
1281 #[inline]
1282 pub fn into_raw(b: Self) -> *mut T {
1283 // Make sure Miri realizes that we transition from a noalias pointer to a raw pointer here.
1284 unsafe { &raw mut *&mut *Self::into_raw_with_allocator(b).0 }
1285 }
1286
1287 /// Consumes the `Box`, returning a wrapped `NonNull` pointer.
1288 ///
1289 /// The pointer will be properly aligned.
1290 ///
1291 /// After calling this function, the caller is responsible for the
1292 /// memory previously managed by the `Box`. In particular, the
1293 /// caller should properly destroy `T` and release the memory, taking
1294 /// into account the [memory layout] used by `Box`. The easiest way to
1295 /// do this is to convert the `NonNull` pointer back into a `Box` with the
1296 /// [`Box::from_non_null`] function, allowing the `Box` destructor to
1297 /// perform the cleanup.
1298 ///
1299 /// Note: this is an associated function, which means that you have
1300 /// to call it as `Box::into_non_null(b)` instead of `b.into_non_null()`.
1301 /// This is so that there is no conflict with a method on the inner type.
1302 ///
1303 /// # Examples
1304 /// Converting the `NonNull` pointer back into a `Box` with [`Box::from_non_null`]
1305 /// for automatic cleanup:
1306 /// ```
1307 /// #![feature(box_vec_non_null)]
1308 ///
1309 /// let x = Box::new(String::from("Hello"));
1310 /// let non_null = Box::into_non_null(x);
1311 /// let x = unsafe { Box::from_non_null(non_null) };
1312 /// ```
1313 /// Manual cleanup by explicitly running the destructor and deallocating
1314 /// the memory:
1315 /// ```
1316 /// #![feature(box_vec_non_null)]
1317 ///
1318 /// use std::alloc::{dealloc, Layout};
1319 ///
1320 /// let x = Box::new(String::from("Hello"));
1321 /// let non_null = Box::into_non_null(x);
1322 /// unsafe {
1323 /// non_null.drop_in_place();
1324 /// dealloc(non_null.as_ptr().cast::<u8>(), Layout::new::<String>());
1325 /// }
1326 /// ```
1327 /// Note: This is equivalent to the following:
1328 /// ```
1329 /// #![feature(box_vec_non_null)]
1330 ///
1331 /// let x = Box::new(String::from("Hello"));
1332 /// let non_null = Box::into_non_null(x);
1333 /// unsafe {
1334 /// drop(Box::from_non_null(non_null));
1335 /// }
1336 /// ```
1337 ///
1338 /// [memory layout]: self#memory-layout
1339 #[must_use = "losing the pointer will leak memory"]
1340 #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")]
1341 #[inline]
1342 pub fn into_non_null(b: Self) -> NonNull<T> {
1343 // SAFETY: `Box` is guaranteed to be non-null.
1344 unsafe { NonNull::new_unchecked(Self::into_raw(b)) }
1345 }
1346
1347 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1348 ///
1349 /// The pointer will be properly aligned and non-null.
1350 ///
1351 /// After calling this function, the caller is responsible for the
1352 /// memory previously managed by the `Box`. In particular, the
1353 /// caller should properly destroy `T` and release the memory, taking
1354 /// into account the [memory layout] used by `Box`. The easiest way to
1355 /// do this is to convert the raw pointer back into a `Box` with the
1356 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1357 /// the cleanup.
1358 ///
1359 /// Note: this is an associated function, which means that you have
1360 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1361 /// is so that there is no conflict with a method on the inner type.
1362 ///
1363 /// # Examples
1364 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1365 /// for automatic cleanup:
1366 /// ```
1367 /// #![feature(allocator_api)]
1368 ///
1369 /// use std::alloc::System;
1370 ///
1371 /// let x = Box::new_in(String::from("Hello"), System);
1372 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1373 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1374 /// ```
1375 /// Manual cleanup by explicitly running the destructor and deallocating
1376 /// the memory:
1377 /// ```
1378 /// #![feature(allocator_api)]
1379 ///
1380 /// use std::alloc::{Allocator, Layout, System};
1381 /// use std::ptr::{self, NonNull};
1382 ///
1383 /// let x = Box::new_in(String::from("Hello"), System);
1384 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1385 /// unsafe {
1386 /// ptr::drop_in_place(ptr);
1387 /// let non_null = NonNull::new_unchecked(ptr);
1388 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1389 /// }
1390 /// ```
1391 ///
1392 /// [memory layout]: self#memory-layout
1393 #[must_use = "losing the pointer will leak memory"]
1394 #[unstable(feature = "allocator_api", issue = "32838")]
1395 #[inline]
1396 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1397 let mut b = mem::ManuallyDrop::new(b);
1398 // We carefully get the raw pointer out in a way that Miri's aliasing model understands what
1399 // is happening: using the primitive "deref" of `Box`. In case `A` is *not* `Global`, we
1400 // want *no* aliasing requirements here!
1401 // In case `A` *is* `Global`, this does not quite have the right behavior; `into_raw`
1402 // works around that.
1403 let ptr = &raw mut **b;
1404 let alloc = unsafe { ptr::read(&b.1) };
1405 (ptr, alloc)
1406 }
1407
1408 /// Consumes the `Box`, returning a wrapped `NonNull` pointer and the allocator.
1409 ///
1410 /// The pointer will be properly aligned.
1411 ///
1412 /// After calling this function, the caller is responsible for the
1413 /// memory previously managed by the `Box`. In particular, the
1414 /// caller should properly destroy `T` and release the memory, taking
1415 /// into account the [memory layout] used by `Box`. The easiest way to
1416 /// do this is to convert the `NonNull` pointer back into a `Box` with the
1417 /// [`Box::from_non_null_in`] function, allowing the `Box` destructor to
1418 /// perform the cleanup.
1419 ///
1420 /// Note: this is an associated function, which means that you have
1421 /// to call it as `Box::into_non_null_with_allocator(b)` instead of
1422 /// `b.into_non_null_with_allocator()`. This is so that there is no
1423 /// conflict with a method on the inner type.
1424 ///
1425 /// # Examples
1426 /// Converting the `NonNull` pointer back into a `Box` with
1427 /// [`Box::from_non_null_in`] for automatic cleanup:
1428 /// ```
1429 /// #![feature(allocator_api, box_vec_non_null)]
1430 ///
1431 /// use std::alloc::System;
1432 ///
1433 /// let x = Box::new_in(String::from("Hello"), System);
1434 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1435 /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1436 /// ```
1437 /// Manual cleanup by explicitly running the destructor and deallocating
1438 /// the memory:
1439 /// ```
1440 /// #![feature(allocator_api, box_vec_non_null)]
1441 ///
1442 /// use std::alloc::{Allocator, Layout, System};
1443 ///
1444 /// let x = Box::new_in(String::from("Hello"), System);
1445 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1446 /// unsafe {
1447 /// non_null.drop_in_place();
1448 /// alloc.deallocate(non_null.cast::<u8>(), Layout::new::<String>());
1449 /// }
1450 /// ```
1451 ///
1452 /// [memory layout]: self#memory-layout
1453 #[must_use = "losing the pointer will leak memory"]
1454 #[unstable(feature = "allocator_api", issue = "32838")]
1455 // #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")]
1456 #[inline]
1457 pub fn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A) {
1458 let (ptr, alloc) = Box::into_raw_with_allocator(b);
1459 // SAFETY: `Box` is guaranteed to be non-null.
1460 unsafe { (NonNull::new_unchecked(ptr), alloc) }
1461 }
1462
1463 #[unstable(
1464 feature = "ptr_internals",
1465 issue = "none",
1466 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1467 )]
1468 #[inline]
1469 #[doc(hidden)]
1470 pub fn into_unique(b: Self) -> (Unique<T>, A) {
1471 let (ptr, alloc) = Box::into_raw_with_allocator(b);
1472 unsafe { (Unique::from(&mut *ptr), alloc) }
1473 }
1474
1475 /// Returns a raw mutable pointer to the `Box`'s contents.
1476 ///
1477 /// The caller must ensure that the `Box` outlives the pointer this
1478 /// function returns, or else it will end up dangling.
1479 ///
1480 /// This method guarantees that for the purpose of the aliasing model, this method
1481 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1482 /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
1483 /// Note that calling other methods that materialize references to the memory
1484 /// may still invalidate this pointer.
1485 /// See the example below for how this guarantee can be used.
1486 ///
1487 /// # Examples
1488 ///
1489 /// Due to the aliasing guarantee, the following code is legal:
1490 ///
1491 /// ```rust
1492 /// #![feature(box_as_ptr)]
1493 ///
1494 /// unsafe {
1495 /// let mut b = Box::new(0);
1496 /// let ptr1 = Box::as_mut_ptr(&mut b);
1497 /// ptr1.write(1);
1498 /// let ptr2 = Box::as_mut_ptr(&mut b);
1499 /// ptr2.write(2);
1500 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1501 /// ptr1.write(3);
1502 /// }
1503 /// ```
1504 ///
1505 /// [`as_mut_ptr`]: Self::as_mut_ptr
1506 /// [`as_ptr`]: Self::as_ptr
1507 #[unstable(feature = "box_as_ptr", issue = "129090")]
1508 #[rustc_never_returns_null_ptr]
1509 #[rustc_as_ptr]
1510 #[inline]
1511 pub fn as_mut_ptr(b: &mut Self) -> *mut T {
1512 // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1513 // any references.
1514 &raw mut **b
1515 }
1516
1517 /// Returns a raw pointer to the `Box`'s contents.
1518 ///
1519 /// The caller must ensure that the `Box` outlives the pointer this
1520 /// function returns, or else it will end up dangling.
1521 ///
1522 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1523 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1524 /// derived from it. If you need to mutate the contents of the `Box`, use [`as_mut_ptr`].
1525 ///
1526 /// This method guarantees that for the purpose of the aliasing model, this method
1527 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1528 /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
1529 /// Note that calling other methods that materialize mutable references to the memory,
1530 /// as well as writing to this memory, may still invalidate this pointer.
1531 /// See the example below for how this guarantee can be used.
1532 ///
1533 /// # Examples
1534 ///
1535 /// Due to the aliasing guarantee, the following code is legal:
1536 ///
1537 /// ```rust
1538 /// #![feature(box_as_ptr)]
1539 ///
1540 /// unsafe {
1541 /// let mut v = Box::new(0);
1542 /// let ptr1 = Box::as_ptr(&v);
1543 /// let ptr2 = Box::as_mut_ptr(&mut v);
1544 /// let _val = ptr2.read();
1545 /// // No write to this memory has happened yet, so `ptr1` is still valid.
1546 /// let _val = ptr1.read();
1547 /// // However, once we do a write...
1548 /// ptr2.write(1);
1549 /// // ... `ptr1` is no longer valid.
1550 /// // This would be UB: let _val = ptr1.read();
1551 /// }
1552 /// ```
1553 ///
1554 /// [`as_mut_ptr`]: Self::as_mut_ptr
1555 /// [`as_ptr`]: Self::as_ptr
1556 #[unstable(feature = "box_as_ptr", issue = "129090")]
1557 #[rustc_never_returns_null_ptr]
1558 #[rustc_as_ptr]
1559 #[inline]
1560 pub fn as_ptr(b: &Self) -> *const T {
1561 // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1562 // any references.
1563 &raw const **b
1564 }
1565
1566 /// Returns a reference to the underlying allocator.
1567 ///
1568 /// Note: this is an associated function, which means that you have
1569 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1570 /// is so that there is no conflict with a method on the inner type.
1571 #[unstable(feature = "allocator_api", issue = "32838")]
1572 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1573 #[inline]
1574 pub const fn allocator(b: &Self) -> &A {
1575 &b.1
1576 }
1577
1578 /// Consumes and leaks the `Box`, returning a mutable reference,
1579 /// `&'a mut T`.
1580 ///
1581 /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
1582 /// has only static references, or none at all, then this may be chosen to be
1583 /// `'static`.
1584 ///
1585 /// This function is mainly useful for data that lives for the remainder of
1586 /// the program's life. Dropping the returned reference will cause a memory
1587 /// leak. If this is not acceptable, the reference should first be wrapped
1588 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1589 /// then be dropped which will properly destroy `T` and release the
1590 /// allocated memory.
1591 ///
1592 /// Note: this is an associated function, which means that you have
1593 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1594 /// is so that there is no conflict with a method on the inner type.
1595 ///
1596 /// # Examples
1597 ///
1598 /// Simple usage:
1599 ///
1600 /// ```
1601 /// let x = Box::new(41);
1602 /// let static_ref: &'static mut usize = Box::leak(x);
1603 /// *static_ref += 1;
1604 /// assert_eq!(*static_ref, 42);
1605 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1606 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1607 /// # drop(unsafe { Box::from_raw(static_ref) });
1608 /// ```
1609 ///
1610 /// Unsized data:
1611 ///
1612 /// ```
1613 /// let x = vec![1, 2, 3].into_boxed_slice();
1614 /// let static_ref = Box::leak(x);
1615 /// static_ref[0] = 4;
1616 /// assert_eq!(*static_ref, [4, 2, 3]);
1617 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
1618 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
1619 /// # drop(unsafe { Box::from_raw(static_ref) });
1620 /// ```
1621 #[stable(feature = "box_leak", since = "1.26.0")]
1622 #[inline]
1623 pub fn leak<'a>(b: Self) -> &'a mut T
1624 where
1625 A: 'a,
1626 {
1627 unsafe { &mut *Box::into_raw(b) }
1628 }
1629
1630 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1631 /// `*boxed` will be pinned in memory and unable to be moved.
1632 ///
1633 /// This conversion does not allocate on the heap and happens in place.
1634 ///
1635 /// This is also available via [`From`].
1636 ///
1637 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1638 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1639 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1640 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1641 ///
1642 /// # Notes
1643 ///
1644 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1645 /// as it'll introduce an ambiguity when calling `Pin::from`.
1646 /// A demonstration of such a poor impl is shown below.
1647 ///
1648 /// ```compile_fail
1649 /// # use std::pin::Pin;
1650 /// struct Foo; // A type defined in this crate.
1651 /// impl From<Box<()>> for Pin<Foo> {
1652 /// fn from(_: Box<()>) -> Pin<Foo> {
1653 /// Pin::new(Foo)
1654 /// }
1655 /// }
1656 ///
1657 /// let foo = Box::new(());
1658 /// let bar = Pin::from(foo);
1659 /// ```
1660 #[stable(feature = "box_into_pin", since = "1.63.0")]
1661 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1662 pub const fn into_pin(boxed: Self) -> Pin<Self>
1663 where
1664 A: 'static,
1665 {
1666 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1667 // when `T: !Unpin`, so it's safe to pin it directly without any
1668 // additional requirements.
1669 unsafe { Pin::new_unchecked(boxed) }
1670 }
1671}
1672
1673#[stable(feature = "rust1", since = "1.0.0")]
1674unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1675 #[inline]
1676 fn drop(&mut self) {
1677 // the T in the Box is dropped by the compiler before the destructor is run
1678
1679 let ptr = self.0;
1680
1681 unsafe {
1682 let layout = Layout::for_value_raw(ptr.as_ptr());
1683 if layout.size() != 0 {
1684 self.1.deallocate(From::from(ptr.cast()), layout);
1685 }
1686 }
1687 }
1688}
1689
1690#[cfg(not(no_global_oom_handling))]
1691#[stable(feature = "rust1", since = "1.0.0")]
1692impl<T: Default> Default for Box<T> {
1693 /// Creates a `Box<T>`, with the `Default` value for T.
1694 #[inline]
1695 fn default() -> Self {
1696 Box::write(Box::new_uninit(), T::default())
1697 }
1698}
1699
1700#[cfg(not(no_global_oom_handling))]
1701#[stable(feature = "rust1", since = "1.0.0")]
1702impl<T> Default for Box<[T]> {
1703 #[inline]
1704 fn default() -> Self {
1705 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1706 Box(ptr, Global)
1707 }
1708}
1709
1710#[cfg(not(no_global_oom_handling))]
1711#[stable(feature = "default_box_extra", since = "1.17.0")]
1712impl Default for Box<str> {
1713 #[inline]
1714 fn default() -> Self {
1715 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1716 let ptr: Unique<str> = unsafe {
1717 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1718 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1719 };
1720 Box(ptr, Global)
1721 }
1722}
1723
1724#[cfg(not(no_global_oom_handling))]
1725#[stable(feature = "rust1", since = "1.0.0")]
1726impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1727 /// Returns a new box with a `clone()` of this box's contents.
1728 ///
1729 /// # Examples
1730 ///
1731 /// ```
1732 /// let x = Box::new(5);
1733 /// let y = x.clone();
1734 ///
1735 /// // The value is the same
1736 /// assert_eq!(x, y);
1737 ///
1738 /// // But they are unique objects
1739 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1740 /// ```
1741 #[inline]
1742 fn clone(&self) -> Self {
1743 // Pre-allocate memory to allow writing the cloned value directly.
1744 let mut boxed = Self::new_uninit_in(self.1.clone());
1745 unsafe {
1746 (**self).clone_to_uninit(boxed.as_mut_ptr().cast());
1747 boxed.assume_init()
1748 }
1749 }
1750
1751 /// Copies `source`'s contents into `self` without creating a new allocation.
1752 ///
1753 /// # Examples
1754 ///
1755 /// ```
1756 /// let x = Box::new(5);
1757 /// let mut y = Box::new(10);
1758 /// let yp: *const i32 = &*y;
1759 ///
1760 /// y.clone_from(&x);
1761 ///
1762 /// // The value is the same
1763 /// assert_eq!(x, y);
1764 ///
1765 /// // And no allocation occurred
1766 /// assert_eq!(yp, &*y);
1767 /// ```
1768 #[inline]
1769 fn clone_from(&mut self, source: &Self) {
1770 (**self).clone_from(&(**source));
1771 }
1772}
1773
1774#[cfg(not(no_global_oom_handling))]
1775#[stable(feature = "box_slice_clone", since = "1.3.0")]
1776impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
1777 fn clone(&self) -> Self {
1778 let alloc = Box::allocator(self).clone();
1779 self.to_vec_in(alloc).into_boxed_slice()
1780 }
1781
1782 /// Copies `source`'s contents into `self` without creating a new allocation,
1783 /// so long as the two are of the same length.
1784 ///
1785 /// # Examples
1786 ///
1787 /// ```
1788 /// let x = Box::new([5, 6, 7]);
1789 /// let mut y = Box::new([8, 9, 10]);
1790 /// let yp: *const [i32] = &*y;
1791 ///
1792 /// y.clone_from(&x);
1793 ///
1794 /// // The value is the same
1795 /// assert_eq!(x, y);
1796 ///
1797 /// // And no allocation occurred
1798 /// assert_eq!(yp, &*y);
1799 /// ```
1800 fn clone_from(&mut self, source: &Self) {
1801 if self.len() == source.len() {
1802 self.clone_from_slice(&source);
1803 } else {
1804 *self = source.clone();
1805 }
1806 }
1807}
1808
1809#[cfg(not(no_global_oom_handling))]
1810#[stable(feature = "box_slice_clone", since = "1.3.0")]
1811impl Clone for Box<str> {
1812 fn clone(&self) -> Self {
1813 // this makes a copy of the data
1814 let buf: Box<[u8]> = self.as_bytes().into();
1815 unsafe { from_boxed_utf8_unchecked(buf) }
1816 }
1817}
1818
1819#[stable(feature = "rust1", since = "1.0.0")]
1820impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1821 #[inline]
1822 fn eq(&self, other: &Self) -> bool {
1823 PartialEq::eq(&**self, &**other)
1824 }
1825 #[inline]
1826 fn ne(&self, other: &Self) -> bool {
1827 PartialEq::ne(&**self, &**other)
1828 }
1829}
1830
1831#[stable(feature = "rust1", since = "1.0.0")]
1832impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1833 #[inline]
1834 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1835 PartialOrd::partial_cmp(&**self, &**other)
1836 }
1837 #[inline]
1838 fn lt(&self, other: &Self) -> bool {
1839 PartialOrd::lt(&**self, &**other)
1840 }
1841 #[inline]
1842 fn le(&self, other: &Self) -> bool {
1843 PartialOrd::le(&**self, &**other)
1844 }
1845 #[inline]
1846 fn ge(&self, other: &Self) -> bool {
1847 PartialOrd::ge(&**self, &**other)
1848 }
1849 #[inline]
1850 fn gt(&self, other: &Self) -> bool {
1851 PartialOrd::gt(&**self, &**other)
1852 }
1853}
1854
1855#[stable(feature = "rust1", since = "1.0.0")]
1856impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1857 #[inline]
1858 fn cmp(&self, other: &Self) -> Ordering {
1859 Ord::cmp(&**self, &**other)
1860 }
1861}
1862
1863#[stable(feature = "rust1", since = "1.0.0")]
1864impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1865
1866#[stable(feature = "rust1", since = "1.0.0")]
1867impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1868 fn hash<H: Hasher>(&self, state: &mut H) {
1869 (**self).hash(state);
1870 }
1871}
1872
1873#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1874impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1875 fn finish(&self) -> u64 {
1876 (**self).finish()
1877 }
1878 fn write(&mut self, bytes: &[u8]) {
1879 (**self).write(bytes)
1880 }
1881 fn write_u8(&mut self, i: u8) {
1882 (**self).write_u8(i)
1883 }
1884 fn write_u16(&mut self, i: u16) {
1885 (**self).write_u16(i)
1886 }
1887 fn write_u32(&mut self, i: u32) {
1888 (**self).write_u32(i)
1889 }
1890 fn write_u64(&mut self, i: u64) {
1891 (**self).write_u64(i)
1892 }
1893 fn write_u128(&mut self, i: u128) {
1894 (**self).write_u128(i)
1895 }
1896 fn write_usize(&mut self, i: usize) {
1897 (**self).write_usize(i)
1898 }
1899 fn write_i8(&mut self, i: i8) {
1900 (**self).write_i8(i)
1901 }
1902 fn write_i16(&mut self, i: i16) {
1903 (**self).write_i16(i)
1904 }
1905 fn write_i32(&mut self, i: i32) {
1906 (**self).write_i32(i)
1907 }
1908 fn write_i64(&mut self, i: i64) {
1909 (**self).write_i64(i)
1910 }
1911 fn write_i128(&mut self, i: i128) {
1912 (**self).write_i128(i)
1913 }
1914 fn write_isize(&mut self, i: isize) {
1915 (**self).write_isize(i)
1916 }
1917 fn write_length_prefix(&mut self, len: usize) {
1918 (**self).write_length_prefix(len)
1919 }
1920 fn write_str(&mut self, s: &str) {
1921 (**self).write_str(s)
1922 }
1923}
1924
1925#[stable(feature = "rust1", since = "1.0.0")]
1926impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1927 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1928 fmt::Display::fmt(&**self, f)
1929 }
1930}
1931
1932#[stable(feature = "rust1", since = "1.0.0")]
1933impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1934 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1935 fmt::Debug::fmt(&**self, f)
1936 }
1937}
1938
1939#[stable(feature = "rust1", since = "1.0.0")]
1940impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1941 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1942 // It's not possible to extract the inner Uniq directly from the Box,
1943 // instead we cast it to a *const which aliases the Unique
1944 let ptr: *const T = &**self;
1945 fmt::Pointer::fmt(&ptr, f)
1946 }
1947}
1948
1949#[stable(feature = "rust1", since = "1.0.0")]
1950impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
1951 type Target = T;
1952
1953 fn deref(&self) -> &T {
1954 &**self
1955 }
1956}
1957
1958#[stable(feature = "rust1", since = "1.0.0")]
1959impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
1960 fn deref_mut(&mut self) -> &mut T {
1961 &mut **self
1962 }
1963}
1964
1965#[unstable(feature = "deref_pure_trait", issue = "87121")]
1966unsafe impl<T: ?Sized, A: Allocator> DerefPure for Box<T, A> {}
1967
1968#[unstable(feature = "legacy_receiver_trait", issue = "none")]
1969impl<T: ?Sized, A: Allocator> LegacyReceiver for Box<T, A> {}
1970
1971#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1972impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1973 type Output = <F as FnOnce<Args>>::Output;
1974
1975 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1976 <F as FnOnce<Args>>::call_once(*self, args)
1977 }
1978}
1979
1980#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1981impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1982 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1983 <F as FnMut<Args>>::call_mut(self, args)
1984 }
1985}
1986
1987#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1988impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
1989 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1990 <F as Fn<Args>>::call(self, args)
1991 }
1992}
1993
1994#[stable(feature = "async_closure", since = "1.85.0")]
1995impl<Args: Tuple, F: AsyncFnOnce<Args> + ?Sized, A: Allocator> AsyncFnOnce<Args> for Box<F, A> {
1996 type Output = F::Output;
1997 type CallOnceFuture = F::CallOnceFuture;
1998
1999 extern "rust-call" fn async_call_once(self, args: Args) -> Self::CallOnceFuture {
2000 F::async_call_once(*self, args)
2001 }
2002}
2003
2004#[stable(feature = "async_closure", since = "1.85.0")]
2005impl<Args: Tuple, F: AsyncFnMut<Args> + ?Sized, A: Allocator> AsyncFnMut<Args> for Box<F, A> {
2006 type CallRefFuture<'a>
2007 = F::CallRefFuture<'a>
2008 where
2009 Self: 'a;
2010
2011 extern "rust-call" fn async_call_mut(&mut self, args: Args) -> Self::CallRefFuture<'_> {
2012 F::async_call_mut(self, args)
2013 }
2014}
2015
2016#[stable(feature = "async_closure", since = "1.85.0")]
2017impl<Args: Tuple, F: AsyncFn<Args> + ?Sized, A: Allocator> AsyncFn<Args> for Box<F, A> {
2018 extern "rust-call" fn async_call(&self, args: Args) -> Self::CallRefFuture<'_> {
2019 F::async_call(self, args)
2020 }
2021}
2022
2023#[unstable(feature = "coerce_unsized", issue = "18598")]
2024impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2025
2026#[unstable(feature = "pin_coerce_unsized_trait", issue = "123430")]
2027unsafe impl<T: ?Sized, A: Allocator> PinCoerceUnsized for Box<T, A> {}
2028
2029// It is quite crucial that we only allow the `Global` allocator here.
2030// Handling arbitrary custom allocators (which can affect the `Box` layout heavily!)
2031// would need a lot of codegen and interpreter adjustments.
2032#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2033impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2034
2035#[stable(feature = "box_borrow", since = "1.1.0")]
2036impl<T: ?Sized, A: Allocator> Borrow<T> for Box<T, A> {
2037 fn borrow(&self) -> &T {
2038 &**self
2039 }
2040}
2041
2042#[stable(feature = "box_borrow", since = "1.1.0")]
2043impl<T: ?Sized, A: Allocator> BorrowMut<T> for Box<T, A> {
2044 fn borrow_mut(&mut self) -> &mut T {
2045 &mut **self
2046 }
2047}
2048
2049#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2050impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2051 fn as_ref(&self) -> &T {
2052 &**self
2053 }
2054}
2055
2056#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2057impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2058 fn as_mut(&mut self) -> &mut T {
2059 &mut **self
2060 }
2061}
2062
2063/* Nota bene
2064 *
2065 * We could have chosen not to add this impl, and instead have written a
2066 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2067 * because Box<T> implements Unpin even when T does not, as a result of
2068 * this impl.
2069 *
2070 * We chose this API instead of the alternative for a few reasons:
2071 * - Logically, it is helpful to understand pinning in regard to the
2072 * memory region being pointed to. For this reason none of the
2073 * standard library pointer types support projecting through a pin
2074 * (Box<T> is the only pointer type in std for which this would be
2075 * safe.)
2076 * - It is in practice very useful to have Box<T> be unconditionally
2077 * Unpin because of trait objects, for which the structural auto
2078 * trait functionality does not apply (e.g., Box<dyn Foo> would
2079 * otherwise not be Unpin).
2080 *
2081 * Another type with the same semantics as Box but only a conditional
2082 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2083 * could have a method to project a Pin<T> from it.
2084 */
2085#[stable(feature = "pin", since = "1.33.0")]
2086impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> {}
2087
2088#[unstable(feature = "coroutine_trait", issue = "43122")]
2089impl<G: ?Sized + Coroutine<R> + Unpin, R, A: Allocator> Coroutine<R> for Box<G, A> {
2090 type Yield = G::Yield;
2091 type Return = G::Return;
2092
2093 fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2094 G::resume(Pin::new(&mut *self), arg)
2095 }
2096}
2097
2098#[unstable(feature = "coroutine_trait", issue = "43122")]
2099impl<G: ?Sized + Coroutine<R>, R, A: Allocator> Coroutine<R> for Pin<Box<G, A>>
2100where
2101 A: 'static,
2102{
2103 type Yield = G::Yield;
2104 type Return = G::Return;
2105
2106 fn resume(mut self: Pin<&mut Self>, arg: R) -> CoroutineState<Self::Yield, Self::Return> {
2107 G::resume((*self).as_mut(), arg)
2108 }
2109}
2110
2111#[stable(feature = "futures_api", since = "1.36.0")]
2112impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A> {
2113 type Output = F::Output;
2114
2115 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2116 F::poll(Pin::new(&mut *self), cx)
2117 }
2118}
2119
2120#[stable(feature = "box_error", since = "1.8.0")]
2121impl<E: Error> Error for Box<E> {
2122 #[allow(deprecated, deprecated_in_future)]
2123 fn description(&self) -> &str {
2124 Error::description(&**self)
2125 }
2126
2127 #[allow(deprecated)]
2128 fn cause(&self) -> Option<&dyn Error> {
2129 Error::cause(&**self)
2130 }
2131
2132 fn source(&self) -> Option<&(dyn Error + 'static)> {
2133 Error::source(&**self)
2134 }
2135
2136 fn provide<'b>(&'b self, request: &mut error::Request<'b>) {
2137 Error::provide(&**self, request);
2138 }
2139}
2140
2141#[unstable(feature = "pointer_like_trait", issue = "none")]
2142impl<T> PointerLike for Box<T> {}