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