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