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