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