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//! 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_zeroed_alloc)]
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_zeroed_alloc)]
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(box_uninit_write)]
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 /// Constructs a box from a `NonNull` pointer.
1023 ///
1024 /// After calling this function, the `NonNull` pointer is owned by
1025 /// the resulting `Box`. Specifically, the `Box` destructor will call
1026 /// the destructor of `T` and free the allocated memory. For this
1027 /// to be safe, the memory must have been allocated in accordance
1028 /// with the [memory layout] used by `Box` .
1029 ///
1030 /// # Safety
1031 ///
1032 /// This function is unsafe because improper use may lead to
1033 /// memory problems. For example, a double-free may occur if the
1034 /// function is called twice on the same `NonNull` pointer.
1035 ///
1036 /// The safety conditions are described in the [memory layout] section.
1037 ///
1038 /// # Examples
1039 ///
1040 /// Recreate a `Box` which was previously converted to a `NonNull`
1041 /// pointer using [`Box::into_non_null`]:
1042 /// ```
1043 /// #![feature(box_vec_non_null)]
1044 ///
1045 /// let x = Box::new(5);
1046 /// let non_null = Box::into_non_null(x);
1047 /// let x = unsafe { Box::from_non_null(non_null) };
1048 /// ```
1049 /// Manually create a `Box` from scratch by using the global allocator:
1050 /// ```
1051 /// #![feature(box_vec_non_null)]
1052 ///
1053 /// use std::alloc::{alloc, Layout};
1054 /// use std::ptr::NonNull;
1055 ///
1056 /// unsafe {
1057 /// let non_null = NonNull::new(alloc(Layout::new::<i32>()).cast::<i32>())
1058 /// .expect("allocation failed");
1059 /// // In general .write is required to avoid attempting to destruct
1060 /// // the (uninitialized) previous contents of `non_null`.
1061 /// non_null.write(5);
1062 /// let x = Box::from_non_null(non_null);
1063 /// }
1064 /// ```
1065 ///
1066 /// [memory layout]: self#memory-layout
1067 /// [`Layout`]: crate::Layout
1068 #[inline(always)]
1069 #[must_use = "call `drop(Box::from_non_null(ptr))` if you intend to drop the `Box`"]
1070 pub unsafe fn from_non_null(ptr: NonNull<T>) -> Self {
1071 unsafe { Self::from_raw(ptr.as_ptr()) }
1072 }
1073}
1074
1075impl<T: ?Sized, A: Allocator> Box<T, A> {
1076 /// Constructs a box from a raw pointer in the given allocator.
1077 ///
1078 /// After calling this function, the raw pointer is owned by the
1079 /// resulting `Box`. Specifically, the `Box` destructor will call
1080 /// the destructor of `T` and free the allocated memory. For this
1081 /// to be safe, the memory must have been allocated in accordance
1082 /// with the [memory layout] used by `Box` .
1083 ///
1084 /// # Safety
1085 ///
1086 /// This function is unsafe because improper use may lead to
1087 /// memory problems. For example, a double-free may occur if the
1088 /// function is called twice on the same raw pointer.
1089 ///
1090 ///
1091 /// # Examples
1092 ///
1093 /// Recreate a `Box` which was previously converted to a raw pointer
1094 /// using [`Box::into_raw_with_allocator`]:
1095 /// ```
1096 /// use std::alloc::System;
1097 /// # use allocator_api2::boxed::Box;
1098 ///
1099 /// let x = Box::new_in(5, System);
1100 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1101 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1102 /// ```
1103 /// Manually create a `Box` from scratch by using the system allocator:
1104 /// ```
1105 /// use allocator_api2::alloc::{Allocator, Layout, System};
1106 /// # use allocator_api2::boxed::Box;
1107 ///
1108 /// unsafe {
1109 /// let ptr = System.allocate(Layout::new::<i32>())?.as_ptr().cast::<i32>();
1110 /// // In general .write is required to avoid attempting to destruct
1111 /// // the (uninitialized) previous contents of `ptr`, though for this
1112 /// // simple example `*ptr = 5` would have worked as well.
1113 /// ptr.write(5);
1114 /// let x = Box::from_raw_in(ptr, System);
1115 /// }
1116 /// # Ok::<(), allocator_api2::alloc::AllocError>(())
1117 /// ```
1118 ///
1119 /// [memory layout]: self#memory-layout
1120 /// [`Layout`]: crate::Layout
1121 #[inline(always)]
1122 pub const unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
1123 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
1124 }
1125
1126 /// Constructs a box from a `NonNull` pointer in the given allocator.
1127 ///
1128 /// After calling this function, the `NonNull` pointer is owned by
1129 /// the resulting `Box`. Specifically, the `Box` destructor will call
1130 /// the destructor of `T` and free the allocated memory. For this
1131 /// to be safe, the memory must have been allocated in accordance
1132 /// with the [memory layout] used by `Box` .
1133 ///
1134 /// # Safety
1135 ///
1136 /// This function is unsafe because improper use may lead to
1137 /// memory problems. For example, a double-free may occur if the
1138 /// function is called twice on the same raw pointer.
1139 ///
1140 ///
1141 /// # Examples
1142 ///
1143 /// Recreate a `Box` which was previously converted to a `NonNull` pointer
1144 /// using [`Box::into_non_null_with_allocator`]:
1145 /// ```
1146 /// #![feature(allocator_api, box_vec_non_null)]
1147 ///
1148 /// use std::alloc::System;
1149 ///
1150 /// let x = Box::new_in(5, System);
1151 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1152 /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1153 /// ```
1154 /// Manually create a `Box` from scratch by using the system allocator:
1155 /// ```
1156 /// #![feature(allocator_api, box_vec_non_null, slice_ptr_get)]
1157 ///
1158 /// use std::alloc::{Allocator, Layout, System};
1159 ///
1160 /// unsafe {
1161 /// let non_null = System.allocate(Layout::new::<i32>())?.cast::<i32>();
1162 /// // In general .write is required to avoid attempting to destruct
1163 /// // the (uninitialized) previous contents of `non_null`.
1164 /// non_null.write(5);
1165 /// let x = Box::from_non_null_in(non_null, System);
1166 /// }
1167 /// # Ok::<(), std::alloc::AllocError>(())
1168 /// ```
1169 ///
1170 /// [memory layout]: self#memory-layout
1171 /// [`Layout`]: crate::Layout
1172 #[inline(always)]
1173 pub const unsafe fn from_non_null_in(raw: NonNull<T>, alloc: A) -> Self {
1174 // SAFETY: guaranteed by the caller.
1175 unsafe { Box::from_raw_in(raw.as_ptr(), alloc) }
1176 }
1177
1178 /// Consumes the `Box`, returning a wrapped raw pointer.
1179 ///
1180 /// The pointer will be properly aligned and non-null.
1181 ///
1182 /// After calling this function, the caller is responsible for the
1183 /// memory previously managed by the `Box`. In particular, the
1184 /// caller should properly destroy `T` and release the memory, taking
1185 /// into account the [memory layout] used by `Box`. The easiest way to
1186 /// do this is to convert the raw pointer back into a `Box` with the
1187 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
1188 /// the cleanup.
1189 ///
1190 /// Note: this is an associated function, which means that you have
1191 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
1192 /// is so that there is no conflict with a method on the inner type.
1193 ///
1194 /// # Examples
1195 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
1196 /// for automatic cleanup:
1197 /// ```
1198 /// let x = Box::new(String::from("Hello"));
1199 /// let ptr = Box::into_raw(x);
1200 /// let x = unsafe { Box::from_raw(ptr) };
1201 /// ```
1202 /// Manual cleanup by explicitly running the destructor and deallocating
1203 /// the memory:
1204 /// ```
1205 /// use std::alloc::{dealloc, Layout};
1206 /// use std::ptr;
1207 ///
1208 /// let x = Box::new(String::from("Hello"));
1209 /// let p = Box::into_raw(x);
1210 /// unsafe {
1211 /// ptr::drop_in_place(p);
1212 /// dealloc(p as *mut u8, Layout::new::<String>());
1213 /// }
1214 /// ```
1215 ///
1216 /// [memory layout]: self#memory-layout
1217 #[inline(always)]
1218 pub fn into_raw(b: Self) -> *mut T {
1219 Self::into_raw_with_allocator(b).0
1220 }
1221
1222 /// Consumes the `Box`, returning a wrapped `NonNull` pointer.
1223 ///
1224 /// The pointer will be properly aligned.
1225 ///
1226 /// After calling this function, the caller is responsible for the
1227 /// memory previously managed by the `Box`. In particular, the
1228 /// caller should properly destroy `T` and release the memory, taking
1229 /// into account the [memory layout] used by `Box`. The easiest way to
1230 /// do this is to convert the `NonNull` pointer back into a `Box` with the
1231 /// [`Box::from_non_null`] function, allowing the `Box` destructor to
1232 /// perform the cleanup.
1233 ///
1234 /// Note: this is an associated function, which means that you have
1235 /// to call it as `Box::into_non_null(b)` instead of `b.into_non_null()`.
1236 /// This is so that there is no conflict with a method on the inner type.
1237 ///
1238 /// # Examples
1239 /// Converting the `NonNull` pointer back into a `Box` with [`Box::from_non_null`]
1240 /// for automatic cleanup:
1241 /// ```
1242 /// #![feature(box_vec_non_null)]
1243 ///
1244 /// let x = Box::new(String::from("Hello"));
1245 /// let non_null = Box::into_non_null(x);
1246 /// let x = unsafe { Box::from_non_null(non_null) };
1247 /// ```
1248 /// Manual cleanup by explicitly running the destructor and deallocating
1249 /// the memory:
1250 /// ```
1251 /// #![feature(box_vec_non_null)]
1252 ///
1253 /// use std::alloc::{dealloc, Layout};
1254 ///
1255 /// let x = Box::new(String::from("Hello"));
1256 /// let non_null = Box::into_non_null(x);
1257 /// unsafe {
1258 /// non_null.drop_in_place();
1259 /// dealloc(non_null.as_ptr().cast::<u8>(), Layout::new::<String>());
1260 /// }
1261 /// ```
1262 /// Note: This is equivalent to the following:
1263 /// ```
1264 /// #![feature(box_vec_non_null)]
1265 ///
1266 /// let x = Box::new(String::from("Hello"));
1267 /// let non_null = Box::into_non_null(x);
1268 /// unsafe {
1269 /// drop(Box::from_non_null(non_null));
1270 /// }
1271 /// ```
1272 ///
1273 /// [memory layout]: self#memory-layout
1274 #[must_use = "losing the pointer will leak memory"]
1275 #[inline(always)]
1276 pub fn into_non_null(b: Self) -> NonNull<T> {
1277 // SAFETY: `Box` is guaranteed to be non-null.
1278 unsafe { NonNull::new_unchecked(Self::into_raw(b)) }
1279 }
1280
1281 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
1282 ///
1283 /// The pointer will be properly aligned and non-null.
1284 ///
1285 /// After calling this function, the caller is responsible for the
1286 /// memory previously managed by the `Box`. In particular, the
1287 /// caller should properly destroy `T` and release the memory, taking
1288 /// into account the [memory layout] used by `Box`. The easiest way to
1289 /// do this is to convert the raw pointer back into a `Box` with the
1290 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
1291 /// the cleanup.
1292 ///
1293 /// Note: this is an associated function, which means that you have
1294 /// to call it as `Box::into_raw_with_allocator(b)` instead of `b.into_raw_with_allocator()`. This
1295 /// is so that there is no conflict with a method on the inner type.
1296 ///
1297 /// # Examples
1298 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
1299 /// for automatic cleanup:
1300 /// ```
1301 /// #![feature(allocator_api)]
1302 ///
1303 /// use std::alloc::System;
1304 ///
1305 /// let x = Box::new_in(String::from("Hello"), System);
1306 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1307 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
1308 /// ```
1309 /// Manual cleanup by explicitly running the destructor and deallocating
1310 /// the memory:
1311 /// ```
1312 /// #![feature(allocator_api)]
1313 ///
1314 /// use std::alloc::{Allocator, Layout, System};
1315 /// use std::ptr::{self, NonNull};
1316 ///
1317 /// let x = Box::new_in(String::from("Hello"), System);
1318 /// let (ptr, alloc) = Box::into_raw_with_allocator(x);
1319 /// unsafe {
1320 /// ptr::drop_in_place(ptr);
1321 /// let non_null = NonNull::new_unchecked(ptr);
1322 /// alloc.deallocate(non_null.cast(), Layout::new::<String>());
1323 /// }
1324 /// ```
1325 ///
1326 /// [memory layout]: self#memory-layout
1327 #[inline(always)]
1328 pub fn into_raw_with_allocator(b: Self) -> (*mut T, A) {
1329 let (leaked, alloc) = Box::into_non_null_with_allocator(b);
1330 (leaked.as_ptr(), alloc)
1331 }
1332
1333 /// Consumes the `Box`, returning a wrapped `NonNull` pointer and the allocator.
1334 ///
1335 /// The pointer will be properly aligned.
1336 ///
1337 /// After calling this function, the caller is responsible for the
1338 /// memory previously managed by the `Box`. In particular, the
1339 /// caller should properly destroy `T` and release the memory, taking
1340 /// into account the [memory layout] used by `Box`. The easiest way to
1341 /// do this is to convert the `NonNull` pointer back into a `Box` with the
1342 /// [`Box::from_non_null_in`] function, allowing the `Box` destructor to
1343 /// perform the cleanup.
1344 ///
1345 /// Note: this is an associated function, which means that you have
1346 /// to call it as `Box::into_non_null_with_allocator(b)` instead of
1347 /// `b.into_non_null_with_allocator()`. This is so that there is no
1348 /// conflict with a method on the inner type.
1349 ///
1350 /// # Examples
1351 /// Converting the `NonNull` pointer back into a `Box` with
1352 /// [`Box::from_non_null_in`] for automatic cleanup:
1353 /// ```
1354 /// #![feature(allocator_api, box_vec_non_null)]
1355 ///
1356 /// use std::alloc::System;
1357 ///
1358 /// let x = Box::new_in(String::from("Hello"), System);
1359 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1360 /// let x = unsafe { Box::from_non_null_in(non_null, alloc) };
1361 /// ```
1362 /// Manual cleanup by explicitly running the destructor and deallocating
1363 /// the memory:
1364 /// ```
1365 /// #![feature(allocator_api, box_vec_non_null)]
1366 ///
1367 /// use std::alloc::{Allocator, Layout, System};
1368 ///
1369 /// let x = Box::new_in(String::from("Hello"), System);
1370 /// let (non_null, alloc) = Box::into_non_null_with_allocator(x);
1371 /// unsafe {
1372 /// non_null.drop_in_place();
1373 /// alloc.deallocate(non_null.cast::<u8>(), Layout::new::<String>());
1374 /// }
1375 /// ```
1376 ///
1377 /// [memory layout]: self#memory-layout
1378 #[inline(always)]
1379 pub fn into_non_null_with_allocator(b: Self) -> (NonNull<T>, A) {
1380 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
1381 // raw pointer for the type system. Turning it directly into a raw pointer would not be
1382 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
1383 // so all raw pointer methods have to go through `Box::leak`. Turning *that* to a raw pointer
1384 // behaves correctly.
1385 let alloc = unsafe { ptr::read(&b.1) };
1386 (NonNull::from(Box::leak(b)), alloc)
1387 }
1388 /// Returns a raw mutable pointer to the `Box`'s contents.
1389 ///
1390 /// The caller must ensure that the `Box` outlives the pointer this
1391 /// function returns, or else it will end up dangling.
1392 ///
1393 /// This method guarantees that for the purpose of the aliasing model, this method
1394 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1395 /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
1396 /// Note that calling other methods that materialize references to the memory
1397 /// may still invalidate this pointer.
1398 /// See the example below for how this guarantee can be used.
1399 ///
1400 /// # Examples
1401 ///
1402 /// Due to the aliasing guarantee, the following code is legal:
1403 ///
1404 /// ```rust
1405 /// #![feature(box_as_ptr)]
1406 ///
1407 /// unsafe {
1408 /// let mut b = Box::new(0);
1409 /// let ptr1 = Box::as_mut_ptr(&mut b);
1410 /// ptr1.write(1);
1411 /// let ptr2 = Box::as_mut_ptr(&mut b);
1412 /// ptr2.write(2);
1413 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1414 /// ptr1.write(3);
1415 /// }
1416 /// ```
1417 ///
1418 /// [`as_mut_ptr`]: Self::as_mut_ptr
1419 /// [`as_ptr`]: Self::as_ptr
1420 #[inline(always)]
1421 pub fn as_mut_ptr(b: &mut Self) -> *mut T {
1422 // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1423 // any references.
1424 &raw mut **b
1425 }
1426
1427 /// Returns a raw pointer to the `Box`'s contents.
1428 ///
1429 /// The caller must ensure that the `Box` outlives the pointer this
1430 /// function returns, or else it will end up dangling.
1431 ///
1432 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1433 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1434 /// derived from it. If you need to mutate the contents of the `Box`, use [`as_mut_ptr`].
1435 ///
1436 /// This method guarantees that for the purpose of the aliasing model, this method
1437 /// does not materialize a reference to the underlying memory, and thus the returned pointer
1438 /// will remain valid when mixed with other calls to [`as_ptr`] and [`as_mut_ptr`].
1439 /// Note that calling other methods that materialize mutable references to the memory,
1440 /// as well as writing to this memory, may still invalidate this pointer.
1441 /// See the example below for how this guarantee can be used.
1442 ///
1443 /// # Examples
1444 ///
1445 /// Due to the aliasing guarantee, the following code is legal:
1446 ///
1447 /// ```rust
1448 /// #![feature(box_as_ptr)]
1449 ///
1450 /// unsafe {
1451 /// let mut v = Box::new(0);
1452 /// let ptr1 = Box::as_ptr(&v);
1453 /// let ptr2 = Box::as_mut_ptr(&mut v);
1454 /// let _val = ptr2.read();
1455 /// // No write to this memory has happened yet, so `ptr1` is still valid.
1456 /// let _val = ptr1.read();
1457 /// // However, once we do a write...
1458 /// ptr2.write(1);
1459 /// // ... `ptr1` is no longer valid.
1460 /// // This would be UB: let _val = ptr1.read();
1461 /// }
1462 /// ```
1463 ///
1464 /// [`as_mut_ptr`]: Self::as_mut_ptr
1465 /// [`as_ptr`]: Self::as_ptr
1466 #[inline(always)]
1467 pub fn as_ptr(b: &Self) -> *const T {
1468 // This is a primitive deref, not going through `DerefMut`, and therefore not materializing
1469 // any references.
1470 &raw const **b
1471 }
1472
1473 /// Returns a reference to the underlying allocator.
1474 ///
1475 /// Note: this is an associated function, which means that you have
1476 /// to call it as `Box::allocator(&b)` instead of `b.allocator()`. This
1477 /// is so that there is no conflict with a method on the inner type.
1478 #[inline(always)]
1479 pub const fn allocator(b: &Self) -> &A {
1480 &b.1
1481 }
1482
1483 /// Consumes and leaks the `Box`, returning a mutable reference,
1484 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
1485 /// `'a`. If the type has only static references, or none at all, then this
1486 /// may be chosen to be `'static`.
1487 ///
1488 /// This function is mainly useful for data that lives for the remainder of
1489 /// the program's life. Dropping the returned reference will cause a memory
1490 /// leak. If this is not acceptable, the reference should first be wrapped
1491 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
1492 /// then be dropped which will properly destroy `T` and release the
1493 /// allocated memory.
1494 ///
1495 /// Note: this is an associated function, which means that you have
1496 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
1497 /// is so that there is no conflict with a method on the inner type.
1498 ///
1499 /// # Examples
1500 ///
1501 /// Simple usage:
1502 ///
1503 /// ```
1504 /// let x = Box::new(41);
1505 /// let static_ref: &'static mut usize = Box::leak(x);
1506 /// *static_ref += 1;
1507 /// assert_eq!(*static_ref, 42);
1508 /// ```
1509 ///
1510 /// Unsized data:
1511 ///
1512 /// ```
1513 /// let x = vec![1, 2, 3].into_boxed_slice();
1514 /// let static_ref = Box::leak(x);
1515 /// static_ref[0] = 4;
1516 /// assert_eq!(*static_ref, [4, 2, 3]);
1517 /// ```
1518 #[inline(always)]
1519 pub fn leak<'a>(b: Self) -> &'a mut T
1520 where
1521 A: 'a,
1522 {
1523 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
1524 }
1525
1526 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1527 /// `*boxed` will be pinned in memory and unable to be moved.
1528 ///
1529 /// This conversion does not allocate on the heap and happens in place.
1530 ///
1531 /// This is also available via [`From`].
1532 ///
1533 /// Constructing and pinning a `Box` with <code>Box::into_pin([Box::new]\(x))</code>
1534 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1535 /// This `into_pin` method is useful if you already have a `Box<T>`, or you are
1536 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1537 ///
1538 /// # Notes
1539 ///
1540 /// It's not recommended that crates add an impl like `From<Box<T>> for Pin<T>`,
1541 /// as it'll introduce an ambiguity when calling `Pin::from`.
1542 /// A demonstration of such a poor impl is shown below.
1543 ///
1544 /// ```compile_fail
1545 /// # use std::pin::Pin;
1546 /// struct Foo; // A type defined in this crate.
1547 /// impl From<Box<()>> for Pin<Foo> {
1548 /// fn from(_: Box<()>) -> Pin<Foo> {
1549 /// Pin::new(Foo)
1550 /// }
1551 /// }
1552 ///
1553 /// let foo = Box::new(());
1554 /// let bar = Pin::from(foo);
1555 /// ```
1556 #[inline(always)]
1557 pub fn into_pin(boxed: Self) -> Pin<Self>
1558 where
1559 A: 'static,
1560 {
1561 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
1562 // when `T: !Unpin`, so it's safe to pin it directly without any
1563 // additional requirements.
1564 unsafe { Pin::new_unchecked(boxed) }
1565 }
1566}
1567
1568impl<T: ?Sized, A: Allocator> Drop for Box<T, A> {
1569 #[inline(always)]
1570 fn drop(&mut self) {
1571 let layout = Layout::for_value::<T>(&**self);
1572 unsafe {
1573 ptr::drop_in_place(self.0.as_mut());
1574 self.1.deallocate(self.0.as_non_null_ptr().cast(), layout);
1575 }
1576 }
1577}
1578
1579#[cfg(not(no_global_oom_handling))]
1580impl<T: Default> Default for Box<T> {
1581 /// Creates a `Box<T>`, with the `Default` value for T.
1582 #[inline(always)]
1583 fn default() -> Self {
1584 Box::new(T::default())
1585 }
1586}
1587
1588impl<T, A: Allocator + Default> Default for Box<[T], A> {
1589 #[inline(always)]
1590 fn default() -> Self {
1591 let ptr: NonNull<[T]> = NonNull::<[T; 0]>::dangling();
1592 Box(unsafe { Unique::new_unchecked(ptr.as_ptr()) }, A::default())
1593 }
1594}
1595
1596impl<A: Allocator + Default> Default for Box<str, A> {
1597 #[inline(always)]
1598 fn default() -> Self {
1599 // SAFETY: This is the same as `Unique::cast<U>` but with an unsized `U = str`.
1600 let ptr: Unique<str> = unsafe {
1601 let bytes: NonNull<[u8]> = NonNull::<[u8; 0]>::dangling();
1602 Unique::new_unchecked(bytes.as_ptr() as *mut str)
1603 };
1604 Box(ptr, A::default())
1605 }
1606}
1607
1608#[cfg(not(no_global_oom_handling))]
1609impl<T: Clone, A: Allocator + Clone> Clone for Box<T, A> {
1610 /// Returns a new box with a `clone()` of this box's contents.
1611 ///
1612 /// # Examples
1613 ///
1614 /// ```
1615 /// let x = Box::new(5);
1616 /// let y = x.clone();
1617 ///
1618 /// // The value is the same
1619 /// assert_eq!(x, y);
1620 ///
1621 /// // But they are unique objects
1622 /// assert_ne!(&*x as *const i32, &*y as *const i32);
1623 /// ```
1624 #[inline(always)]
1625 fn clone(&self) -> Self {
1626 // Pre-allocate memory to allow writing the cloned value directly.
1627 let mut boxed = Self::new_uninit_in(self.1.clone());
1628 unsafe {
1629 boxed.write((**self).clone());
1630 boxed.assume_init()
1631 }
1632 }
1633
1634 /// Copies `source`'s contents into `self` without creating a new allocation.
1635 ///
1636 /// # Examples
1637 ///
1638 /// ```
1639 /// let x = Box::new(5);
1640 /// let mut y = Box::new(10);
1641 /// let yp: *const i32 = &*y;
1642 ///
1643 /// y.clone_from(&x);
1644 ///
1645 /// // The value is the same
1646 /// assert_eq!(x, y);
1647 ///
1648 /// // And no allocation occurred
1649 /// assert_eq!(yp, &*y);
1650 /// ```
1651 #[inline(always)]
1652 fn clone_from(&mut self, source: &Self) {
1653 (**self).clone_from(&(**source));
1654 }
1655}
1656
1657#[cfg(not(no_global_oom_handling))]
1658impl Clone for Box<str> {
1659 #[inline(always)]
1660 fn clone(&self) -> Self {
1661 // this makes a copy of the data
1662 let buf: Box<[u8]> = self.as_bytes().into();
1663 unsafe { Box::from_raw(Box::into_raw(buf) as *mut str) }
1664 }
1665}
1666
1667impl<T: ?Sized + PartialEq, A: Allocator> PartialEq for Box<T, A> {
1668 #[inline(always)]
1669 fn eq(&self, other: &Self) -> bool {
1670 PartialEq::eq(&**self, &**other)
1671 }
1672 #[inline(always)]
1673 fn ne(&self, other: &Self) -> bool {
1674 PartialEq::ne(&**self, &**other)
1675 }
1676}
1677
1678impl<T: ?Sized + PartialOrd, A: Allocator> PartialOrd for Box<T, A> {
1679 #[inline(always)]
1680 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1681 PartialOrd::partial_cmp(&**self, &**other)
1682 }
1683 #[inline(always)]
1684 fn lt(&self, other: &Self) -> bool {
1685 PartialOrd::lt(&**self, &**other)
1686 }
1687 #[inline(always)]
1688 fn le(&self, other: &Self) -> bool {
1689 PartialOrd::le(&**self, &**other)
1690 }
1691 #[inline(always)]
1692 fn ge(&self, other: &Self) -> bool {
1693 PartialOrd::ge(&**self, &**other)
1694 }
1695 #[inline(always)]
1696 fn gt(&self, other: &Self) -> bool {
1697 PartialOrd::gt(&**self, &**other)
1698 }
1699}
1700
1701impl<T: ?Sized + Ord, A: Allocator> Ord for Box<T, A> {
1702 #[inline(always)]
1703 fn cmp(&self, other: &Self) -> Ordering {
1704 Ord::cmp(&**self, &**other)
1705 }
1706}
1707
1708impl<T: ?Sized + Eq, A: Allocator> Eq for Box<T, A> {}
1709
1710impl<T: ?Sized + Hash, A: Allocator> Hash for Box<T, A> {
1711 #[inline(always)]
1712 fn hash<H: Hasher>(&self, state: &mut H) {
1713 (**self).hash(state);
1714 }
1715}
1716
1717impl<T: ?Sized + Hasher, A: Allocator> Hasher for Box<T, A> {
1718 #[inline(always)]
1719 fn finish(&self) -> u64 {
1720 (**self).finish()
1721 }
1722 #[inline(always)]
1723 fn write(&mut self, bytes: &[u8]) {
1724 (**self).write(bytes)
1725 }
1726 #[inline(always)]
1727 fn write_u8(&mut self, i: u8) {
1728 (**self).write_u8(i)
1729 }
1730 #[inline(always)]
1731 fn write_u16(&mut self, i: u16) {
1732 (**self).write_u16(i)
1733 }
1734 #[inline(always)]
1735 fn write_u32(&mut self, i: u32) {
1736 (**self).write_u32(i)
1737 }
1738 #[inline(always)]
1739 fn write_u64(&mut self, i: u64) {
1740 (**self).write_u64(i)
1741 }
1742 #[inline(always)]
1743 fn write_u128(&mut self, i: u128) {
1744 (**self).write_u128(i)
1745 }
1746 #[inline(always)]
1747 fn write_usize(&mut self, i: usize) {
1748 (**self).write_usize(i)
1749 }
1750 #[inline(always)]
1751 fn write_i8(&mut self, i: i8) {
1752 (**self).write_i8(i)
1753 }
1754 #[inline(always)]
1755 fn write_i16(&mut self, i: i16) {
1756 (**self).write_i16(i)
1757 }
1758 #[inline(always)]
1759 fn write_i32(&mut self, i: i32) {
1760 (**self).write_i32(i)
1761 }
1762 #[inline(always)]
1763 fn write_i64(&mut self, i: i64) {
1764 (**self).write_i64(i)
1765 }
1766 #[inline(always)]
1767 fn write_i128(&mut self, i: i128) {
1768 (**self).write_i128(i)
1769 }
1770 #[inline(always)]
1771 fn write_isize(&mut self, i: isize) {
1772 (**self).write_isize(i)
1773 }
1774}
1775
1776#[cfg(not(no_global_oom_handling))]
1777impl<T> From<T> for Box<T> {
1778 /// Converts a `T` into a `Box<T>`
1779 ///
1780 /// The conversion allocates on the heap and moves `t`
1781 /// from the stack into it.
1782 ///
1783 /// # Examples
1784 ///
1785 /// ```rust
1786 /// let x = 5;
1787 /// let boxed = Box::new(5);
1788 ///
1789 /// assert_eq!(Box::from(x), boxed);
1790 /// ```
1791 #[inline(always)]
1792 fn from(t: T) -> Self {
1793 Box::new(t)
1794 }
1795}
1796
1797impl<T: ?Sized, A: Allocator> From<Box<T, A>> for Pin<Box<T, A>>
1798where
1799 A: 'static,
1800{
1801 /// Converts a `Box<T>` into a `Pin<Box<T>>`. If `T` does not implement [`Unpin`], then
1802 /// `*boxed` will be pinned in memory and unable to be moved.
1803 ///
1804 /// This conversion does not allocate on the heap and happens in place.
1805 ///
1806 /// This is also available via [`Box::into_pin`].
1807 ///
1808 /// Constructing and pinning a `Box` with <code><Pin<Box\<T>>>::from([Box::new]\(x))</code>
1809 /// can also be written more concisely using <code>[Box::pin]\(x)</code>.
1810 /// This `From` implementation is useful if you already have a `Box<T>`, or you are
1811 /// constructing a (pinned) `Box` in a different way than with [`Box::new`].
1812 #[inline(always)]
1813 fn from(boxed: Box<T, A>) -> Self {
1814 Box::into_pin(boxed)
1815 }
1816}
1817
1818#[cfg(not(no_global_oom_handling))]
1819impl<T: Copy, A: Allocator + Default> From<&[T]> for Box<[T], A> {
1820 /// Converts a `&[T]` into a `Box<[T]>`
1821 ///
1822 /// This conversion allocates on the heap
1823 /// and performs a copy of `slice` and its contents.
1824 ///
1825 /// # Examples
1826 /// ```rust
1827 /// // create a &[u8] which will be used to create a Box<[u8]>
1828 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1829 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1830 ///
1831 /// println!("{boxed_slice:?}");
1832 /// ```
1833 #[inline(always)]
1834 fn from(slice: &[T]) -> Box<[T], A> {
1835 let len = slice.len();
1836 let buf = RawVec::with_capacity_in(len, A::default());
1837 unsafe {
1838 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1839 buf.into_box(slice.len()).assume_init()
1840 }
1841 }
1842}
1843
1844#[cfg(not(no_global_oom_handling))]
1845impl<A: Allocator + Default> From<&str> for Box<str, A> {
1846 /// Converts a `&str` into a `Box<str>`
1847 ///
1848 /// This conversion allocates on the heap
1849 /// and performs a copy of `s`.
1850 ///
1851 /// # Examples
1852 ///
1853 /// ```rust
1854 /// let boxed: Box<str> = Box::from("hello");
1855 /// println!("{boxed}");
1856 /// ```
1857 #[inline(always)]
1858 fn from(s: &str) -> Box<str, A> {
1859 let (raw, alloc) = Box::into_raw_with_allocator(Box::<[u8], A>::from(s.as_bytes()));
1860 unsafe { Box::from_raw_in(raw as *mut str, alloc) }
1861 }
1862}
1863
1864impl<A: Allocator> From<Box<str, A>> for Box<[u8], A> {
1865 /// Converts a `Box<str>` into a `Box<[u8]>`
1866 ///
1867 /// This conversion does not allocate on the heap and happens in place.
1868 ///
1869 /// # Examples
1870 /// ```rust
1871 /// // create a Box<str> which will be used to create a Box<[u8]>
1872 /// let boxed: Box<str> = Box::from("hello");
1873 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1874 ///
1875 /// // create a &[u8] which will be used to create a Box<[u8]>
1876 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1877 /// let boxed_slice = Box::from(slice);
1878 ///
1879 /// assert_eq!(boxed_slice, boxed_str);
1880 /// ```
1881 #[inline(always)]
1882 fn from(s: Box<str, A>) -> Self {
1883 let (raw, alloc) = Box::into_raw_with_allocator(s);
1884 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1885 }
1886}
1887
1888impl<T, A: Allocator, const N: usize> Box<[T; N], A> {
1889 #[inline(always)]
1890 pub fn slice(b: Self) -> Box<[T], A> {
1891 let (ptr, alloc) = Box::into_raw_with_allocator(b);
1892 unsafe { Box::from_raw_in(ptr, alloc) }
1893 }
1894
1895 pub fn into_vec(self) -> Vec<T, A>
1896 where
1897 A: Allocator,
1898 {
1899 unsafe {
1900 let (b, alloc) = Box::into_raw_with_allocator(self);
1901 Vec::from_raw_parts_in(b as *mut T, N, N, alloc)
1902 }
1903 }
1904}
1905
1906#[cfg(not(no_global_oom_handling))]
1907impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1908 /// Converts a `[T; N]` into a `Box<[T]>`
1909 ///
1910 /// This conversion moves the array to newly heap-allocated memory.
1911 ///
1912 /// # Examples
1913 ///
1914 /// ```rust
1915 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1916 /// println!("{boxed:?}");
1917 /// ```
1918 #[inline(always)]
1919 fn from(array: [T; N]) -> Box<[T]> {
1920 Box::slice(Box::new(array))
1921 }
1922}
1923
1924impl<T, A: Allocator, const N: usize> TryFrom<Box<[T], A>> for Box<[T; N], A> {
1925 type Error = Box<[T], A>;
1926
1927 /// Attempts to convert a `Box<[T]>` into a `Box<[T; N]>`.
1928 ///
1929 /// The conversion occurs in-place and does not require a
1930 /// new memory allocation.
1931 ///
1932 /// # Errors
1933 ///
1934 /// Returns the old `Box<[T]>` in the `Err` variant if
1935 /// `boxed_slice.len()` does not equal `N`.
1936 #[inline(always)]
1937 fn try_from(boxed_slice: Box<[T], A>) -> Result<Self, Self::Error> {
1938 if boxed_slice.len() == N {
1939 let (ptr, alloc) = Box::into_raw_with_allocator(boxed_slice);
1940 Ok(unsafe { Box::from_raw_in(ptr as *mut [T; N], alloc) })
1941 } else {
1942 Err(boxed_slice)
1943 }
1944 }
1945}
1946
1947impl<A: Allocator> Box<dyn Any, A> {
1948 /// Attempt to downcast the box to a concrete type.
1949 ///
1950 /// # Examples
1951 ///
1952 /// ```
1953 /// use std::any::Any;
1954 ///
1955 /// fn print_if_string(value: Box<dyn Any>) {
1956 /// if let Ok(string) = value.downcast::<String>() {
1957 /// println!("String ({}): {}", string.len(), string);
1958 /// }
1959 /// }
1960 ///
1961 /// let my_string = "Hello World".to_string();
1962 /// print_if_string(Box::new(my_string));
1963 /// print_if_string(Box::new(0i8));
1964 /// ```
1965 #[inline(always)]
1966 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1967 if self.is::<T>() {
1968 unsafe { Ok(self.downcast_unchecked::<T>()) }
1969 } else {
1970 Err(self)
1971 }
1972 }
1973
1974 /// Downcasts the box to a concrete type.
1975 ///
1976 /// For a safe alternative see [`downcast`].
1977 ///
1978 /// # Examples
1979 ///
1980 /// ```
1981 /// #![feature(downcast_unchecked)]
1982 ///
1983 /// use std::any::Any;
1984 ///
1985 /// let x: Box<dyn Any> = Box::new(1_usize);
1986 ///
1987 /// unsafe {
1988 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
1989 /// }
1990 /// ```
1991 ///
1992 /// # Safety
1993 ///
1994 /// The contained value must be of type `T`. Calling this method
1995 /// with the incorrect type is *undefined behavior*.
1996 ///
1997 /// [`downcast`]: Self::downcast
1998 #[inline(always)]
1999 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
2000 debug_assert!(self.is::<T>());
2001 unsafe {
2002 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_allocator(self);
2003 Box::from_raw_in(raw as *mut T, alloc)
2004 }
2005 }
2006}
2007
2008impl<A: Allocator> Box<dyn Any + Send, A> {
2009 /// Attempt to downcast the box to a concrete type.
2010 ///
2011 /// # Examples
2012 ///
2013 /// ```
2014 /// use std::any::Any;
2015 ///
2016 /// fn print_if_string(value: Box<dyn Any + Send>) {
2017 /// if let Ok(string) = value.downcast::<String>() {
2018 /// println!("String ({}): {}", string.len(), string);
2019 /// }
2020 /// }
2021 ///
2022 /// let my_string = "Hello World".to_string();
2023 /// print_if_string(Box::new(my_string));
2024 /// print_if_string(Box::new(0i8));
2025 /// ```
2026 #[inline(always)]
2027 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
2028 if self.is::<T>() {
2029 unsafe { Ok(self.downcast_unchecked::<T>()) }
2030 } else {
2031 Err(self)
2032 }
2033 }
2034
2035 /// Downcasts the box to a concrete type.
2036 ///
2037 /// For a safe alternative see [`downcast`].
2038 ///
2039 /// # Examples
2040 ///
2041 /// ```
2042 /// #![feature(downcast_unchecked)]
2043 ///
2044 /// use std::any::Any;
2045 ///
2046 /// let x: Box<dyn Any + Send> = Box::new(1_usize);
2047 ///
2048 /// unsafe {
2049 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
2050 /// }
2051 /// ```
2052 ///
2053 /// # Safety
2054 ///
2055 /// The contained value must be of type `T`. Calling this method
2056 /// with the incorrect type is *undefined behavior*.
2057 ///
2058 /// [`downcast`]: Self::downcast
2059 #[inline(always)]
2060 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
2061 debug_assert!(self.is::<T>());
2062 unsafe {
2063 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_allocator(self);
2064 Box::from_raw_in(raw as *mut T, alloc)
2065 }
2066 }
2067}
2068
2069impl<A: Allocator> Box<dyn Any + Send + Sync, A> {
2070 /// Attempt to downcast the box to a concrete type.
2071 ///
2072 /// # Examples
2073 ///
2074 /// ```
2075 /// use std::any::Any;
2076 ///
2077 /// fn print_if_string(value: Box<dyn Any + Send + Sync>) {
2078 /// if let Ok(string) = value.downcast::<String>() {
2079 /// println!("String ({}): {}", string.len(), string);
2080 /// }
2081 /// }
2082 ///
2083 /// let my_string = "Hello World".to_string();
2084 /// print_if_string(Box::new(my_string));
2085 /// print_if_string(Box::new(0i8));
2086 /// ```
2087 #[inline(always)]
2088 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
2089 if self.is::<T>() {
2090 unsafe { Ok(self.downcast_unchecked::<T>()) }
2091 } else {
2092 Err(self)
2093 }
2094 }
2095
2096 /// Downcasts the box to a concrete type.
2097 ///
2098 /// For a safe alternative see [`downcast`].
2099 ///
2100 /// # Examples
2101 ///
2102 /// ```
2103 /// #![feature(downcast_unchecked)]
2104 ///
2105 /// use std::any::Any;
2106 ///
2107 /// let x: Box<dyn Any + Send + Sync> = Box::new(1_usize);
2108 ///
2109 /// unsafe {
2110 /// assert_eq!(*x.downcast_unchecked::<usize>(), 1);
2111 /// }
2112 /// ```
2113 ///
2114 /// # Safety
2115 ///
2116 /// The contained value must be of type `T`. Calling this method
2117 /// with the incorrect type is *undefined behavior*.
2118 ///
2119 /// [`downcast`]: Self::downcast
2120 #[inline(always)]
2121 pub unsafe fn downcast_unchecked<T: Any>(self) -> Box<T, A> {
2122 debug_assert!(self.is::<T>());
2123 unsafe {
2124 let (raw, alloc): (*mut (dyn Any + Send + Sync), _) =
2125 Box::into_raw_with_allocator(self);
2126 Box::from_raw_in(raw as *mut T, alloc)
2127 }
2128 }
2129}
2130
2131impl<T: fmt::Display + ?Sized, A: Allocator> fmt::Display for Box<T, A> {
2132 #[inline(always)]
2133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2134 fmt::Display::fmt(&**self, f)
2135 }
2136}
2137
2138impl<T: fmt::Debug + ?Sized, A: Allocator> fmt::Debug for Box<T, A> {
2139 #[inline(always)]
2140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2141 fmt::Debug::fmt(&**self, f)
2142 }
2143}
2144
2145impl<T: ?Sized, A: Allocator> fmt::Pointer for Box<T, A> {
2146 #[inline(always)]
2147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2148 // It's not possible to extract the inner Uniq directly from the Box,
2149 // instead we cast it to a *const which aliases the Unique
2150 let ptr: *const T = &**self;
2151 fmt::Pointer::fmt(&ptr, f)
2152 }
2153}
2154
2155impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
2156 type Target = T;
2157
2158 #[inline(always)]
2159 fn deref(&self) -> &T {
2160 unsafe { self.0.as_ref() }
2161 }
2162}
2163
2164impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
2165 #[inline(always)]
2166 fn deref_mut(&mut self) -> &mut T {
2167 unsafe { self.0.as_mut() }
2168 }
2169}
2170
2171impl<I: Iterator + ?Sized, A: Allocator> Iterator for Box<I, A> {
2172 type Item = I::Item;
2173
2174 #[inline(always)]
2175 fn next(&mut self) -> Option<I::Item> {
2176 (**self).next()
2177 }
2178
2179 #[inline(always)]
2180 fn size_hint(&self) -> (usize, Option<usize>) {
2181 (**self).size_hint()
2182 }
2183
2184 #[inline(always)]
2185 fn nth(&mut self, n: usize) -> Option<I::Item> {
2186 (**self).nth(n)
2187 }
2188
2189 #[inline(always)]
2190 fn last(self) -> Option<I::Item> {
2191 BoxIter::last(self)
2192 }
2193}
2194
2195trait BoxIter {
2196 type Item;
2197 fn last(self) -> Option<Self::Item>;
2198}
2199
2200impl<I: Iterator + ?Sized, A: Allocator> BoxIter for Box<I, A> {
2201 type Item = I::Item;
2202
2203 #[inline(always)]
2204 fn last(self) -> Option<I::Item> {
2205 #[inline(always)]
2206 fn some<T>(_: Option<T>, x: T) -> Option<T> {
2207 Some(x)
2208 }
2209
2210 self.fold(None, some)
2211 }
2212}
2213
2214impl<I: DoubleEndedIterator + ?Sized, A: Allocator> DoubleEndedIterator for Box<I, A> {
2215 #[inline(always)]
2216 fn next_back(&mut self) -> Option<I::Item> {
2217 (**self).next_back()
2218 }
2219 #[inline(always)]
2220 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
2221 (**self).nth_back(n)
2222 }
2223}
2224
2225impl<I: ExactSizeIterator + ?Sized, A: Allocator> ExactSizeIterator for Box<I, A> {
2226 #[inline(always)]
2227 fn len(&self) -> usize {
2228 (**self).len()
2229 }
2230}
2231
2232impl<I: FusedIterator + ?Sized, A: Allocator> FusedIterator for Box<I, A> {}
2233
2234#[cfg(not(no_global_oom_handling))]
2235impl<I> FromIterator<I> for Box<[I]> {
2236 #[inline(always)]
2237 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
2238 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
2239 }
2240}
2241
2242#[cfg(not(no_global_oom_handling))]
2243impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
2244 #[inline(always)]
2245 fn clone(&self) -> Self {
2246 let alloc = Box::allocator(self).clone();
2247 let mut vec = Vec::with_capacity_in(self.len(), alloc);
2248 vec.extend_from_slice(self);
2249 vec.into_boxed_slice()
2250 }
2251
2252 #[inline(always)]
2253 fn clone_from(&mut self, other: &Self) {
2254 if self.len() == other.len() {
2255 self.clone_from_slice(other);
2256 } else {
2257 *self = other.clone();
2258 }
2259 }
2260}
2261
2262impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Box<T, A> {
2263 #[inline(always)]
2264 fn borrow(&self) -> &T {
2265 self
2266 }
2267}
2268
2269impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for Box<T, A> {
2270 #[inline(always)]
2271 fn borrow_mut(&mut self) -> &mut T {
2272 self
2273 }
2274}
2275
2276impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
2277 #[inline(always)]
2278 fn as_ref(&self) -> &T {
2279 self
2280 }
2281}
2282
2283impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
2284 #[inline(always)]
2285 fn as_mut(&mut self) -> &mut T {
2286 self
2287 }
2288}
2289
2290/* Nota bene
2291 *
2292 * We could have chosen not to add this impl, and instead have written a
2293 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
2294 * because Box<T> implements Unpin even when T does not, as a result of
2295 * this impl.
2296 *
2297 * We chose this API instead of the alternative for a few reasons:
2298 * - Logically, it is helpful to understand pinning in regard to the
2299 * memory region being pointed to. For this reason none of the
2300 * standard library pointer types support projecting through a pin
2301 * (Box<T> is the only pointer type in std for which this would be
2302 * safe.)
2303 * - It is in practice very useful to have Box<T> be unconditionally
2304 * Unpin because of trait objects, for which the structural auto
2305 * trait functionality does not apply (e.g., Box<dyn Foo> would
2306 * otherwise not be Unpin).
2307 *
2308 * Another type with the same semantics as Box but only a conditional
2309 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
2310 * could have a method to project a Pin<T> from it.
2311 */
2312impl<T: ?Sized, A: Allocator> Unpin for Box<T, A> where A: 'static {}
2313
2314impl<F: ?Sized + Future + Unpin, A: Allocator> Future for Box<F, A>
2315where
2316 A: 'static,
2317{
2318 type Output = F::Output;
2319
2320 #[inline(always)]
2321 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
2322 F::poll(Pin::new(&mut *self), cx)
2323 }
2324}
2325
2326#[cfg(feature = "std")]
2327mod error {
2328 use std::error::Error;
2329
2330 use super::Box;
2331
2332 #[cfg(not(no_global_oom_handling))]
2333 impl<'a, E: Error + 'a> From<E> for Box<dyn Error + 'a> {
2334 /// Converts a type of [`Error`] into a box of dyn [`Error`].
2335 ///
2336 /// # Examples
2337 ///
2338 /// ```
2339 /// use std::error::Error;
2340 /// use std::fmt;
2341 /// use std::mem;
2342 ///
2343 /// #[derive(Debug)]
2344 /// struct AnError;
2345 ///
2346 /// impl fmt::Display for AnError {
2347 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2348 /// write!(f, "An error")
2349 /// }
2350 /// }
2351 ///
2352 /// impl Error for AnError {}
2353 ///
2354 /// let an_error = AnError;
2355 /// assert!(0 == mem::size_of_val(&an_error));
2356 /// let a_boxed_error = Box::<dyn Error>::from(an_error);
2357 /// assert!(mem::size_of::<Box<dyn Error>>() == mem::size_of_val(&a_boxed_error))
2358 /// ```
2359 #[inline(always)]
2360 fn from(err: E) -> Box<dyn Error + 'a> {
2361 unsafe { Box::from_raw(Box::leak(Box::new(err))) }
2362 }
2363 }
2364
2365 #[cfg(not(no_global_oom_handling))]
2366 impl<'a, E: Error + Send + Sync + 'a> From<E> for Box<dyn Error + Send + Sync + 'a> {
2367 /// Converts a type of [`Error`] + [`Send`] + [`Sync`] into a box of
2368 /// dyn [`Error`] + [`Send`] + [`Sync`].
2369 ///
2370 /// # Examples
2371 ///
2372 /// ```
2373 /// use std::error::Error;
2374 /// use std::fmt;
2375 /// use std::mem;
2376 ///
2377 /// #[derive(Debug)]
2378 /// struct AnError;
2379 ///
2380 /// impl fmt::Display for AnError {
2381 /// fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2382 /// write!(f, "An error")
2383 /// }
2384 /// }
2385 ///
2386 /// impl Error for AnError {}
2387 ///
2388 /// unsafe impl Send for AnError {}
2389 ///
2390 /// unsafe impl Sync for AnError {}
2391 ///
2392 /// let an_error = AnError;
2393 /// assert!(0 == mem::size_of_val(&an_error));
2394 /// let a_boxed_error = Box::<dyn Error + Send + Sync>::from(an_error);
2395 /// assert!(
2396 /// mem::size_of::<Box<dyn Error + Send + Sync>>() == mem::size_of_val(&a_boxed_error))
2397 /// ```
2398 #[inline(always)]
2399 fn from(err: E) -> Box<dyn Error + Send + Sync + 'a> {
2400 unsafe { Box::from_raw(Box::leak(Box::new(err))) }
2401 }
2402 }
2403
2404 impl<T: Error> Error for Box<T> {
2405 #[inline(always)]
2406 fn source(&self) -> Option<&(dyn Error + 'static)> {
2407 Error::source(&**self)
2408 }
2409 }
2410}
2411
2412#[cfg(feature = "std")]
2413impl<R: std::io::Read + ?Sized, A: Allocator> std::io::Read for Box<R, A> {
2414 #[inline]
2415 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
2416 (**self).read(buf)
2417 }
2418
2419 #[inline]
2420 fn read_to_end(&mut self, buf: &mut std::vec::Vec<u8>) -> std::io::Result<usize> {
2421 (**self).read_to_end(buf)
2422 }
2423
2424 #[inline]
2425 fn read_to_string(&mut self, buf: &mut String) -> std::io::Result<usize> {
2426 (**self).read_to_string(buf)
2427 }
2428
2429 #[inline]
2430 fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
2431 (**self).read_exact(buf)
2432 }
2433}
2434
2435#[cfg(feature = "std")]
2436impl<W: std::io::Write + ?Sized, A: Allocator> std::io::Write for Box<W, A> {
2437 #[inline]
2438 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
2439 (**self).write(buf)
2440 }
2441
2442 #[inline]
2443 fn flush(&mut self) -> std::io::Result<()> {
2444 (**self).flush()
2445 }
2446
2447 #[inline]
2448 fn write_all(&mut self, buf: &[u8]) -> std::io::Result<()> {
2449 (**self).write_all(buf)
2450 }
2451
2452 #[inline]
2453 fn write_fmt(&mut self, fmt: fmt::Arguments<'_>) -> std::io::Result<()> {
2454 (**self).write_fmt(fmt)
2455 }
2456}
2457
2458#[cfg(feature = "std")]
2459impl<S: std::io::Seek + ?Sized, A: Allocator> std::io::Seek for Box<S, A> {
2460 #[inline]
2461 fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
2462 (**self).seek(pos)
2463 }
2464
2465 #[inline]
2466 fn stream_position(&mut self) -> std::io::Result<u64> {
2467 (**self).stream_position()
2468 }
2469}
2470
2471#[cfg(feature = "std")]
2472impl<B: std::io::BufRead + ?Sized, A: Allocator> std::io::BufRead for Box<B, A> {
2473 #[inline]
2474 fn fill_buf(&mut self) -> std::io::Result<&[u8]> {
2475 (**self).fill_buf()
2476 }
2477
2478 #[inline]
2479 fn consume(&mut self, amt: usize) {
2480 (**self).consume(amt)
2481 }
2482
2483 #[inline]
2484 fn read_until(&mut self, byte: u8, buf: &mut std::vec::Vec<u8>) -> std::io::Result<usize> {
2485 (**self).read_until(byte, buf)
2486 }
2487
2488 #[inline]
2489 fn read_line(&mut self, buf: &mut std::string::String) -> std::io::Result<usize> {
2490 (**self).read_line(buf)
2491 }
2492}
2493
2494#[cfg(feature = "alloc")]
2495impl<A: Allocator> Extend<Box<str, A>> for alloc_crate::string::String {
2496 fn extend<I: IntoIterator<Item = Box<str, A>>>(&mut self, iter: I) {
2497 iter.into_iter().for_each(move |s| self.push_str(&s));
2498 }
2499}
2500
2501#[cfg(not(no_global_oom_handling))]
2502#[cfg(feature = "std")]
2503impl Clone for Box<std::ffi::CStr> {
2504 #[inline]
2505 fn clone(&self) -> Self {
2506 (**self).into()
2507 }
2508}
2509
2510#[cfg(not(no_global_oom_handling))]
2511#[cfg(feature = "std")]
2512impl From<&std::ffi::CStr> for Box<std::ffi::CStr> {
2513 /// Converts a `&CStr` into a `Box<CStr>`,
2514 /// by copying the contents into a newly allocated [`Box`].
2515 fn from(s: &std::ffi::CStr) -> Box<std::ffi::CStr> {
2516 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
2517 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut std::ffi::CStr) }
2518 }
2519}
2520
2521#[cfg(not(no_global_oom_handling))]
2522#[cfg(all(feature = "fresh-rust", not(feature = "std")))]
2523impl Clone for Box<core::ffi::CStr> {
2524 #[inline]
2525 fn clone(&self) -> Self {
2526 (**self).into()
2527 }
2528}
2529
2530#[cfg(not(no_global_oom_handling))]
2531#[cfg(all(feature = "fresh-rust", not(feature = "std")))]
2532impl From<&core::ffi::CStr> for Box<core::ffi::CStr> {
2533 /// Converts a `&CStr` into a `Box<CStr>`,
2534 /// by copying the contents into a newly allocated [`Box`].
2535 fn from(s: &core::ffi::CStr) -> Box<core::ffi::CStr> {
2536 let boxed: Box<[u8]> = Box::from(s.to_bytes_with_nul());
2537 unsafe { Box::from_raw(Box::into_raw(boxed) as *mut core::ffi::CStr) }
2538 }
2539}
2540
2541#[cfg(feature = "serde")]
2542impl<T, A> serde::Serialize for Box<T, A>
2543where
2544 T: serde::Serialize,
2545 A: Allocator,
2546{
2547 #[inline(always)]
2548 fn serialize<S: serde::ser::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2549 (**self).serialize(serializer)
2550 }
2551}
2552
2553#[cfg(feature = "serde")]
2554impl<'de, T, A> serde::Deserialize<'de> for Box<T, A>
2555where
2556 T: serde::Deserialize<'de>,
2557 A: Allocator + Default,
2558{
2559 #[inline(always)]
2560 fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2561 let value = T::deserialize(deserializer)?;
2562 Ok(Box::new_in(value, A::default()))
2563 }
2564}