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