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