Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
1// SPDX-License-Identifier: Apache-2.0 OR MIT
2
3//! The `Box<T>` type for heap allocation.
4//!
5//! [`Box<T>`], casually referred to as a 'box', provides the simplest form of
6//! heap allocation in Rust. Boxes provide ownership for this allocation, and
7//! drop their contents when they go out of scope. Boxes also ensure that they
8//! never allocate more than `isize::MAX` bytes.
9//!
10//! # Examples
11//!
12//! Move a value from the stack to the heap by creating a [`Box`]:
13//!
14//! ```
15//! let val: u8 = 5;
16//! let boxed: Box<u8> = Box::new(val);
17//! ```
18//!
19//! Move a value from a [`Box`] back to the stack by [dereferencing]:
20//!
21//! ```
22//! let boxed: Box<u8> = Box::new(5);
23//! let val: u8 = *boxed;
24//! ```
25//!
26//! Creating a recursive data structure:
27//!
28//! ```
29//! #[derive(Debug)]
30//! enum List<T> {
31//! Cons(T, Box<List<T>>),
32//! Nil,
33//! }
34//!
35//! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
36//! println!("{list:?}");
37//! ```
38//!
39//! This will print `Cons(1, Cons(2, Nil))`.
40//!
41//! Recursive structures must be boxed, because if the definition of `Cons`
42//! looked like this:
43//!
44//! ```compile_fail,E0072
45//! # enum List<T> {
46//! Cons(T, List<T>),
47//! # }
48//! ```
49//!
50//! It wouldn't work. This is because the size of a `List` depends on how many
51//! elements are in the list, and so we don't know how much memory to allocate
52//! for a `Cons`. By introducing a [`Box<T>`], which has a defined size, we know how
53//! big `Cons` needs to be.
54//!
55//! # Memory layout
56//!
57//! For non-zero-sized values, a [`Box`] will use the [`Global`] allocator for
58//! its allocation. It is valid to convert both ways between a [`Box`] and a
59//! raw pointer allocated with the [`Global`] allocator, given that the
60//! [`Layout`] used with the allocator is correct for the type. More precisely,
61//! a `value: *mut T` that has been allocated with the [`Global`] allocator
62//! with `Layout::for_value(&*value)` may be converted into a box using
63//! [`Box::<T>::from_raw(value)`]. Conversely, the memory backing a `value: *mut
64//! T` obtained from [`Box::<T>::into_raw`] may be deallocated using the
65//! [`Global`] allocator with [`Layout::for_value(&*value)`].
66//!
67//! For zero-sized values, the `Box` pointer still has to be [valid] for reads
68//! and writes and sufficiently aligned. In particular, casting any aligned
69//! non-zero integer literal to a raw pointer produces a valid pointer, but a
70//! pointer pointing into previously allocated memory that since got freed is
71//! not valid. The recommended way to build a Box to a ZST if `Box::new` cannot
72//! be used is to use [`ptr::NonNull::dangling`].
73//!
74//! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
75//! as a single pointer and is also ABI-compatible with C pointers
76//! (i.e. the C type `T*`). This means that if you have extern "C"
77//! Rust functions that will be called from C, you can define those
78//! Rust functions using `Box<T>` types, and use `T*` as corresponding
79//! type on the C side. As an example, consider this C header which
80//! declares functions that create and destroy some kind of `Foo`
81//! value:
82//!
83//! ```c
84//! /* C header */
85//!
86//! /* Returns ownership to the caller */
87//! struct Foo* foo_new(void);
88//!
89//! /* Takes ownership from the caller; no-op when invoked with null */
90//! void foo_delete(struct Foo*);
91//! ```
92//!
93//! These two functions might be implemented in Rust as follows. Here, the
94//! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
95//! the ownership constraints. Note also that the nullable argument to
96//! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
97//! cannot be null.
98//!
99//! ```
100//! #[repr(C)]
101//! pub struct Foo;
102//!
103//! #[no_mangle]
104//! pub extern "C" fn foo_new() -> Box<Foo> {
105//! Box::new(Foo)
106//! }
107//!
108//! #[no_mangle]
109//! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
110//! ```
111//!
112//! Even though `Box<T>` has the same representation and C ABI as a C pointer,
113//! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
114//! and expect things to work. `Box<T>` values will always be fully aligned,
115//! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
116//! free the value with the global allocator. In general, the best practice
117//! is to only use `Box<T>` for pointers that originated from the global
118//! allocator.
119//!
120//! **Important.** At least at present, you should avoid using
121//! `Box<T>` types for functions that are defined in C but invoked
122//! from Rust. In those cases, you should directly mirror the C types
123//! as closely as possible. Using types like `Box<T>` where the C
124//! definition is just using `T*` can lead to undefined behavior, as
125//! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
126//!
127//! # Considerations for unsafe code
128//!
129//! **Warning: This section is not normative and is subject to change, possibly
130//! being relaxed in the future! It is a simplified summary of the rules
131//! currently implemented in the compiler.**
132//!
133//! The aliasing rules for `Box<T>` are the same as for `&mut T`. `Box<T>`
134//! asserts uniqueness over its content. Using raw pointers derived from a box
135//! after that box has been mutated through, moved or borrowed as `&mut T`
136//! is not allowed. For more guidance on working with box from unsafe code, see
137//! [rust-lang/unsafe-code-guidelines#326][ucg#326].
138//!
139//!
140//! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
141//! [ucg#326]: https://github.com/rust-lang/unsafe-code-guidelines/issues/326
142//! [dereferencing]: core::ops::Deref
143//! [`Box::<T>::from_raw(value)`]: Box::from_raw
144//! [`Global`]: crate::alloc::Global
145//! [`Layout`]: crate::alloc::Layout
146//! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
147//! [valid]: ptr#safety
148
149#![stable(feature = "rust1", since = "1.0.0")]
150
151use core::any::Any;
152use core::async_iter::AsyncIterator;
153use core::borrow;
154use core::cmp::Ordering;
155use core::convert::{From, TryFrom};
156use core::error::Error;
157use core::fmt;
158use core::future::Future;
159use core::hash::{Hash, Hasher};
160#[cfg(not(no_global_oom_handling))]
161use core::iter::FromIterator;
162use core::iter::{FusedIterator, Iterator};
163use core::marker::Tuple;
164use core::marker::{Destruct, Unpin, Unsize};
165use core::mem;
166use core::ops::{
167 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
168};
169use core::pin::Pin;
170use core::ptr::{self, Unique};
171use core::task::{Context, Poll};
172
173#[cfg(not(no_global_oom_handling))]
174use crate::alloc::{handle_alloc_error, WriteCloneIntoRaw};
175use crate::alloc::{AllocError, Allocator, Global, Layout};
176#[cfg(not(no_global_oom_handling))]
177use crate::borrow::Cow;
178use crate::raw_vec::RawVec;
179#[cfg(not(no_global_oom_handling))]
180use crate::str::from_boxed_utf8_unchecked;
181#[cfg(not(no_global_oom_handling))]
182use crate::string::String;
183#[cfg(not(no_global_oom_handling))]
184use crate::vec::Vec;
185
186#[cfg(not(no_thin))]
187#[unstable(feature = "thin_box", issue = "92791")]
188pub use thin::ThinBox;
189
190#[cfg(not(no_thin))]
191mod thin;
192
193/// A pointer type that uniquely owns a heap allocation of type `T`.
194///
195/// See the [module-level documentation](../../std/boxed/index.html) for more.
196#[lang = "owned_box"]
197#[fundamental]
198#[stable(feature = "rust1", since = "1.0.0")]
199// The declaration of the `Box` struct must be kept in sync with the
200// `alloc::alloc::box_free` function or ICEs will happen. See the comment
201// on `box_free` for more details.
202pub struct Box<
203 T: ?Sized,
204 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
205>(Unique<T>, A);
206
207impl<T> Box<T> {
208 /// Allocates memory on the heap and then places `x` into it.
209 ///
210 /// This doesn't actually allocate if `T` is zero-sized.
211 ///
212 /// # Examples
213 ///
214 /// ```
215 /// let five = Box::new(5);
216 /// ```
217 #[cfg(all(not(no_global_oom_handling)))]
218 #[inline(always)]
219 #[stable(feature = "rust1", since = "1.0.0")]
220 #[must_use]
221 pub fn new(x: T) -> Self {
222 #[rustc_box]
223 Box::new(x)
224 }
225
226 /// Constructs a new box with uninitialized contents.
227 ///
228 /// # Examples
229 ///
230 /// ```
231 /// #![feature(new_uninit)]
232 ///
233 /// let mut five = Box::<u32>::new_uninit();
234 ///
235 /// let five = unsafe {
236 /// // Deferred initialization:
237 /// five.as_mut_ptr().write(5);
238 ///
239 /// five.assume_init()
240 /// };
241 ///
242 /// assert_eq!(*five, 5)
243 /// ```
244 #[cfg(not(no_global_oom_handling))]
245 #[unstable(feature = "new_uninit", issue = "63291")]
246 #[must_use]
247 #[inline]
248 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
249 Self::new_uninit_in(Global)
250 }
251
252 /// Constructs a new `Box` with uninitialized contents, with the memory
253 /// being filled with `0` bytes.
254 ///
255 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
256 /// of this method.
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// #![feature(new_uninit)]
262 ///
263 /// let zero = Box::<u32>::new_zeroed();
264 /// let zero = unsafe { zero.assume_init() };
265 ///
266 /// assert_eq!(*zero, 0)
267 /// ```
268 ///
269 /// [zeroed]: mem::MaybeUninit::zeroed
270 #[cfg(not(no_global_oom_handling))]
271 #[inline]
272 #[unstable(feature = "new_uninit", issue = "63291")]
273 #[must_use]
274 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
275 Self::new_zeroed_in(Global)
276 }
277
278 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
279 /// `x` will be pinned in memory and unable to be moved.
280 ///
281 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin(x)`
282 /// does the same as <code>[Box::into_pin]\([Box::new]\(x))</code>. Consider using
283 /// [`into_pin`](Box::into_pin) if you already have a `Box<T>`, or if you want to
284 /// construct a (pinned) `Box` in a different way than with [`Box::new`].
285 #[cfg(not(no_global_oom_handling))]
286 #[stable(feature = "pin", since = "1.33.0")]
287 #[must_use]
288 #[inline(always)]
289 pub fn pin(x: T) -> Pin<Box<T>> {
290 (#[rustc_box]
291 Box::new(x))
292 .into()
293 }
294
295 /// Allocates memory on the heap then places `x` into it,
296 /// returning an error if the allocation fails
297 ///
298 /// This doesn't actually allocate if `T` is zero-sized.
299 ///
300 /// # Examples
301 ///
302 /// ```
303 /// #![feature(allocator_api)]
304 ///
305 /// let five = Box::try_new(5)?;
306 /// # Ok::<(), std::alloc::AllocError>(())
307 /// ```
308 #[unstable(feature = "allocator_api", issue = "32838")]
309 #[inline]
310 pub fn try_new(x: T) -> Result<Self, AllocError> {
311 Self::try_new_in(x, Global)
312 }
313
314 /// Constructs a new box with uninitialized contents on the heap,
315 /// returning an error if the allocation fails
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// #![feature(allocator_api, new_uninit)]
321 ///
322 /// let mut five = Box::<u32>::try_new_uninit()?;
323 ///
324 /// let five = unsafe {
325 /// // Deferred initialization:
326 /// five.as_mut_ptr().write(5);
327 ///
328 /// five.assume_init()
329 /// };
330 ///
331 /// assert_eq!(*five, 5);
332 /// # Ok::<(), std::alloc::AllocError>(())
333 /// ```
334 #[unstable(feature = "allocator_api", issue = "32838")]
335 // #[unstable(feature = "new_uninit", issue = "63291")]
336 #[inline]
337 pub fn try_new_uninit() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
338 Box::try_new_uninit_in(Global)
339 }
340
341 /// Constructs a new `Box` with uninitialized contents, with the memory
342 /// being filled with `0` bytes on the heap
343 ///
344 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
345 /// of this method.
346 ///
347 /// # Examples
348 ///
349 /// ```
350 /// #![feature(allocator_api, new_uninit)]
351 ///
352 /// let zero = Box::<u32>::try_new_zeroed()?;
353 /// let zero = unsafe { zero.assume_init() };
354 ///
355 /// assert_eq!(*zero, 0);
356 /// # Ok::<(), std::alloc::AllocError>(())
357 /// ```
358 ///
359 /// [zeroed]: mem::MaybeUninit::zeroed
360 #[unstable(feature = "allocator_api", issue = "32838")]
361 // #[unstable(feature = "new_uninit", issue = "63291")]
362 #[inline]
363 pub fn try_new_zeroed() -> Result<Box<mem::MaybeUninit<T>>, AllocError> {
364 Box::try_new_zeroed_in(Global)
365 }
366}
367
368impl<T, A: Allocator> Box<T, A> {
369 /// Allocates memory in the given allocator then places `x` into it.
370 ///
371 /// This doesn't actually allocate if `T` is zero-sized.
372 ///
373 /// # Examples
374 ///
375 /// ```
376 /// #![feature(allocator_api)]
377 ///
378 /// use std::alloc::System;
379 ///
380 /// let five = Box::new_in(5, System);
381 /// ```
382 #[cfg(not(no_global_oom_handling))]
383 #[unstable(feature = "allocator_api", issue = "32838")]
384 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
385 #[must_use]
386 #[inline]
387 pub const fn new_in(x: T, alloc: A) -> Self
388 where
389 A: ~const Allocator + ~const Destruct,
390 {
391 let mut boxed = Self::new_uninit_in(alloc);
392 unsafe {
393 boxed.as_mut_ptr().write(x);
394 boxed.assume_init()
395 }
396 }
397
398 /// Allocates memory in the given allocator then places `x` into it,
399 /// returning an error if the allocation fails
400 ///
401 /// This doesn't actually allocate if `T` is zero-sized.
402 ///
403 /// # Examples
404 ///
405 /// ```
406 /// #![feature(allocator_api)]
407 ///
408 /// use std::alloc::System;
409 ///
410 /// let five = Box::try_new_in(5, System)?;
411 /// # Ok::<(), std::alloc::AllocError>(())
412 /// ```
413 #[unstable(feature = "allocator_api", issue = "32838")]
414 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
415 #[inline]
416 pub const fn try_new_in(x: T, alloc: A) -> Result<Self, AllocError>
417 where
418 T: ~const Destruct,
419 A: ~const Allocator + ~const Destruct,
420 {
421 let mut boxed = Self::try_new_uninit_in(alloc)?;
422 unsafe {
423 boxed.as_mut_ptr().write(x);
424 Ok(boxed.assume_init())
425 }
426 }
427
428 /// Constructs a new box with uninitialized contents in the provided allocator.
429 ///
430 /// # Examples
431 ///
432 /// ```
433 /// #![feature(allocator_api, new_uninit)]
434 ///
435 /// use std::alloc::System;
436 ///
437 /// let mut five = Box::<u32, _>::new_uninit_in(System);
438 ///
439 /// let five = unsafe {
440 /// // Deferred initialization:
441 /// five.as_mut_ptr().write(5);
442 ///
443 /// five.assume_init()
444 /// };
445 ///
446 /// assert_eq!(*five, 5)
447 /// ```
448 #[unstable(feature = "allocator_api", issue = "32838")]
449 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
450 #[cfg(not(no_global_oom_handling))]
451 #[must_use]
452 // #[unstable(feature = "new_uninit", issue = "63291")]
453 pub const fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
454 where
455 A: ~const Allocator + ~const Destruct,
456 {
457 let layout = Layout::new::<mem::MaybeUninit<T>>();
458 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
459 // That would make code size bigger.
460 match Box::try_new_uninit_in(alloc) {
461 Ok(m) => m,
462 Err(_) => handle_alloc_error(layout),
463 }
464 }
465
466 /// Constructs a new box with uninitialized contents in the provided allocator,
467 /// returning an error if the allocation fails
468 ///
469 /// # Examples
470 ///
471 /// ```
472 /// #![feature(allocator_api, new_uninit)]
473 ///
474 /// use std::alloc::System;
475 ///
476 /// let mut five = Box::<u32, _>::try_new_uninit_in(System)?;
477 ///
478 /// let five = unsafe {
479 /// // Deferred initialization:
480 /// five.as_mut_ptr().write(5);
481 ///
482 /// five.assume_init()
483 /// };
484 ///
485 /// assert_eq!(*five, 5);
486 /// # Ok::<(), std::alloc::AllocError>(())
487 /// ```
488 #[unstable(feature = "allocator_api", issue = "32838")]
489 // #[unstable(feature = "new_uninit", issue = "63291")]
490 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
491 pub const fn try_new_uninit_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
492 where
493 A: ~const Allocator + ~const Destruct,
494 {
495 let layout = Layout::new::<mem::MaybeUninit<T>>();
496 let ptr = alloc.allocate(layout)?.cast();
497 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
498 }
499
500 /// Constructs a new `Box` with uninitialized contents, with the memory
501 /// being filled with `0` bytes in the provided allocator.
502 ///
503 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
504 /// of this method.
505 ///
506 /// # Examples
507 ///
508 /// ```
509 /// #![feature(allocator_api, new_uninit)]
510 ///
511 /// use std::alloc::System;
512 ///
513 /// let zero = Box::<u32, _>::new_zeroed_in(System);
514 /// let zero = unsafe { zero.assume_init() };
515 ///
516 /// assert_eq!(*zero, 0)
517 /// ```
518 ///
519 /// [zeroed]: mem::MaybeUninit::zeroed
520 #[unstable(feature = "allocator_api", issue = "32838")]
521 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
522 #[cfg(not(no_global_oom_handling))]
523 // #[unstable(feature = "new_uninit", issue = "63291")]
524 #[must_use]
525 pub const fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A>
526 where
527 A: ~const Allocator + ~const Destruct,
528 {
529 let layout = Layout::new::<mem::MaybeUninit<T>>();
530 // NOTE: Prefer match over unwrap_or_else since closure sometimes not inlineable.
531 // That would make code size bigger.
532 match Box::try_new_zeroed_in(alloc) {
533 Ok(m) => m,
534 Err(_) => handle_alloc_error(layout),
535 }
536 }
537
538 /// Constructs a new `Box` with uninitialized contents, with the memory
539 /// being filled with `0` bytes in the provided allocator,
540 /// returning an error if the allocation fails,
541 ///
542 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
543 /// of this method.
544 ///
545 /// # Examples
546 ///
547 /// ```
548 /// #![feature(allocator_api, new_uninit)]
549 ///
550 /// use std::alloc::System;
551 ///
552 /// let zero = Box::<u32, _>::try_new_zeroed_in(System)?;
553 /// let zero = unsafe { zero.assume_init() };
554 ///
555 /// assert_eq!(*zero, 0);
556 /// # Ok::<(), std::alloc::AllocError>(())
557 /// ```
558 ///
559 /// [zeroed]: mem::MaybeUninit::zeroed
560 #[unstable(feature = "allocator_api", issue = "32838")]
561 // #[unstable(feature = "new_uninit", issue = "63291")]
562 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
563 pub const fn try_new_zeroed_in(alloc: A) -> Result<Box<mem::MaybeUninit<T>, A>, AllocError>
564 where
565 A: ~const Allocator + ~const Destruct,
566 {
567 let layout = Layout::new::<mem::MaybeUninit<T>>();
568 let ptr = alloc.allocate_zeroed(layout)?.cast();
569 unsafe { Ok(Box::from_raw_in(ptr.as_ptr(), alloc)) }
570 }
571
572 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
573 /// `x` will be pinned in memory and unable to be moved.
574 ///
575 /// Constructing and pinning of the `Box` can also be done in two steps: `Box::pin_in(x, alloc)`
576 /// does the same as <code>[Box::into_pin]\([Box::new_in]\(x, alloc))</code>. Consider using
577 /// [`into_pin`](Box::into_pin) if you already have a `Box<T, A>`, or if you want to
578 /// construct a (pinned) `Box` in a different way than with [`Box::new_in`].
579 #[cfg(not(no_global_oom_handling))]
580 #[unstable(feature = "allocator_api", issue = "32838")]
581 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
582 #[must_use]
583 #[inline(always)]
584 pub const fn pin_in(x: T, alloc: A) -> Pin<Self>
585 where
586 A: 'static + ~const Allocator + ~const Destruct,
587 {
588 Self::into_pin(Self::new_in(x, alloc))
589 }
590
591 /// Converts a `Box<T>` into a `Box<[T]>`
592 ///
593 /// This conversion does not allocate on the heap and happens in place.
594 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
595 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
596 pub const fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
597 let (raw, alloc) = Box::into_raw_with_allocator(boxed);
598 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
599 }
600
601 /// Consumes the `Box`, returning the wrapped value.
602 ///
603 /// # Examples
604 ///
605 /// ```
606 /// #![feature(box_into_inner)]
607 ///
608 /// let c = Box::new(5);
609 ///
610 /// assert_eq!(Box::into_inner(c), 5);
611 /// ```
612 #[unstable(feature = "box_into_inner", issue = "80437")]
613 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
614 #[inline]
615 pub const fn into_inner(boxed: Self) -> T
616 where
617 Self: ~const Destruct,
618 {
619 *boxed
620 }
621}
622
623impl<T> Box<[T]> {
624 /// Constructs a new boxed slice with uninitialized contents.
625 ///
626 /// # Examples
627 ///
628 /// ```
629 /// #![feature(new_uninit)]
630 ///
631 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
632 ///
633 /// let values = unsafe {
634 /// // Deferred initialization:
635 /// values[0].as_mut_ptr().write(1);
636 /// values[1].as_mut_ptr().write(2);
637 /// values[2].as_mut_ptr().write(3);
638 ///
639 /// values.assume_init()
640 /// };
641 ///
642 /// assert_eq!(*values, [1, 2, 3])
643 /// ```
644 #[cfg(not(no_global_oom_handling))]
645 #[unstable(feature = "new_uninit", issue = "63291")]
646 #[must_use]
647 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
648 unsafe { RawVec::with_capacity(len).into_box(len) }
649 }
650
651 /// Constructs a new boxed slice with uninitialized contents, with the memory
652 /// being filled with `0` bytes.
653 ///
654 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
655 /// of this method.
656 ///
657 /// # Examples
658 ///
659 /// ```
660 /// #![feature(new_uninit)]
661 ///
662 /// let values = Box::<[u32]>::new_zeroed_slice(3);
663 /// let values = unsafe { values.assume_init() };
664 ///
665 /// assert_eq!(*values, [0, 0, 0])
666 /// ```
667 ///
668 /// [zeroed]: mem::MaybeUninit::zeroed
669 #[cfg(not(no_global_oom_handling))]
670 #[unstable(feature = "new_uninit", issue = "63291")]
671 #[must_use]
672 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
673 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
674 }
675
676 /// Constructs a new boxed slice with uninitialized contents. Returns an error if
677 /// the allocation fails
678 ///
679 /// # Examples
680 ///
681 /// ```
682 /// #![feature(allocator_api, new_uninit)]
683 ///
684 /// let mut values = Box::<[u32]>::try_new_uninit_slice(3)?;
685 /// let values = unsafe {
686 /// // Deferred initialization:
687 /// values[0].as_mut_ptr().write(1);
688 /// values[1].as_mut_ptr().write(2);
689 /// values[2].as_mut_ptr().write(3);
690 /// values.assume_init()
691 /// };
692 ///
693 /// assert_eq!(*values, [1, 2, 3]);
694 /// # Ok::<(), std::alloc::AllocError>(())
695 /// ```
696 #[unstable(feature = "allocator_api", issue = "32838")]
697 #[inline]
698 pub fn try_new_uninit_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
699 unsafe {
700 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
701 Ok(l) => l,
702 Err(_) => return Err(AllocError),
703 };
704 let ptr = Global.allocate(layout)?;
705 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
706 }
707 }
708
709 /// Constructs a new boxed slice with uninitialized contents, with the memory
710 /// being filled with `0` bytes. Returns an error if the allocation fails
711 ///
712 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
713 /// of this method.
714 ///
715 /// # Examples
716 ///
717 /// ```
718 /// #![feature(allocator_api, new_uninit)]
719 ///
720 /// let values = Box::<[u32]>::try_new_zeroed_slice(3)?;
721 /// let values = unsafe { values.assume_init() };
722 ///
723 /// assert_eq!(*values, [0, 0, 0]);
724 /// # Ok::<(), std::alloc::AllocError>(())
725 /// ```
726 ///
727 /// [zeroed]: mem::MaybeUninit::zeroed
728 #[unstable(feature = "allocator_api", issue = "32838")]
729 #[inline]
730 pub fn try_new_zeroed_slice(len: usize) -> Result<Box<[mem::MaybeUninit<T>]>, AllocError> {
731 unsafe {
732 let layout = match Layout::array::<mem::MaybeUninit<T>>(len) {
733 Ok(l) => l,
734 Err(_) => return Err(AllocError),
735 };
736 let ptr = Global.allocate_zeroed(layout)?;
737 Ok(RawVec::from_raw_parts_in(ptr.as_mut_ptr() as *mut _, len, Global).into_box(len))
738 }
739 }
740}
741
742impl<T, A: Allocator> Box<[T], A> {
743 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
744 ///
745 /// # Examples
746 ///
747 /// ```
748 /// #![feature(allocator_api, new_uninit)]
749 ///
750 /// use std::alloc::System;
751 ///
752 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
753 ///
754 /// let values = unsafe {
755 /// // Deferred initialization:
756 /// values[0].as_mut_ptr().write(1);
757 /// values[1].as_mut_ptr().write(2);
758 /// values[2].as_mut_ptr().write(3);
759 ///
760 /// values.assume_init()
761 /// };
762 ///
763 /// assert_eq!(*values, [1, 2, 3])
764 /// ```
765 #[cfg(not(no_global_oom_handling))]
766 #[unstable(feature = "allocator_api", issue = "32838")]
767 // #[unstable(feature = "new_uninit", issue = "63291")]
768 #[must_use]
769 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
770 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
771 }
772
773 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
774 /// with the memory being filled with `0` bytes.
775 ///
776 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
777 /// of this method.
778 ///
779 /// # Examples
780 ///
781 /// ```
782 /// #![feature(allocator_api, new_uninit)]
783 ///
784 /// use std::alloc::System;
785 ///
786 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
787 /// let values = unsafe { values.assume_init() };
788 ///
789 /// assert_eq!(*values, [0, 0, 0])
790 /// ```
791 ///
792 /// [zeroed]: mem::MaybeUninit::zeroed
793 #[cfg(not(no_global_oom_handling))]
794 #[unstable(feature = "allocator_api", issue = "32838")]
795 // #[unstable(feature = "new_uninit", issue = "63291")]
796 #[must_use]
797 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
798 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
799 }
800}
801
802impl<T, A: Allocator> Box<mem::MaybeUninit<T>, A> {
803 /// Converts to `Box<T, A>`.
804 ///
805 /// # Safety
806 ///
807 /// As with [`MaybeUninit::assume_init`],
808 /// it is up to the caller to guarantee that the value
809 /// really is in an initialized state.
810 /// Calling this when the content is not yet fully initialized
811 /// causes immediate undefined behavior.
812 ///
813 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
814 ///
815 /// # Examples
816 ///
817 /// ```
818 /// #![feature(new_uninit)]
819 ///
820 /// let mut five = Box::<u32>::new_uninit();
821 ///
822 /// let five: Box<u32> = unsafe {
823 /// // Deferred initialization:
824 /// five.as_mut_ptr().write(5);
825 ///
826 /// five.assume_init()
827 /// };
828 ///
829 /// assert_eq!(*five, 5)
830 /// ```
831 #[unstable(feature = "new_uninit", issue = "63291")]
832 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
833 #[inline]
834 pub const unsafe fn assume_init(self) -> Box<T, A> {
835 let (raw, alloc) = Box::into_raw_with_allocator(self);
836 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
837 }
838
839 /// Writes the value and converts to `Box<T, A>`.
840 ///
841 /// This method converts the box similarly to [`Box::assume_init`] but
842 /// writes `value` into it before conversion thus guaranteeing safety.
843 /// In some scenarios use of this method may improve performance because
844 /// the compiler may be able to optimize copying from stack.
845 ///
846 /// # Examples
847 ///
848 /// ```
849 /// #![feature(new_uninit)]
850 ///
851 /// let big_box = Box::<[usize; 1024]>::new_uninit();
852 ///
853 /// let mut array = [0; 1024];
854 /// for (i, place) in array.iter_mut().enumerate() {
855 /// *place = i;
856 /// }
857 ///
858 /// // The optimizer may be able to elide this copy, so previous code writes
859 /// // to heap directly.
860 /// let big_box = Box::write(big_box, array);
861 ///
862 /// for (i, x) in big_box.iter().enumerate() {
863 /// assert_eq!(*x, i);
864 /// }
865 /// ```
866 #[unstable(feature = "new_uninit", issue = "63291")]
867 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
868 #[inline]
869 pub const fn write(mut boxed: Self, value: T) -> Box<T, A> {
870 unsafe {
871 (*boxed).write(value);
872 boxed.assume_init()
873 }
874 }
875}
876
877impl<T, A: Allocator> Box<[mem::MaybeUninit<T>], A> {
878 /// Converts to `Box<[T], A>`.
879 ///
880 /// # Safety
881 ///
882 /// As with [`MaybeUninit::assume_init`],
883 /// it is up to the caller to guarantee that the values
884 /// really are in an initialized state.
885 /// Calling this when the content is not yet fully initialized
886 /// causes immediate undefined behavior.
887 ///
888 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
889 ///
890 /// # Examples
891 ///
892 /// ```
893 /// #![feature(new_uninit)]
894 ///
895 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
896 ///
897 /// let values = unsafe {
898 /// // Deferred initialization:
899 /// values[0].as_mut_ptr().write(1);
900 /// values[1].as_mut_ptr().write(2);
901 /// values[2].as_mut_ptr().write(3);
902 ///
903 /// values.assume_init()
904 /// };
905 ///
906 /// assert_eq!(*values, [1, 2, 3])
907 /// ```
908 #[unstable(feature = "new_uninit", issue = "63291")]
909 #[inline]
910 pub unsafe fn assume_init(self) -> Box<[T], A> {
911 let (raw, alloc) = Box::into_raw_with_allocator(self);
912 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
913 }
914}
915
916impl<T: ?Sized> Box<T> {
917 /// Constructs a box from a raw pointer.
918 ///
919 /// After calling this function, the raw pointer is owned by the
920 /// resulting `Box`. Specifically, the `Box` destructor will call
921 /// the destructor of `T` and free the allocated memory. For this
922 /// to be safe, the memory must have been allocated in accordance
923 /// with the [memory layout] used by `Box` .
924 ///
925 /// # Safety
926 ///
927 /// This function is unsafe because improper use may lead to
928 /// memory problems. For example, a double-free may occur if the
929 /// function is called twice on the same raw pointer.
930 ///
931 /// The safety conditions are described in the [memory layout] section.
932 ///
933 /// # Examples
934 ///
935 /// Recreate a `Box` which was previously converted to a raw pointer
936 /// using [`Box::into_raw`]:
937 /// ```
938 /// let x = Box::new(5);
939 /// let ptr = Box::into_raw(x);
940 /// let x = unsafe { Box::from_raw(ptr) };
941 /// ```
942 /// Manually create a `Box` from scratch by using the global allocator:
943 /// ```
944 /// use std::alloc::{alloc, Layout};
945 ///
946 /// unsafe {
947 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
948 /// // In general .write is required to avoid attempting to destruct
949 /// // the (uninitialized) previous contents of `ptr`, though for this
950 /// // simple example `*ptr = 5` would have worked as well.
951 /// ptr.write(5);
952 /// let x = Box::from_raw(ptr);
953 /// }
954 /// ```
955 ///
956 /// [memory layout]: self#memory-layout
957 /// [`Layout`]: crate::Layout
958 #[stable(feature = "box_raw", since = "1.4.0")]
959 #[inline]
960 #[must_use = "call `drop(Box::from_raw(ptr))` if you intend to drop the `Box`"]
961 pub unsafe fn from_raw(raw: *mut T) -> Self {
962 unsafe { Self::from_raw_in(raw, Global) }
963 }
964}
965
966impl<T: ?Sized, A: Allocator> Box<T, A> {
967 /// Constructs a box from a raw pointer in the given allocator.
968 ///
969 /// After calling this function, the raw pointer is owned by the
970 /// resulting `Box`. Specifically, the `Box` destructor will call
971 /// the destructor of `T` and free the allocated memory. For this
972 /// to be safe, the memory must have been allocated in accordance
973 /// with the [memory layout] used by `Box` .
974 ///
975 /// # Safety
976 ///
977 /// This function is unsafe because improper use may lead to
978 /// memory problems. For example, a double-free may occur if the
979 /// function is called twice on the same raw pointer.
980 ///
981 ///
982 /// # Examples
983 ///
984 /// Recreate a `Box` which was previously converted to a raw pointer
985 /// using [`Box::into_raw_with_allocator`]:
986 /// ```
987 /// #![feature(allocator_api)]
988 ///
989 /// use std::alloc::System;
990 ///
991 /// let x = Box::new_in(5, System);
992 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
993 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
994 /// ```
995 /// Manually create a `Box` from scratch by using the system allocator:
996 /// ```
997 /// #![feature(allocator_api, slice_ptr_get)]
998 ///
999 /// use std::alloc::{Allocator, Layout, System};
1000 ///
1001 /// unsafe {
1002 /// let ptr = System.allocate(Layout::new::<i32>())?.as_mut_ptr() as *mut i32;
1003 /// // In general .write is required to avoid attempting to destruct
1004 /// // the (uninitialized) previous contents of `ptr`, though for this
1005 /// // simple example `*ptr = 5` would have worked as well.
1006 /// ptr.write(5);
1007 /// let x = Box::from_raw_in(ptr, System);
1008 /// }
1009 /// # Ok::<(), std::alloc::AllocError>(())
1010 /// ```
1011 ///
1012 /// [memory layout]: self#memory-layout
1013 /// [`Layout`]: crate::Layout
1014 #[unstable(feature = "allocator_api", issue = "32838")]
1015 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1016 #[inline]
1017 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1018 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1019 }
1020
1021 /// Consumes the `Box`, returning a wrapped raw pointer.
1022 ///
1023 /// The pointer will be properly aligned and non-null.
1024 ///
1025 /// After calling this function, the caller is responsible for the
1026 /// memory previously managed by the `Box`. In particular, the
1027 /// caller should properly destroy `T` and release the memory, taking
1028 /// into account the [memory layout] used by `Box`. The easiest way to
1029 /// do this is to convert the raw pointer back into a `Box` with the
1030 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1031 /// the cleanup.
1032 ///
1033 /// Note: this is an associated function, which means that you have
1034 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1035 /// is so that there is no conflict with a method on the inner type.
1036 ///
1037 /// # Examples
1038 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1039 /// for automatic cleanup:
1040 /// ```
1041 /// let x = Box::new(String::from("Hello"));
1042 /// let ptr = Box::into_raw(x);
1043 /// let x = unsafe { Box::from_raw(ptr) };
1044 /// ```
1045 /// Manual cleanup by explicitly running the destructor and deallocating
1046 /// the memory:
1047 /// ```
1048 /// use std::alloc::{dealloc, Layout};
1049 /// use std::ptr;
1050 ///
1051 /// let x = Box::new(String::from("Hello"));
1052 /// let p = Box::into_raw(x);
1053 /// unsafe {
1054 /// ptr::drop_in_place(p);
1055 /// dealloc(p as *mut u8, Layout::new::<String>());
1056 /// }
1057 /// ```
1058 ///
1059 /// [memory layout]: self#memory-layout
1060 #[stable(feature = "box_raw", since = "1.4.0")]
1061 #[inline]
1062 pub fn into_raw(b: Self) -> *mut T {
1063 Self::into_raw_with_allocator(b).0
1064 }
1065
1066 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1067 ///
1068 /// The pointer will be properly aligned and non-null.
1069 ///
1070 /// After calling this function, the caller is responsible for the
1071 /// memory previously managed by the `Box`. In particular, the
1072 /// caller should properly destroy `T` and release the memory, taking
1073 /// into account the [memory layout] used by `Box`. The easiest way to
1074 /// do this is to convert the raw pointer back into a `Box` with the
1075 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1076 /// the cleanup.
1077 ///
1078 /// Note: this is an associated function, which means that you have
1079 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1080 /// is so that there is no conflict with a method on the inner type.
1081 ///
1082 /// # Examples
1083 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1084 /// for automatic cleanup:
1085 /// ```
1086 /// #![feature(allocator_api)]
1087 ///
1088 /// use std::alloc::System;
1089 ///
1090 /// let x = Box::new_in(String::from("Hello"), System);
1091 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1092 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1093 /// ```
1094 /// Manual cleanup by explicitly running the destructor and deallocating
1095 /// the memory:
1096 /// ```
1097 /// #![feature(allocator_api)]
1098 ///
1099 /// use std::alloc::{Allocator, Layout, System};
1100 /// use std::ptr::{self, NonNull};
1101 ///
1102 /// let x = Box::new_in(String::from("Hello"), System);
1103 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1104 /// unsafe {
1105 /// ptr::drop_in_place(ptr);
1106 /// let non_null = NonNull::new_unchecked(ptr);
1107 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1108 /// }
1109 /// ```
1110 ///
1111 /// [memory layout]: self#memory-layout
1112 #[unstable(feature = "allocator_api", issue = "32838")]
1113 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1114 #[inline]
1115 pub const fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1116 let (leaked, alloc) = Box::into_unique(b);
1117 (leaked.as_ptr(), alloc)
1118 }
1119
1120 #[unstable(
1121 feature = "ptr_internals",
1122 issue = "none",
1123 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
1124 )]
1125 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1126 #[inline]
1127 #[doc(hidden)]
1128 pub const fn into_unique(b: Self) -> (Unique<T>, A) {
1129 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1130 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1131 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1132 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1133 // behaves correctly.
1134 let alloc = unsafe { ptr::read(&b.1) };
1135 (Unique::from(Box::leak(b)), alloc)
1136 }
1137
1138 /// Returns a reference to the underlying allocator.
1139 ///
1140 /// Note: this is an associated function, which means that you have
1141 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1142 /// is so that there is no conflict with a method on the inner type.
1143 #[unstable(feature = "allocator_api", issue = "32838")]
1144 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1145 #[inline]
1146 pub const fn allocator(b: &Self) -> &A {
1147 &b.1
1148 }
1149
1150 /// Consumes and leaks the `Box`, returning a mutable reference,
1151 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1152 /// `'a`. If the type has only static references, or none at all, then this
1153 /// may be chosen to be `'static`.
1154 ///
1155 /// This function is mainly useful for data that lives for the remainder of
1156 /// the program's life. Dropping the returned reference will cause a memory
1157 /// leak. If this is not acceptable, the reference should first be wrapped
1158 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1159 /// then be dropped which will properly destroy `T` and release the
1160 /// allocated memory.
1161 ///
1162 /// Note: this is an associated function, which means that you have
1163 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1164 /// is so that there is no conflict with a method on the inner type.
1165 ///
1166 /// # Examples
1167 ///
1168 /// Simple usage:
1169 ///
1170 /// ```
1171 /// let x = Box::new(41);
1172 /// let static_ref: &'static mut usize = Box::leak(x);
1173 /// *static_ref += 1;
1174 /// assert_eq!(*static_ref, 42);
1175 /// ```
1176 ///
1177 /// Unsized data:
1178 ///
1179 /// ```
1180 /// let x = vec![1, 2, 3].into_boxed_slice();
1181 /// let static_ref = Box::leak(x);
1182 /// static_ref[0] = 4;
1183 /// assert_eq!(*static_ref, [4, 2, 3]);
1184 /// ```
1185 #[stable(feature = "box_leak", since = "1.26.0")]
1186 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1187 #[inline]
1188 pub const fn leak<'a>(b: Self) -> &'a mut T
1189 where
1190 A: 'a,
1191 {
1192 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1193 }
1194
1195 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1196 /// `*boxed` will be pinned in memory and unable to be moved.
1197 ///
1198 /// This conversion does not allocate on the heap and happens in place.
1199 ///
1200 /// This is also available via [`From`].
1201 ///
1202 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1203 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1204 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1205 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1206 ///
1207 /// # Notes
1208 ///
1209 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1210 /// as it'll introduce an ambiguity when calling `Pin::from`.
1211 /// A demonstration of such a poor impl is shown below.
1212 ///
1213 /// ```compile_fail
1214 /// # use std::pin::Pin;
1215 /// struct Foo; // A type defined in this crate.
1216 /// impl From<Box<()>> for Pin<Foo> {
1217 /// fn from(_: Box<()>) -> Pin<Foo> {
1218 /// Pin::new(Foo)
1219 /// }
1220 /// }
1221 ///
1222 /// let foo = Box::new(());
1223 /// let bar = Pin::from(foo);
1224 /// ```
1225 #[stable(feature = "box_into_pin", since = "1.63.0")]
1226 #[rustc_const_unstable(feature = "const_box", issue = "92521")]
1227 pub const fn into_pin(boxed: Self) -> Pin<Self>
1228 where
1229 A: 'static,
1230 {
1231 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1232 // when `T: !Unpin`, so it's safe to pin it directly without any
1233 // additional requirements.
1234 unsafe { Pin::new_unchecked(boxed) }
1235 }
1236}
1237
1238#[stable(feature = "rust1", since = "1.0.0")]
1239unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
1240 fn drop(&mut self) {
1241 // FIXME: Do nothing, drop is currently performed by compiler.
1242 }
1243}
1244
1245#[cfg(not(no_global_oom_handling))]
1246#[stable(feature = "rust1", since = "1.0.0")]
1247impl<T: Default> Default for Box<T> {
1248 /// Creates a `Box<T>`, with the `Default` value for T.
1249 fn default() -> Self {
1250 #[rustc_box]
1251 Box::new(T::default())
1252 }
1253}
1254
1255#[cfg(not(no_global_oom_handling))]
1256#[stable(feature = "rust1", since = "1.0.0")]
1257#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1258impl<T> const Default for Box<[T]> {
1259 fn default() -> Self {
1260 let ptr: Unique<[T]> = Unique::<[T; 0]>::dangling();
1261 Box(ptr, Global)
1262 }
1263}
1264
1265#[cfg(not(no_global_oom_handling))]
1266#[stable(feature = "default_box_extra", since = "1.17.0")]
1267#[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
1268impl const Default for Box<str> {
1269 fn default() -> Self {
1270 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1271 let ptr: Unique<str> = unsafe {
1272 let bytes: Unique<[u8]> = Unique::<[u8; 0]>::dangling();
1273 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1274 };
1275 Box(ptr, Global)
1276 }
1277}
1278
1279#[cfg(not(no_global_oom_handling))]
1280#[stable(feature = "rust1", since = "1.0.0")]
1281impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1282 /// Returns a new box with a `clone()` of this box's contents.
1283 ///
1284 /// # Examples
1285 ///
1286 /// ```
1287 /// let x = Box::new(5);
1288 /// let y = x.clone();
1289 ///
1290 /// // The value is the same
1291 /// assert_eq!(x, y);
1292 ///
1293 /// // But they are unique objects
1294 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1295 /// ```
1296 #[inline]
1297 fn clone(&self) -> Self {
1298 // Pre-allocate memory to allow writing the cloned value directly.
1299 let mut boxed = Self::new_uninit_in(self.1.clone());
1300 unsafe {
1301 (**self).write_clone_into_raw(boxed.as_mut_ptr());
1302 boxed.assume_init()
1303 }
1304 }
1305
1306 /// Copies `source`'s contents into `self` without creating a new allocation.
1307 ///
1308 /// # Examples
1309 ///
1310 /// ```
1311 /// let x = Box::new(5);
1312 /// let mut y = Box::new(10);
1313 /// let yp: *const i32 = &*y;
1314 ///
1315 /// y.clone_from(&x);
1316 ///
1317 /// // The value is the same
1318 /// assert_eq!(x, y);
1319 ///
1320 /// // And no allocation occurred
1321 /// assert_eq!(yp, &*y);
1322 /// ```
1323 #[inline]
1324 fn clone_from(&mut self, source: &Self) {
1325 (**self).clone_from(&(**source));
1326 }
1327}
1328
1329#[cfg(not(no_global_oom_handling))]
1330#[stable(feature = "box_slice_clone", since = "1.3.0")]
1331impl Clone for Box<str> {
1332 fn clone(&self) -> Self {
1333 // this makes a copy of the data
1334 let buf: Box<[u8]> = self.as_bytes().into();
1335 unsafe { from_boxed_utf8_unchecked(buf) }
1336 }
1337}
1338
1339#[stable(feature = "rust1", since = "1.0.0")]
1340impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1341 #[inline]
1342 fn eq(&self, other: &Self) -> bool {
1343 PartialEq::eq(&**self, &**other)
1344 }
1345 #[inline]
1346 fn ne(&self, other: &Self) -> bool {
1347 PartialEq::ne(&**self, &**other)
1348 }
1349}
1350#[stable(feature = "rust1", since = "1.0.0")]
1351impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1352 #[inline]
1353 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1354 PartialOrd::partial_cmp(&**self, &**other)
1355 }
1356 #[inline]
1357 fn lt(&self, other: &Self) -> bool {
1358 PartialOrd::lt(&**self, &**other)
1359 }
1360 #[inline]
1361 fn le(&self, other: &Self) -> bool {
1362 PartialOrd::le(&**self, &**other)
1363 }
1364 #[inline]
1365 fn ge(&self, other: &Self) -> bool {
1366 PartialOrd::ge(&**self, &**other)
1367 }
1368 #[inline]
1369 fn gt(&self, other: &Self) -> bool {
1370 PartialOrd::gt(&**self, &**other)
1371 }
1372}
1373#[stable(feature = "rust1", since = "1.0.0")]
1374impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1375 #[inline]
1376 fn cmp(&self, other: &Self) -> Ordering {
1377 Ord::cmp(&**self, &**other)
1378 }
1379}
1380#[stable(feature = "rust1", since = "1.0.0")]
1381impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1382
1383#[stable(feature = "rust1", since = "1.0.0")]
1384impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1385 fn hash<H: Hasher>(&self, state: &mut H) {
1386 (**self).hash(state);
1387 }
1388}
1389
1390#[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
1391impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1392 fn finish(&self) -> u64 {
1393 (**self).finish()
1394 }
1395 fn write(&mut self, bytes: &[u8]) {
1396 (**self).write(bytes)
1397 }
1398 fn write_u8(&mut self, i: u8) {
1399 (**self).write_u8(i)
1400 }
1401 fn write_u16(&mut self, i: u16) {
1402 (**self).write_u16(i)
1403 }
1404 fn write_u32(&mut self, i: u32) {
1405 (**self).write_u32(i)
1406 }
1407 fn write_u64(&mut self, i: u64) {
1408 (**self).write_u64(i)
1409 }
1410 fn write_u128(&mut self, i: u128) {
1411 (**self).write_u128(i)
1412 }
1413 fn write_usize(&mut self, i: usize) {
1414 (**self).write_usize(i)
1415 }
1416 fn write_i8(&mut self, i: i8) {
1417 (**self).write_i8(i)
1418 }
1419 fn write_i16(&mut self, i: i16) {
1420 (**self).write_i16(i)
1421 }
1422 fn write_i32(&mut self, i: i32) {
1423 (**self).write_i32(i)
1424 }
1425 fn write_i64(&mut self, i: i64) {
1426 (**self).write_i64(i)
1427 }
1428 fn write_i128(&mut self, i: i128) {
1429 (**self).write_i128(i)
1430 }
1431 fn write_isize(&mut self, i: isize) {
1432 (**self).write_isize(i)
1433 }
1434 fn write_length_prefix(&mut self, len: usize) {
1435 (**self).write_length_prefix(len)
1436 }
1437 fn write_str(&mut self, s: &str) {
1438 (**self).write_str(s)
1439 }
1440}
1441
1442#[cfg(not(no_global_oom_handling))]
1443#[stable(feature = "from_for_ptrs", since = "1.6.0")]
1444impl<T> From<T> for Box<T> {
1445 /// Converts a `T` into a `Box<T>`
1446 ///
1447 /// The conversion allocates on the heap and moves `t`
1448 /// from the stack into it.
1449 ///
1450 /// # Examples
1451 ///
1452 /// ```rust
1453 /// let x = 5;
1454 /// let boxed = Box::new(5);
1455 ///
1456 /// assert_eq!(Box::from(x), boxed);
1457 /// ```
1458 fn from(t: T) -> Self {
1459 Box::new(t)
1460 }
1461}
1462
1463#[stable(feature = "pin", since = "1.33.0")]
1464#[rustc_const_unstable(feature = "const_box", issue = "92521")]
1465impl<T: ?Sized, A: Allocator> const From<Box<T, A>> for Pin<Box<T, A>>
1466where
1467 A: 'static,
1468{
1469 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1470 /// `*boxed` will be pinned in memory and unable to be moved.
1471 ///
1472 /// This conversion does not allocate on the heap and happens in place.
1473 ///
1474 /// This is also available via [`Box::into_pin`].
1475 ///
1476 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
1477 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1478 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
1479 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1480 fn from(boxed: Box<T, A>) -> Self {
1481 Box::into_pin(boxed)
1482 }
1483}
1484
1485#[cfg(not(no_global_oom_handling))]
1486#[stable(feature = "box_from_slice", since = "1.17.0")]
1487impl<T: Copy> From<&[T]> for Box<[T]> {
1488 /// Converts a `&[T]` into a `Box<[T]>`
1489 ///
1490 /// This conversion allocates on the heap
1491 /// and performs a copy of `slice` and its contents.
1492 ///
1493 /// # Examples
1494 /// ```rust
1495 /// // create a &[u8] which will be used to create a Box<[u8]>
1496 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1497 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1498 ///
1499 /// println!("{boxed_slice:?}");
1500 /// ```
1501 fn from(slice: &[T]) -> Box<[T]> {
1502 let len = slice.len();
1503 let buf = RawVec::with_capacity(len);
1504 unsafe {
1505 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1506 buf.into_box(slice.len()).assume_init()
1507 }
1508 }
1509}
1510
1511#[cfg(not(no_global_oom_handling))]
1512#[stable(feature = "box_from_cow", since = "1.45.0")]
1513impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1514 /// Converts a `Cow<'_, [T]>` into a `Box<[T]>`
1515 ///
1516 /// When `cow` is the `Cow::Borrowed` variant, this
1517 /// conversion allocates on the heap and copies the
1518 /// underlying slice. Otherwise, it will try to reuse the owned
1519 /// `Vec`'s allocation.
1520 #[inline]
1521 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1522 match cow {
1523 Cow::Borrowed(slice) => Box::from(slice),
1524 Cow::Owned(slice) => Box::from(slice),
1525 }
1526 }
1527}
1528
1529#[cfg(not(no_global_oom_handling))]
1530#[stable(feature = "box_from_slice", since = "1.17.0")]
1531impl From<&str> for Box<str> {
1532 /// Converts a `&str` into a `Box<str>`
1533 ///
1534 /// This conversion allocates on the heap
1535 /// and performs a copy of `s`.
1536 ///
1537 /// # Examples
1538 ///
1539 /// ```rust
1540 /// let boxed: Box<str> = Box::from("hello");
1541 /// println!("{boxed}");
1542 /// ```
1543 #[inline]
1544 fn from(s: &str) -> Box<str> {
1545 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1546 }
1547}
1548
1549#[cfg(not(no_global_oom_handling))]
1550#[stable(feature = "box_from_cow", since = "1.45.0")]
1551impl From<Cow<'_, str>> for Box<str> {
1552 /// Converts a `Cow<'_, str>` into a `Box<str>`
1553 ///
1554 /// When `cow` is the `Cow::Borrowed` variant, this
1555 /// conversion allocates on the heap and copies the
1556 /// underlying `str`. Otherwise, it will try to reuse the owned
1557 /// `String`'s allocation.
1558 ///
1559 /// # Examples
1560 ///
1561 /// ```rust
1562 /// use std::borrow::Cow;
1563 ///
1564 /// let unboxed = Cow::Borrowed("hello");
1565 /// let boxed: Box<str> = Box::from(unboxed);
1566 /// println!("{boxed}");
1567 /// ```
1568 ///
1569 /// ```rust
1570 /// # use std::borrow::Cow;
1571 /// let unboxed = Cow::Owned("hello".to_string());
1572 /// let boxed: Box<str> = Box::from(unboxed);
1573 /// println!("{boxed}");
1574 /// ```
1575 #[inline]
1576 fn from(cow: Cow<'_, str>) -> Box<str> {
1577 match cow {
1578 Cow::Borrowed(s) => Box::from(s),
1579 Cow::Owned(s) => Box::from(s),
1580 }
1581 }
1582}
1583
1584#[stable(feature = "boxed_str_conv", since = "1.19.0")]
1585impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1586 /// Converts a `Box<str>` into a `Box<[u8]>`
1587 ///
1588 /// This conversion does not allocate on the heap and happens in place.
1589 ///
1590 /// # Examples
1591 /// ```rust
1592 /// // create a Box<str> which will be used to create a Box<[u8]>
1593 /// let boxed: Box<str> = Box::from("hello");
1594 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1595 ///
1596 /// // create a &[u8] which will be used to create a Box<[u8]>
1597 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1598 /// let boxed_slice = Box::from(slice);
1599 ///
1600 /// assert_eq!(boxed_slice, boxed_str);
1601 /// ```
1602 #[inline]
1603 fn from(s: Box<str, A>) -> Self {
1604 let (raw, alloc) = Box::into_raw_with_allocator(s);
1605 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1606 }
1607}
1608
1609#[cfg(not(no_global_oom_handling))]
1610#[stable(feature = "box_from_array", since = "1.45.0")]
1611impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1612 /// Converts a `[T; N]` into a `Box<[T]>`
1613 ///
1614 /// This conversion moves the array to newly heap-allocated memory.
1615 ///
1616 /// # Examples
1617 ///
1618 /// ```rust
1619 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1620 /// println!("{boxed:?}");
1621 /// ```
1622 fn from(array: [T; N]) -> Box<[T]> {
1623 #[rustc_box]
1624 Box::new(array)
1625 }
1626}
1627
1628/// Casts a boxed slice to a boxed array.
1629///
1630/// # Safety
1631///
1632/// `boxed_slice.len()` must be exactly `N`.
1633unsafe fn boxed_slice_as_array_unchecked<T, A: Allocator, const N: usize>(
1634 boxed_slice: Box<[T], A>,
1635) -> Box<[T; N], A> {
1636 debug_assert_eq!(boxed_slice.len(), N);
1637
1638 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
1639 // SAFETY: Pointer and allocator came from an existing box,
1640 // and our safety condition requires that the length is exactly `N`
1641 unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) }
1642}
1643
1644#[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1645impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1646 type Error = Box<[T]>;
1647
1648 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1649 ///
1650 /// The conversion occurs in-place and does not require a
1651 /// new memory allocation.
1652 ///
1653 /// # Errors
1654 ///
1655 /// Returns the old `Box<[T]>` in the `Err` variant if
1656 /// `boxed_slice.len()` does not equal `N`.
1657 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1658 if boxed_slice.len() == N {
1659 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1660 } else {
1661 Err(boxed_slice)
1662 }
1663 }
1664}
1665
1666#[cfg(not(no_global_oom_handling))]
1667#[stable(feature = "boxed_array_try_from_vec", since = "1.66.0")]
1668impl<T, const N: usize> TryFrom<Vec<T>> for Box<[T; N]> {
1669 type Error = Vec<T>;
1670
1671 /// Attempts to convert a `Vec<T>` into a `Box<[T; N]>`.
1672 ///
1673 /// Like [`Vec::into_boxed_slice`], this is in-place if `vec.capacity() == N`,
1674 /// but will require a reallocation otherwise.
1675 ///
1676 /// # Errors
1677 ///
1678 /// Returns the original `Vec<T>` in the `Err` variant if
1679 /// `boxed_slice.len()` does not equal `N`.
1680 ///
1681 /// # Examples
1682 ///
1683 /// This can be used with [`vec!`] to create an array on the heap:
1684 ///
1685 /// ```
1686 /// let state: Box<[f32; 100]> = vec![1.0; 100].try_into().unwrap();
1687 /// assert_eq!(state.len(), 100);
1688 /// ```
1689 fn try_from(vec: Vec<T>) -> Result<Self, Self::Error> {
1690 if vec.len() == N {
1691 let boxed_slice = vec.into_boxed_slice();
1692 Ok(unsafe { boxed_slice_as_array_unchecked(boxed_slice) })
1693 } else {
1694 Err(vec)
1695 }
1696 }
1697}
1698
1699impl<A: Allocator> Box<dyn Any, A> {
1700 /// Attempt to downcast the box to a concrete type.
1701 ///
1702 /// # Examples
1703 ///
1704 /// ```
1705 /// use std::any::Any;
1706 ///
1707 /// fn print_if_string(value: Box<dyn Any>) {
1708 /// if let Ok(string) = value.downcast::<String>() {
1709 /// println!("String ({}): {}", string.len(), string);
1710 /// }
1711 /// }
1712 ///
1713 /// let my_string = "Hello World".to_string();
1714 /// print_if_string(Box::new(my_string));
1715 /// print_if_string(Box::new(0i8));
1716 /// ```
1717 #[inline]
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1720 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1721 }
1722
1723 /// Downcasts the box to a concrete type.
1724 ///
1725 /// For a safe alternative see [`downcast`].
1726 ///
1727 /// # Examples
1728 ///
1729 /// ```
1730 /// #![feature(downcast_unchecked)]
1731 ///
1732 /// use std::any::Any;
1733 ///
1734 /// let x: Box<dyn Any> = Box::new(1_usize);
1735 ///
1736 /// unsafe {
1737 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1738 /// }
1739 /// ```
1740 ///
1741 /// # Safety
1742 ///
1743 /// The contained value must be of type `T`. Calling this method
1744 /// with the incorrect type is *undefined behavior*.
1745 ///
1746 /// [`downcast`]: Self::downcast
1747 #[inline]
1748 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1749 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1750 debug_assert!(self.is::<T>());
1751 unsafe {
1752 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
1753 Box::from_raw_in(raw as *mut T, alloc)
1754 }
1755 }
1756}
1757
1758impl<A: Allocator> Box<dyn Any + Send, A> {
1759 /// Attempt to downcast the box to a concrete type.
1760 ///
1761 /// # Examples
1762 ///
1763 /// ```
1764 /// use std::any::Any;
1765 ///
1766 /// fn print_if_string(value: Box<dyn Any + Send>) {
1767 /// if let Ok(string) = value.downcast::<String>() {
1768 /// println!("String ({}): {}", string.len(), string);
1769 /// }
1770 /// }
1771 ///
1772 /// let my_string = "Hello World".to_string();
1773 /// print_if_string(Box::new(my_string));
1774 /// print_if_string(Box::new(0i8));
1775 /// ```
1776 #[inline]
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1779 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1780 }
1781
1782 /// Downcasts the box to a concrete type.
1783 ///
1784 /// For a safe alternative see [`downcast`].
1785 ///
1786 /// # Examples
1787 ///
1788 /// ```
1789 /// #![feature(downcast_unchecked)]
1790 ///
1791 /// use std::any::Any;
1792 ///
1793 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
1794 ///
1795 /// unsafe {
1796 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1797 /// }
1798 /// ```
1799 ///
1800 /// # Safety
1801 ///
1802 /// The contained value must be of type `T`. Calling this method
1803 /// with the incorrect type is *undefined behavior*.
1804 ///
1805 /// [`downcast`]: Self::downcast
1806 #[inline]
1807 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1808 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1809 debug_assert!(self.is::<T>());
1810 unsafe {
1811 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
1812 Box::from_raw_in(raw as *mut T, alloc)
1813 }
1814 }
1815}
1816
1817impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
1818 /// Attempt to downcast the box to a concrete type.
1819 ///
1820 /// # Examples
1821 ///
1822 /// ```
1823 /// use std::any::Any;
1824 ///
1825 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
1826 /// if let Ok(string) = value.downcast::<String>() {
1827 /// println!("String ({}): {}", string.len(), string);
1828 /// }
1829 /// }
1830 ///
1831 /// let my_string = "Hello World".to_string();
1832 /// print_if_string(Box::new(my_string));
1833 /// print_if_string(Box::new(0i8));
1834 /// ```
1835 #[inline]
1836 #[stable(feature = "box_send_sync_any_downcast", since = "1.51.0")]
1837 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1838 if self.is::<T>() { unsafe { Ok(self.downcast_unchecked::<T>()) } } else { Err(self) }
1839 }
1840
1841 /// Downcasts the box to a concrete type.
1842 ///
1843 /// For a safe alternative see [`downcast`].
1844 ///
1845 /// # Examples
1846 ///
1847 /// ```
1848 /// #![feature(downcast_unchecked)]
1849 ///
1850 /// use std::any::Any;
1851 ///
1852 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
1853 ///
1854 /// unsafe {
1855 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1856 /// }
1857 /// ```
1858 ///
1859 /// # Safety
1860 ///
1861 /// The contained value must be of type `T`. Calling this method
1862 /// with the incorrect type is *undefined behavior*.
1863 ///
1864 /// [`downcast`]: Self::downcast
1865 #[inline]
1866 #[unstable(feature = "downcast_unchecked", issue = "90850")]
1867 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
1868 debug_assert!(self.is::<T>());
1869 unsafe {
1870 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
1871 Box::into_raw_with_allocator(self);
1872 Box::from_raw_in(raw as *mut T, alloc)
1873 }
1874 }
1875}
1876
1877#[stable(feature = "rust1", since = "1.0.0")]
1878impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
1879 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1880 fmt::Display::fmt(&**self, f)
1881 }
1882}
1883
1884#[stable(feature = "rust1", since = "1.0.0")]
1885impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
1886 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1887 fmt::Debug::fmt(&**self, f)
1888 }
1889}
1890
1891#[stable(feature = "rust1", since = "1.0.0")]
1892impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
1893 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1894 // It's not possible to extract the inner Uniq directly from the Box,
1895 // instead we cast it to a *const which aliases the Unique
1896 let ptr: *const T = &**self;
1897 fmt::Pointer::fmt(&ptr, f)
1898 }
1899}
1900
1901#[stable(feature = "rust1", since = "1.0.0")]
1902#[rustc_const_unstable(feature = "const_box", issue = "92521")]
1903impl<T: ?Sized, A: Allocator> const Deref for Box<T, A> {
1904 type Target = T;
1905
1906 fn deref(&self) -> &T {
1907 &**self
1908 }
1909}
1910
1911#[stable(feature = "rust1", since = "1.0.0")]
1912#[rustc_const_unstable(feature = "const_box", issue = "92521")]
1913impl<T: ?Sized, A: Allocator> const DerefMut for Box<T, A> {
1914 fn deref_mut(&mut self) -> &mut T {
1915 &mut **self
1916 }
1917}
1918
1919#[unstable(feature = "receiver_trait", issue = "none")]
1920impl<T: ?Sized, A: Allocator> Receiver for Box<T, A> {}
1921
1922#[stable(feature = "rust1", since = "1.0.0")]
1923impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
1924 type Item = I::Item;
1925 fn next(&mut self) -> Option<I::Item> {
1926 (**self).next()
1927 }
1928 fn size_hint(&self) -> (usize, Option<usize>) {
1929 (**self).size_hint()
1930 }
1931 fn nth(&mut self, n: usize) -> Option<I::Item> {
1932 (**self).nth(n)
1933 }
1934 fn last(self) -> Option<I::Item> {
1935 BoxIter::last(self)
1936 }
1937}
1938
1939trait BoxIter {
1940 type Item;
1941 fn last(self) -> Option<Self::Item>;
1942}
1943
1944impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
1945 type Item = I::Item;
1946 default fn last(self) -> Option<I::Item> {
1947 #[inline]
1948 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1949 Some(x)
1950 }
1951
1952 self.fold(None, some)
1953 }
1954}
1955
1956/// Specialization for sized `I`s that uses `I`s implementation of `last()`
1957/// instead of the default.
1958#[stable(feature = "rust1", since = "1.0.0")]
1959impl<I: Iterator, A: Allocator> BoxIter for Box<I, A> {
1960 fn last(self) -> Option<I::Item> {
1961 (*self).last()
1962 }
1963}
1964
1965#[stable(feature = "rust1", since = "1.0.0")]
1966impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
1967 fn next_back(&mut self) -> Option<I::Item> {
1968 (**self).next_back()
1969 }
1970 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1971 (**self).nth_back(n)
1972 }
1973}
1974#[stable(feature = "rust1", since = "1.0.0")]
1975impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
1976 fn len(&self) -> usize {
1977 (**self).len()
1978 }
1979 fn is_empty(&self) -> bool {
1980 (**self).is_empty()
1981 }
1982}
1983
1984#[stable(feature = "fused", since = "1.26.0")]
1985impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
1986
1987#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1988impl<Args: Tuple, F: FnOnce<Args> + ?Sized, A: Allocator> FnOnce<Args> for Box<F, A> {
1989 type Output = <F as FnOnce<Args>>::Output;
1990
1991 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1992 <F as FnOnce<Args>>::call_once(*self, args)
1993 }
1994}
1995
1996#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1997impl<Args: Tuple, F: FnMut<Args> + ?Sized, A: Allocator> FnMut<Args> for Box<F, A> {
1998 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1999 <F as FnMut<Args>>::call_mut(self, args)
2000 }
2001}
2002
2003#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
2004impl<Args: Tuple, F: Fn<Args> + ?Sized, A: Allocator> Fn<Args> for Box<F, A> {
2005 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
2006 <F as Fn<Args>>::call(self, args)
2007 }
2008}
2009
2010#[unstable(feature = "coerce_unsized", issue = "18598")]
2011impl<T: ?Sized + Unsize<U>, U: ?Sized, A: Allocator> CoerceUnsized<Box<U, A>> for Box<T, A> {}
2012
2013#[unstable(feature = "dispatch_from_dyn", issue = "none")]
2014impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
2015
2016#[cfg(not(no_global_oom_handling))]
2017#[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
2018impl<I> FromIterator<I> for Box<[I]> {
2019 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
2020 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
2021 }
2022}
2023
2024#[cfg(not(no_global_oom_handling))]
2025#[stable(feature = "box_slice_clone", since = "1.3.0")]
2026impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2027 fn clone(&self) -> Self {
2028 let alloc = Box::allocator(self).clone();
2029 self.to_vec_in(alloc).into_boxed_slice()
2030 }
2031
2032 fn clone_from(&mut self, other: &Self) {
2033 if self.len() == other.len() {
2034 self.clone_from_slice(&other);
2035 } else {
2036 *self = other.clone();
2037 }
2038 }
2039}
2040
2041#[stable(feature = "box_borrow", since = "1.1.0")]
2042impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
2043 fn borrow(&self) -> &T {
2044 &**self
2045 }
2046}
2047
2048#[stable(feature = "box_borrow", since = "1.1.0")]
2049impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
2050 fn borrow_mut(&mut self) -> &mut T {
2051 &mut **self
2052 }
2053}
2054
2055#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2056impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2057 fn as_ref(&self) -> &T {
2058 &**self
2059 }
2060}
2061
2062#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
2063impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2064 fn as_mut(&mut self) -> &mut T {
2065 &mut **self
2066 }
2067}
2068
2069/* Nota bene
2070 *
2071 * We could have chosen not to add this impl, and instead have written a
2072 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2073 * because Box<T> implements Unpin even when T does not, as a result of
2074 * this impl.
2075 *
2076 * We chose this API instead of the alternative for a few reasons:
2077 * - Logically, it is helpful to understand pinning in regard to the
2078 * memory region being pointed to. For this reason none of the
2079 * standard library pointer types support projecting through a pin
2080 * (Box<T> is the only pointer type in std for which this would be
2081 * safe.)
2082 * - It is in practice very useful to have Box<T> be unconditionally
2083 * Unpin because of trait objects, for which the structural auto
2084 * trait functionality does not apply (e.g., Box<dyn Foo> would
2085 * otherwise not be Unpin).
2086 *
2087 * Another type with the same semantics as Box but only a conditional
2088 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2089 * could have a method to project a Pin<T> from it.
2090 */
2091#[stable(feature = "pin", since = "1.33.0")]
2092impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
2093
2094#[unstable(feature = "generator_trait", issue = "43122")]
2095impl<G: ?Sized + Generator<R> + Unpin, R, A: Allocator> Generator<R> for Box<G, A>
2096where
2097 A: 'static,
2098{
2099 type Yield = G::Yield;
2100 type Return = G::Return;
2101
2102 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2103 G::resume(Pin::new(&mut *self), arg)
2104 }
2105}
2106
2107#[unstable(feature = "generator_trait", issue = "43122")]
2108impl<G: ?Sized + Generator<R>, R, A: Allocator> Generator<R> for Pin<Box<G, A>>
2109where
2110 A: 'static,
2111{
2112 type Yield = G::Yield;
2113 type Return = G::Return;
2114
2115 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
2116 G::resume((*self).as_mut(), arg)
2117 }
2118}
2119
2120#[stable(feature = "futures_api", since = "1.36.0")]
2121impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2122where
2123 A: 'static,
2124{
2125 type Output = F::Output;
2126
2127 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2128 F::poll(Pin::new(&mut *self), cx)
2129 }
2130}
2131
2132#[unstable(feature = "async_iterator", issue = "79024")]
2133impl<S: ?Sized + AsyncIterator + Unpin> AsyncIterator for Box<S> {
2134 type Item = S::Item;
2135
2136 fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
2137 Pin::new(&mut **self).poll_next(cx)
2138 }
2139
2140 fn size_hint(&self) -> (usize, Option<usize>) {
2141 (**self).size_hint()
2142 }
2143}
2144
2145impl dyn Error {
2146 #[inline]
2147 #[stable(feature = "error_downcast", since = "1.3.0")]
2148 #[rustc_allow_incoherent_impl]
2149 /// Attempts to downcast the box to a concrete type.
2150 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error>> {
2151 if self.is::<T>() {
2152 unsafe {
2153 let raw: *mut dyn Error = Box::into_raw(self);
2154 Ok(Box::from_raw(raw as *mut T))
2155 }
2156 } else {
2157 Err(self)
2158 }
2159 }
2160}
2161
2162impl dyn Error + Send {
2163 #[inline]
2164 #[stable(feature = "error_downcast", since = "1.3.0")]
2165 #[rustc_allow_incoherent_impl]
2166 /// Attempts to downcast the box to a concrete type.
2167 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<dyn Error + Send>> {
2168 let err: Box<dyn Error> = self;
2169 <dyn Error>::downcast(err).map_err(|s| unsafe {
2170 // Reapply the `Send` marker.
2171 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send>>(s)
2172 })
2173 }
2174}
2175
2176impl dyn Error + Send + Sync {
2177 #[inline]
2178 #[stable(feature = "error_downcast", since = "1.3.0")]
2179 #[rustc_allow_incoherent_impl]
2180 /// Attempts to downcast the box to a concrete type.
2181 pub fn downcast<T: Error + 'static>(self: Box<Self>) -> Result<Box<T>, Box<Self>> {
2182 let err: Box<dyn Error> = self;
2183 <dyn Error>::downcast(err).map_err(|s| unsafe {
2184 // Reapply the `Send + Sync` marker.
2185 mem::transmute::<Box<dyn Error>, Box<dyn Error + Send + Sync>>(s)
2186 })
2187 }
2188}
2189
2190#[cfg(not(no_global_oom_handling))]
2191#[stable(feature = "rust1", since = "1.0.0")]
2192impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
2193 /// Converts a type of [`Error`] into a box of dyn [`Error`].
2194 ///
2195 /// # Examples
2196 ///
2197 /// ```
2198 /// use std::error::Error;
2199 /// use std::fmt;
2200 /// use std::mem;
2201 ///
2202 /// #[derive(Debug)]
2203 /// struct AnError;
2204 ///
2205 /// impl fmt::Display for AnError {
2206 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2207 /// write!(f, "An error")
2208 /// }
2209 /// }
2210 ///
2211 /// impl Error for AnError {}
2212 ///
2213 /// let an_error = AnError;
2214 /// assert!(0 == mem::size_of_val(&an_error));
2215 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
2216 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2217 /// ```
2218 fn from(err: E) -> Box<dyn Error + 'a> {
2219 Box::new(err)
2220 }
2221}
2222
2223#[cfg(not(no_global_oom_handling))]
2224#[stable(feature = "rust1", since = "1.0.0")]
2225impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
2226 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
2227 /// dyn [`Error`] + [`Send`] + [`Sync`].
2228 ///
2229 /// # Examples
2230 ///
2231 /// ```
2232 /// use std::error::Error;
2233 /// use std::fmt;
2234 /// use std::mem;
2235 ///
2236 /// #[derive(Debug)]
2237 /// struct AnError;
2238 ///
2239 /// impl fmt::Display for AnError {
2240 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2241 /// write!(f, "An error")
2242 /// }
2243 /// }
2244 ///
2245 /// impl Error for AnError {}
2246 ///
2247 /// unsafe impl Send for AnError {}
2248 ///
2249 /// unsafe impl Sync for AnError {}
2250 ///
2251 /// let an_error = AnError;
2252 /// assert!(0 == mem::size_of_val(&an_error));
2253 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
2254 /// assert!(
2255 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2256 /// ```
2257 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
2258 Box::new(err)
2259 }
2260}
2261
2262#[cfg(not(no_global_oom_handling))]
2263#[stable(feature = "rust1", since = "1.0.0")]
2264impl From<String> for Box<dyn Error + Send + Sync> {
2265 /// Converts a [`String`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2266 ///
2267 /// # Examples
2268 ///
2269 /// ```
2270 /// use std::error::Error;
2271 /// use std::mem;
2272 ///
2273 /// let a_string_error = "a string error".to_string();
2274 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_string_error);
2275 /// assert!(
2276 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2277 /// ```
2278 #[inline]
2279 fn from(err: String) -> Box<dyn Error + Send + Sync> {
2280 struct StringError(String);
2281
2282 impl Error for StringError {
2283 #[allow(deprecated)]
2284 fn description(&self) -> &str {
2285 &self.0
2286 }
2287 }
2288
2289 impl fmt::Display for StringError {
2290 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2291 fmt::Display::fmt(&self.0, f)
2292 }
2293 }
2294
2295 // Purposefully skip printing "StringError(..)"
2296 impl fmt::Debug for StringError {
2297 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2298 fmt::Debug::fmt(&self.0, f)
2299 }
2300 }
2301
2302 Box::new(StringError(err))
2303 }
2304}
2305
2306#[cfg(not(no_global_oom_handling))]
2307#[stable(feature = "string_box_error", since = "1.6.0")]
2308impl From<String> for Box<dyn Error> {
2309 /// Converts a [`String`] into a box of dyn [`Error`].
2310 ///
2311 /// # Examples
2312 ///
2313 /// ```
2314 /// use std::error::Error;
2315 /// use std::mem;
2316 ///
2317 /// let a_string_error = "a string error".to_string();
2318 /// let a_boxed_error = Box::<dyn Error>::from(a_string_error);
2319 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2320 /// ```
2321 fn from(str_err: String) -> Box<dyn Error> {
2322 let err1: Box<dyn Error + Send + Sync> = From::from(str_err);
2323 let err2: Box<dyn Error> = err1;
2324 err2
2325 }
2326}
2327
2328#[cfg(not(no_global_oom_handling))]
2329#[stable(feature = "rust1", since = "1.0.0")]
2330impl<'a> From<&str> for Box<dyn Error + Send + Sync + 'a> {
2331 /// Converts a [`str`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2332 ///
2333 /// [`str`]: prim@str
2334 ///
2335 /// # Examples
2336 ///
2337 /// ```
2338 /// use std::error::Error;
2339 /// use std::mem;
2340 ///
2341 /// let a_str_error = "a str error";
2342 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_str_error);
2343 /// assert!(
2344 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2345 /// ```
2346 #[inline]
2347 fn from(err: &str) -> Box<dyn Error + Send + Sync + 'a> {
2348 From::from(String::from(err))
2349 }
2350}
2351
2352#[cfg(not(no_global_oom_handling))]
2353#[stable(feature = "string_box_error", since = "1.6.0")]
2354impl From<&str> for Box<dyn Error> {
2355 /// Converts a [`str`] into a box of dyn [`Error`].
2356 ///
2357 /// [`str`]: prim@str
2358 ///
2359 /// # Examples
2360 ///
2361 /// ```
2362 /// use std::error::Error;
2363 /// use std::mem;
2364 ///
2365 /// let a_str_error = "a str error";
2366 /// let a_boxed_error = Box::<dyn Error>::from(a_str_error);
2367 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2368 /// ```
2369 fn from(err: &str) -> Box<dyn Error> {
2370 From::from(String::from(err))
2371 }
2372}
2373
2374#[cfg(not(no_global_oom_handling))]
2375#[stable(feature = "cow_box_error", since = "1.22.0")]
2376impl<'a, 'b> From<Cow<'b, str>> for Box<dyn Error + Send + Sync + 'a> {
2377 /// Converts a [`Cow`] into a box of dyn [`Error`] + [`Send`] + [`Sync`].
2378 ///
2379 /// # Examples
2380 ///
2381 /// ```
2382 /// use std::error::Error;
2383 /// use std::mem;
2384 /// use std::borrow::Cow;
2385 ///
2386 /// let a_cow_str_error = Cow::from("a str error");
2387 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(a_cow_str_error);
2388 /// assert!(
2389 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2390 /// ```
2391 fn from(err: Cow<'b, str>) -> Box<dyn Error + Send + Sync + 'a> {
2392 From::from(String::from(err))
2393 }
2394}
2395
2396#[cfg(not(no_global_oom_handling))]
2397#[stable(feature = "cow_box_error", since = "1.22.0")]
2398impl<'a> From<Cow<'a, str>> for Box<dyn Error> {
2399 /// Converts a [`Cow`] into a box of dyn [`Error`].
2400 ///
2401 /// # Examples
2402 ///
2403 /// ```
2404 /// use std::error::Error;
2405 /// use std::mem;
2406 /// use std::borrow::Cow;
2407 ///
2408 /// let a_cow_str_error = Cow::from("a str error");
2409 /// let a_boxed_error = Box::<dyn Error>::from(a_cow_str_error);
2410 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2411 /// ```
2412 fn from(err: Cow<'a, str>) -> Box<dyn Error> {
2413 From::from(String::from(err))
2414 }
2415}
2416
2417#[stable(feature = "box_error", since = "1.8.0")]
2418impl<T: core::error::Error> core::error::Error for Box<T> {
2419 #[allow(deprecated, deprecated_in_future)]
2420 fn description(&self) -> &str {
2421 core::error::Error::description(&**self)
2422 }
2423
2424 #[allow(deprecated)]
2425 fn cause(&self) -> Option<&dyn core::error::Error> {
2426 core::error::Error::cause(&**self)
2427 }
2428
2429 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
2430 core::error::Error::source(&**self)
2431 }
2432}