1 //! A pointer type for heap allocation.
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.
10 //! Move a value from the stack to the heap by creating a [`Box`]:
14 //! let boxed: Box<u8> = Box::new(val);
17 //! Move a value from a [`Box`] back to the stack by [dereferencing]:
20 //! let boxed: Box<u8> = Box::new(5);
21 //! let val: u8 = *boxed;
24 //! Creating a recursive data structure:
29 //! Cons(T, Box<List<T>>),
33 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
34 //! println!("{:?}", list);
37 //! This will print `Cons(1, Cons(2, Nil))`.
39 //! Recursive structures must be boxed, because if the definition of `Cons`
42 //! ```compile_fail,E0072
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.
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)`].
65 //! So long as `T: Sized`, a `Box<T>` is guaranteed to be represented
66 //! as a single pointer and is also ABI-compatible with C pointers
67 //! (i.e. the C type `T*`). This means that if you have extern "C"
68 //! Rust functions that will be called from C, you can define those
69 //! Rust functions using `Box<T>` types, and use `T*` as corresponding
70 //! type on the C side. As an example, consider this C header which
71 //! declares functions that create and destroy some kind of `Foo`
77 //! /* Returns ownership to the caller */
78 //! struct Foo* foo_new(void);
80 //! /* Takes ownership from the caller; no-op when invoked with NULL */
81 //! void foo_delete(struct Foo*);
84 //! These two functions might be implemented in Rust as follows. Here, the
85 //! `struct Foo*` type from C is translated to `Box<Foo>`, which captures
86 //! the ownership constraints. Note also that the nullable argument to
87 //! `foo_delete` is represented in Rust as `Option<Box<Foo>>`, since `Box<Foo>`
95 //! #[allow(improper_ctypes_definitions)]
96 //! pub extern "C" fn foo_new() -> Box<Foo> {
101 //! #[allow(improper_ctypes_definitions)]
102 //! pub extern "C" fn foo_delete(_: Option<Box<Foo>>) {}
105 //! Even though `Box<T>` has the same representation and C ABI as a C pointer,
106 //! this does not mean that you can convert an arbitrary `T*` into a `Box<T>`
107 //! and expect things to work. `Box<T>` values will always be fully aligned,
108 //! non-null pointers. Moreover, the destructor for `Box<T>` will attempt to
109 //! free the value with the global allocator. In general, the best practice
110 //! is to only use `Box<T>` for pointers that originated from the global
113 //! **Important.** At least at present, you should avoid using
114 //! `Box<T>` types for functions that are defined in C but invoked
115 //! from Rust. In those cases, you should directly mirror the C types
116 //! as closely as possible. Using types like `Box<T>` where the C
117 //! definition is just using `T*` can lead to undefined behavior, as
118 //! described in [rust-lang/unsafe-code-guidelines#198][ucg#198].
120 //! [ucg#198]: https://github.com/rust-lang/unsafe-code-guidelines/issues/198
121 //! [dereferencing]: core::ops::Deref
123 //! [`Box::<T>::from_raw(value)`]: Box::from_raw
124 //! [`Box::<T>::into_raw`]: Box::into_raw
125 //! [`Global`]: crate::alloc::Global
126 //! [`Layout`]: crate::alloc::Layout
127 //! [`Layout::for_value(&*value)`]: crate::alloc::Layout::for_value
129 #![stable(feature = "rust1", since = "1.0.0")]
133 use core::cmp::Ordering;
134 use core::convert::{From, TryFrom};
136 use core::future::Future;
137 use core::hash::{Hash, Hasher};
138 use core::iter::{FromIterator, FusedIterator, Iterator};
139 use core::marker::{Unpin, Unsize};
142 CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Generator, GeneratorState, Receiver,
145 use core::ptr::{self, Unique};
146 use core::task::{Context, Poll};
148 use crate::alloc::{handle_alloc_error, AllocRef, Global, Layout};
149 use crate::borrow::Cow;
150 use crate::raw_vec::RawVec;
151 use crate::str::from_boxed_utf8_unchecked;
154 /// A pointer type for heap allocation.
156 /// See the [module-level documentation](../../std/boxed/index.html) for more.
157 #[lang = "owned_box"]
159 #[stable(feature = "rust1", since = "1.0.0")]
162 #[unstable(feature = "allocator_api", issue = "32838")] A: AllocRef = Global,
166 /// Allocates memory on the heap and then places `x` into it.
168 /// This doesn't actually allocate if `T` is zero-sized.
173 /// let five = Box::new(5);
175 #[stable(feature = "rust1", since = "1.0.0")]
177 pub fn new(x: T) -> Self {
181 /// Constructs a new box with uninitialized contents.
186 /// #![feature(new_uninit)]
188 /// let mut five = Box::<u32>::new_uninit();
190 /// let five = unsafe {
191 /// // Deferred initialization:
192 /// five.as_mut_ptr().write(5);
194 /// five.assume_init()
197 /// assert_eq!(*five, 5)
199 #[unstable(feature = "new_uninit", issue = "63291")]
201 pub fn new_uninit() -> Box<mem::MaybeUninit<T>> {
202 Self::new_uninit_in(Global)
205 /// Constructs a new `Box` with uninitialized contents, with the memory
206 /// being filled with `0` bytes.
208 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
214 /// #![feature(new_uninit)]
216 /// let zero = Box::<u32>::new_zeroed();
217 /// let zero = unsafe { zero.assume_init() };
219 /// assert_eq!(*zero, 0)
222 /// [zeroed]: mem::MaybeUninit::zeroed
223 #[unstable(feature = "new_uninit", issue = "63291")]
225 pub fn new_zeroed() -> Box<mem::MaybeUninit<T>> {
226 Self::new_zeroed_in(Global)
229 /// Constructs a new `Pin<Box<T>>`. If `T` does not implement `Unpin`, then
230 /// `x` will be pinned in memory and unable to be moved.
231 #[stable(feature = "pin", since = "1.33.0")]
233 pub fn pin(x: T) -> Pin<Box<T>> {
238 impl<T, A: AllocRef> Box<T, A> {
239 /// Allocates memory in the given allocator then places `x` into it.
241 /// This doesn't actually allocate if `T` is zero-sized.
246 /// #![feature(allocator_api)]
248 /// use std::alloc::System;
250 /// let five = Box::new_in(5, System);
252 #[unstable(feature = "allocator_api", issue = "32838")]
254 pub fn new_in(x: T, alloc: A) -> Self {
255 let mut boxed = Self::new_uninit_in(alloc);
257 boxed.as_mut_ptr().write(x);
262 /// Constructs a new box with uninitialized contents in the provided allocator.
267 /// #![feature(allocator_api, new_uninit)]
269 /// use std::alloc::System;
271 /// let mut five = Box::<u32, _>::new_uninit_in(System);
273 /// let five = unsafe {
274 /// // Deferred initialization:
275 /// five.as_mut_ptr().write(5);
277 /// five.assume_init()
280 /// assert_eq!(*five, 5)
282 #[unstable(feature = "allocator_api", issue = "32838")]
283 // #[unstable(feature = "new_uninit", issue = "63291")]
284 pub fn new_uninit_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
285 let layout = Layout::new::<mem::MaybeUninit<T>>();
286 let ptr = alloc.alloc(layout).unwrap_or_else(|_| handle_alloc_error(layout)).cast();
287 unsafe { Box::from_raw_in(ptr.as_ptr(), alloc) }
290 /// Constructs a new `Box` with uninitialized contents, with the memory
291 /// being filled with `0` bytes in the provided allocator.
293 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
299 /// #![feature(allocator_api, new_uninit)]
301 /// use std::alloc::System;
303 /// let zero = Box::<u32, _>::new_zeroed_in(System);
304 /// let zero = unsafe { zero.assume_init() };
306 /// assert_eq!(*zero, 0)
309 /// [zeroed]: mem::MaybeUninit::zeroed
310 #[unstable(feature = "allocator_api", issue = "32838")]
311 // #[unstable(feature = "new_uninit", issue = "63291")]
312 pub fn new_zeroed_in(alloc: A) -> Box<mem::MaybeUninit<T>, A> {
313 let layout = Layout::new::<mem::MaybeUninit<T>>();
314 let ptr = alloc.alloc_zeroed(layout).unwrap_or_else(|_| handle_alloc_error(layout)).cast();
315 unsafe { Box::from_raw_in(ptr.as_ptr(), alloc) }
318 /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement `Unpin`, then
319 /// `x` will be pinned in memory and unable to be moved.
320 #[unstable(feature = "allocator_api", issue = "32838")]
322 pub fn pin_in(x: T, alloc: A) -> Pin<Self> {
323 Self::new_in(x, alloc).into()
326 /// Converts a `Box<T>` into a `Box<[T]>`
328 /// This conversion does not allocate on the heap and happens in place.
329 #[unstable(feature = "box_into_boxed_slice", issue = "71582")]
330 pub fn into_boxed_slice(boxed: Self) -> Box<[T], A> {
331 let (raw, alloc) = Box::into_raw_with_alloc(boxed);
332 unsafe { Box::from_raw_in(raw as *mut [T; 1], alloc) }
337 /// Constructs a new boxed slice with uninitialized contents.
342 /// #![feature(new_uninit)]
344 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
346 /// let values = unsafe {
347 /// // Deferred initialization:
348 /// values[0].as_mut_ptr().write(1);
349 /// values[1].as_mut_ptr().write(2);
350 /// values[2].as_mut_ptr().write(3);
352 /// values.assume_init()
355 /// assert_eq!(*values, [1, 2, 3])
357 #[unstable(feature = "new_uninit", issue = "63291")]
358 pub fn new_uninit_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
359 unsafe { RawVec::with_capacity(len).into_box(len) }
362 /// Constructs a new boxed slice with uninitialized contents, with the memory
363 /// being filled with `0` bytes.
365 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
371 /// #![feature(new_uninit)]
373 /// let values = Box::<[u32]>::new_zeroed_slice(3);
374 /// let values = unsafe { values.assume_init() };
376 /// assert_eq!(*values, [0, 0, 0])
379 /// [zeroed]: mem::MaybeUninit::zeroed
380 #[unstable(feature = "new_uninit", issue = "63291")]
381 pub fn new_zeroed_slice(len: usize) -> Box<[mem::MaybeUninit<T>]> {
382 unsafe { RawVec::with_capacity_zeroed(len).into_box(len) }
386 impl<T, A: AllocRef> Box<[T], A> {
387 /// Constructs a new boxed slice with uninitialized contents in the provided allocator.
392 /// #![feature(allocator_api, new_uninit)]
394 /// use std::alloc::System;
396 /// let mut values = Box::<[u32], _>::new_uninit_slice_in(3, System);
398 /// let values = unsafe {
399 /// // Deferred initialization:
400 /// values[0].as_mut_ptr().write(1);
401 /// values[1].as_mut_ptr().write(2);
402 /// values[2].as_mut_ptr().write(3);
404 /// values.assume_init()
407 /// assert_eq!(*values, [1, 2, 3])
409 #[unstable(feature = "allocator_api", issue = "32838")]
410 // #[unstable(feature = "new_uninit", issue = "63291")]
411 pub fn new_uninit_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
412 unsafe { RawVec::with_capacity_in(len, alloc).into_box(len) }
415 /// Constructs a new boxed slice with uninitialized contents in the provided allocator,
416 /// with the memory being filled with `0` bytes.
418 /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage
424 /// #![feature(allocator_api, new_uninit)]
426 /// use std::alloc::System;
428 /// let values = Box::<[u32], _>::new_zeroed_slice_in(3, System);
429 /// let values = unsafe { values.assume_init() };
431 /// assert_eq!(*values, [0, 0, 0])
434 /// [zeroed]: mem::MaybeUninit::zeroed
435 #[unstable(feature = "allocator_api", issue = "32838")]
436 // #[unstable(feature = "new_uninit", issue = "63291")]
437 pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Box<[mem::MaybeUninit<T>], A> {
438 unsafe { RawVec::with_capacity_zeroed_in(len, alloc).into_box(len) }
442 impl<T, A: AllocRef> Box<mem::MaybeUninit<T>, A> {
443 /// Converts to `Box<T, A>`.
447 /// As with [`MaybeUninit::assume_init`],
448 /// it is up to the caller to guarantee that the value
449 /// really is in an initialized state.
450 /// Calling this when the content is not yet fully initialized
451 /// causes immediate undefined behavior.
453 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
458 /// #![feature(new_uninit)]
460 /// let mut five = Box::<u32>::new_uninit();
462 /// let five: Box<u32> = unsafe {
463 /// // Deferred initialization:
464 /// five.as_mut_ptr().write(5);
466 /// five.assume_init()
469 /// assert_eq!(*five, 5)
471 #[unstable(feature = "new_uninit", issue = "63291")]
473 pub unsafe fn assume_init(self) -> Box<T, A> {
474 let (raw, alloc) = Box::into_raw_with_alloc(self);
475 unsafe { Box::from_raw_in(raw as *mut T, alloc) }
479 impl<T, A: AllocRef> Box<[mem::MaybeUninit<T>], A> {
480 /// Converts to `Box<[T], A>`.
484 /// As with [`MaybeUninit::assume_init`],
485 /// it is up to the caller to guarantee that the values
486 /// really are in an initialized state.
487 /// Calling this when the content is not yet fully initialized
488 /// causes immediate undefined behavior.
490 /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init
495 /// #![feature(new_uninit)]
497 /// let mut values = Box::<[u32]>::new_uninit_slice(3);
499 /// let values = unsafe {
500 /// // Deferred initialization:
501 /// values[0].as_mut_ptr().write(1);
502 /// values[1].as_mut_ptr().write(2);
503 /// values[2].as_mut_ptr().write(3);
505 /// values.assume_init()
508 /// assert_eq!(*values, [1, 2, 3])
510 #[unstable(feature = "new_uninit", issue = "63291")]
512 pub unsafe fn assume_init(self) -> Box<[T], A> {
513 let (raw, alloc) = Box::into_raw_with_alloc(self);
514 unsafe { Box::from_raw_in(raw as *mut [T], alloc) }
518 impl<T: ?Sized> Box<T> {
519 /// Constructs a box from a raw pointer.
521 /// After calling this function, the raw pointer is owned by the
522 /// resulting `Box`. Specifically, the `Box` destructor will call
523 /// the destructor of `T` and free the allocated memory. For this
524 /// to be safe, the memory must have been allocated in accordance
525 /// with the [memory layout] used by `Box` .
529 /// This function is unsafe because improper use may lead to
530 /// memory problems. For example, a double-free may occur if the
531 /// function is called twice on the same raw pointer.
534 /// Recreate a `Box` which was previously converted to a raw pointer
535 /// using [`Box::into_raw`]:
537 /// let x = Box::new(5);
538 /// let ptr = Box::into_raw(x);
539 /// let x = unsafe { Box::from_raw(ptr) };
541 /// Manually create a `Box` from scratch by using the global allocator:
543 /// use std::alloc::{alloc, Layout};
546 /// let ptr = alloc(Layout::new::<i32>()) as *mut i32;
547 /// // In general .write is required to avoid attempting to destruct
548 /// // the (uninitialized) previous contents of `ptr`, though for this
549 /// // simple example `*ptr = 5` would have worked as well.
551 /// let x = Box::from_raw(ptr);
555 /// [memory layout]: self#memory-layout
556 /// [`Layout`]: crate::Layout
557 #[stable(feature = "box_raw", since = "1.4.0")]
559 pub unsafe fn from_raw(raw: *mut T) -> Self {
560 unsafe { Self::from_raw_in(raw, Global) }
564 impl<T: ?Sized, A: AllocRef> Box<T, A> {
565 /// Constructs a box from a raw pointer in the given allocator.
567 /// After calling this function, the raw pointer is owned by the
568 /// resulting `Box`. Specifically, the `Box` destructor will call
569 /// the destructor of `T` and free the allocated memory. For this
570 /// to be safe, the memory must have been allocated in accordance
571 /// with the [memory layout] used by `Box` .
575 /// This function is unsafe because improper use may lead to
576 /// memory problems. For example, a double-free may occur if the
577 /// function is called twice on the same raw pointer.
582 /// Recreate a `Box` which was previously converted to a raw pointer
583 /// using [`Box::into_raw_with_alloc`]:
585 /// #![feature(allocator_api)]
587 /// use std::alloc::System;
589 /// let x = Box::new_in(5, System);
590 /// let (ptr, alloc) = Box::into_raw_with_alloc(x);
591 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
593 /// Manually create a `Box` from scratch by using the system allocator:
595 /// #![feature(allocator_api, slice_ptr_get)]
597 /// use std::alloc::{AllocRef, Layout, System};
600 /// let ptr = System.alloc(Layout::new::<i32>())?.as_mut_ptr();
601 /// // In general .write is required to avoid attempting to destruct
602 /// // the (uninitialized) previous contents of `ptr`, though for this
603 /// // simple example `*ptr = 5` would have worked as well.
605 /// let x = Box::from_raw_in(ptr, System);
607 /// # Ok::<(), std::alloc::AllocError>(())
610 /// [memory layout]: self#memory-layout
611 /// [`Layout`]: crate::Layout
612 #[unstable(feature = "allocator_api", issue = "32838")]
614 pub unsafe fn from_raw_in(raw: *mut T, alloc: A) -> Self {
615 Box(unsafe { Unique::new_unchecked(raw) }, alloc)
618 /// Consumes the `Box`, returning a wrapped raw pointer.
620 /// The pointer will be properly aligned and non-null.
622 /// After calling this function, the caller is responsible for the
623 /// memory previously managed by the `Box`. In particular, the
624 /// caller should properly destroy `T` and release the memory, taking
625 /// into account the [memory layout] used by `Box`. The easiest way to
626 /// do this is to convert the raw pointer back into a `Box` with the
627 /// [`Box::from_raw`] function, allowing the `Box` destructor to perform
630 /// Note: this is an associated function, which means that you have
631 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
632 /// is so that there is no conflict with a method on the inner type.
635 /// Converting the raw pointer back into a `Box` with [`Box::from_raw`]
636 /// for automatic cleanup:
638 /// let x = Box::new(String::from("Hello"));
639 /// let ptr = Box::into_raw(x);
640 /// let x = unsafe { Box::from_raw(ptr) };
642 /// Manual cleanup by explicitly running the destructor and deallocating
645 /// use std::alloc::{dealloc, Layout};
648 /// let x = Box::new(String::from("Hello"));
649 /// let p = Box::into_raw(x);
651 /// ptr::drop_in_place(p);
652 /// dealloc(p as *mut u8, Layout::new::<String>());
656 /// [memory layout]: self#memory-layout
657 #[stable(feature = "box_raw", since = "1.4.0")]
659 pub fn into_raw(b: Self) -> *mut T {
660 Self::into_raw_with_alloc(b).0
663 /// Consumes the `Box`, returning a wrapped raw pointer and the allocator.
665 /// The pointer will be properly aligned and non-null.
667 /// After calling this function, the caller is responsible for the
668 /// memory previously managed by the `Box`. In particular, the
669 /// caller should properly destroy `T` and release the memory, taking
670 /// into account the [memory layout] used by `Box`. The easiest way to
671 /// do this is to convert the raw pointer back into a `Box` with the
672 /// [`Box::from_raw_in`] function, allowing the `Box` destructor to perform
675 /// Note: this is an associated function, which means that you have
676 /// to call it as `Box::into_raw_with_alloc(b)` instead of `b.into_raw_with_alloc()`. This
677 /// is so that there is no conflict with a method on the inner type.
680 /// Converting the raw pointer back into a `Box` with [`Box::from_raw_in`]
681 /// for automatic cleanup:
683 /// #![feature(allocator_api)]
685 /// use std::alloc::System;
687 /// let x = Box::new_in(String::from("Hello"), System);
688 /// let (ptr, alloc) = Box::into_raw_with_alloc(x);
689 /// let x = unsafe { Box::from_raw_in(ptr, alloc) };
691 /// Manual cleanup by explicitly running the destructor and deallocating
694 /// #![feature(allocator_api)]
696 /// use std::alloc::{AllocRef, Layout, System};
697 /// use std::ptr::{self, NonNull};
699 /// let x = Box::new_in(String::from("Hello"), System);
700 /// let (ptr, alloc) = Box::into_raw_with_alloc(x);
702 /// ptr::drop_in_place(ptr);
703 /// let non_null = NonNull::new_unchecked(ptr);
704 /// alloc.dealloc(non_null.cast(), Layout::new::<String>());
708 /// [memory layout]: self#memory-layout
709 #[unstable(feature = "allocator_api", issue = "32838")]
711 pub fn into_raw_with_alloc(b: Self) -> (*mut T, A) {
712 let (leaked, alloc) = Box::into_unique(b);
713 (leaked.as_ptr(), alloc)
717 feature = "ptr_internals",
719 reason = "use `Box::leak(b).into()` or `Unique::from(Box::leak(b))` instead"
723 pub fn into_unique(b: Self) -> (Unique<T>, A) {
724 // Box is recognized as a "unique pointer" by Stacked Borrows, but internally it is a
725 // raw pointer for the type system. Turning it directly into a raw pointer would not be
726 // recognized as "releasing" the unique pointer to permit aliased raw accesses,
727 // so all raw pointer methods have to leak the box. Turning *that* to a raw pointer
728 // behaves correctly.
729 let b = mem::ManuallyDrop::new(b);
731 // The box is unitiliazed later when moving out the allocator. The pointer is stored
734 let alloc = unsafe { ptr::read(&b.1) };
738 /// Returns a reference to the underlying allocator.
740 /// Note: this is an associated function, which means that you have
741 /// to call it as `Box::alloc_ref(&b)` instead of `b.alloc_ref()`. This
742 /// is so that there is no conflict with a method on the inner type.
743 #[unstable(feature = "allocator_api", issue = "32838")]
745 pub fn alloc_ref(b: &Self) -> &A {
749 /// Consumes and leaks the `Box`, returning a mutable reference,
750 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
751 /// `'a`. If the type has only static references, or none at all, then this
752 /// may be chosen to be `'static`.
754 /// This function is mainly useful for data that lives for the remainder of
755 /// the program's life. Dropping the returned reference will cause a memory
756 /// leak. If this is not acceptable, the reference should first be wrapped
757 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
758 /// then be dropped which will properly destroy `T` and release the
759 /// allocated memory.
761 /// Note: this is an associated function, which means that you have
762 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
763 /// is so that there is no conflict with a method on the inner type.
770 /// let x = Box::new(41);
771 /// let static_ref: &'static mut usize = Box::leak(x);
772 /// *static_ref += 1;
773 /// assert_eq!(*static_ref, 42);
779 /// let x = vec![1, 2, 3].into_boxed_slice();
780 /// let static_ref = Box::leak(x);
781 /// static_ref[0] = 4;
782 /// assert_eq!(*static_ref, [4, 2, 3]);
784 #[stable(feature = "box_leak", since = "1.26.0")]
786 pub fn leak<'a>(b: Self) -> &'a mut T
790 unsafe { &mut *mem::ManuallyDrop::new(b).0.as_ptr() }
793 /// Converts a `Box<T>` into a `Pin<Box<T>>`
795 /// This conversion does not allocate on the heap and happens in place.
797 /// This is also available via [`From`].
798 #[unstable(feature = "box_into_pin", issue = "62370")]
799 pub fn into_pin(boxed: Self) -> Pin<Self> {
800 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
801 // when `T: !Unpin`, so it's safe to pin it directly without any
802 // additional requirements.
803 unsafe { Pin::new_unchecked(boxed) }
807 #[stable(feature = "rust1", since = "1.0.0")]
808 unsafe impl<#[may_dangle] T: ?Sized, A: AllocRef> Drop for Box<T, A> {
810 // FIXME: Do nothing, drop is currently performed by compiler.
814 #[stable(feature = "rust1", since = "1.0.0")]
815 impl<T: Default> Default for Box<T> {
816 /// Creates a `Box<T>`, with the `Default` value for T.
817 fn default() -> Self {
822 #[stable(feature = "rust1", since = "1.0.0")]
823 impl<T> Default for Box<[T]> {
824 fn default() -> Self {
825 Box::<[T; 0]>::new([])
829 #[stable(feature = "default_box_extra", since = "1.17.0")]
830 impl Default for Box<str> {
831 fn default() -> Self {
832 unsafe { from_boxed_utf8_unchecked(Default::default()) }
836 #[stable(feature = "rust1", since = "1.0.0")]
837 impl<T: Clone, A: AllocRef + Clone> Clone for Box<T, A> {
838 /// Returns a new box with a `clone()` of this box's contents.
843 /// let x = Box::new(5);
844 /// let y = x.clone();
846 /// // The value is the same
847 /// assert_eq!(x, y);
849 /// // But they are unique objects
850 /// assert_ne!(&*x as *const i32, &*y as *const i32);
854 fn clone(&self) -> Self {
855 Self::new_in((**self).clone(), self.1.clone())
858 /// Copies `source`'s contents into `self` without creating a new allocation.
863 /// let x = Box::new(5);
864 /// let mut y = Box::new(10);
865 /// let yp: *const i32 = &*y;
867 /// y.clone_from(&x);
869 /// // The value is the same
870 /// assert_eq!(x, y);
872 /// // And no allocation occurred
873 /// assert_eq!(yp, &*y);
876 fn clone_from(&mut self, source: &Self) {
877 (**self).clone_from(&(**source));
881 #[stable(feature = "box_slice_clone", since = "1.3.0")]
882 impl Clone for Box<str> {
883 fn clone(&self) -> Self {
884 // this makes a copy of the data
885 let buf: Box<[u8]> = self.as_bytes().into();
886 unsafe { from_boxed_utf8_unchecked(buf) }
890 #[stable(feature = "rust1", since = "1.0.0")]
891 impl<T: ?Sized + PartialEq, A: AllocRef> PartialEq for Box<T, A> {
893 fn eq(&self, other: &Self) -> bool {
894 PartialEq::eq(&**self, &**other)
897 fn ne(&self, other: &Self) -> bool {
898 PartialEq::ne(&**self, &**other)
901 #[stable(feature = "rust1", since = "1.0.0")]
902 impl<T: ?Sized + PartialOrd, A: AllocRef> PartialOrd for Box<T, A> {
904 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
905 PartialOrd::partial_cmp(&**self, &**other)
908 fn lt(&self, other: &Self) -> bool {
909 PartialOrd::lt(&**self, &**other)
912 fn le(&self, other: &Self) -> bool {
913 PartialOrd::le(&**self, &**other)
916 fn ge(&self, other: &Self) -> bool {
917 PartialOrd::ge(&**self, &**other)
920 fn gt(&self, other: &Self) -> bool {
921 PartialOrd::gt(&**self, &**other)
924 #[stable(feature = "rust1", since = "1.0.0")]
925 impl<T: ?Sized + Ord, A: AllocRef> Ord for Box<T, A> {
927 fn cmp(&self, other: &Self) -> Ordering {
928 Ord::cmp(&**self, &**other)
931 #[stable(feature = "rust1", since = "1.0.0")]
932 impl<T: ?Sized + Eq, A: AllocRef> Eq for Box<T, A> {}
934 #[stable(feature = "rust1", since = "1.0.0")]
935 impl<T: ?Sized + Hash, A: AllocRef> Hash for Box<T, A> {
936 fn hash<H: Hasher>(&self, state: &mut H) {
937 (**self).hash(state);
941 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
942 impl<T: ?Sized + Hasher, A: AllocRef> Hasher for Box<T, A> {
943 fn finish(&self) -> u64 {
946 fn write(&mut self, bytes: &[u8]) {
947 (**self).write(bytes)
949 fn write_u8(&mut self, i: u8) {
952 fn write_u16(&mut self, i: u16) {
953 (**self).write_u16(i)
955 fn write_u32(&mut self, i: u32) {
956 (**self).write_u32(i)
958 fn write_u64(&mut self, i: u64) {
959 (**self).write_u64(i)
961 fn write_u128(&mut self, i: u128) {
962 (**self).write_u128(i)
964 fn write_usize(&mut self, i: usize) {
965 (**self).write_usize(i)
967 fn write_i8(&mut self, i: i8) {
970 fn write_i16(&mut self, i: i16) {
971 (**self).write_i16(i)
973 fn write_i32(&mut self, i: i32) {
974 (**self).write_i32(i)
976 fn write_i64(&mut self, i: i64) {
977 (**self).write_i64(i)
979 fn write_i128(&mut self, i: i128) {
980 (**self).write_i128(i)
982 fn write_isize(&mut self, i: isize) {
983 (**self).write_isize(i)
987 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
988 impl<T> From<T> for Box<T> {
989 /// Converts a generic type `T` into a `Box<T>`
991 /// The conversion allocates on the heap and moves `t`
992 /// from the stack into it.
997 /// let boxed = Box::new(5);
999 /// assert_eq!(Box::from(x), boxed);
1001 fn from(t: T) -> Self {
1006 #[stable(feature = "pin", since = "1.33.0")]
1007 impl<T: ?Sized, A: AllocRef> From<Box<T, A>> for Pin<Box<T, A>> {
1008 /// Converts a `Box<T>` into a `Pin<Box<T>>`
1010 /// This conversion does not allocate on the heap and happens in place.
1011 fn from(boxed: Box<T, A>) -> Self {
1012 Box::into_pin(boxed)
1016 #[stable(feature = "box_from_slice", since = "1.17.0")]
1017 impl<T: Copy> From<&[T]> for Box<[T]> {
1018 /// Converts a `&[T]` into a `Box<[T]>`
1020 /// This conversion allocates on the heap
1021 /// and performs a copy of `slice`.
1025 /// // create a &[u8] which will be used to create a Box<[u8]>
1026 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1027 /// let boxed_slice: Box<[u8]> = Box::from(slice);
1029 /// println!("{:?}", boxed_slice);
1031 fn from(slice: &[T]) -> Box<[T]> {
1032 let len = slice.len();
1033 let buf = RawVec::with_capacity(len);
1035 ptr::copy_nonoverlapping(slice.as_ptr(), buf.ptr(), len);
1036 buf.into_box(slice.len()).assume_init()
1041 #[stable(feature = "box_from_cow", since = "1.45.0")]
1042 impl<T: Copy> From<Cow<'_, [T]>> for Box<[T]> {
1044 fn from(cow: Cow<'_, [T]>) -> Box<[T]> {
1046 Cow::Borrowed(slice) => Box::from(slice),
1047 Cow::Owned(slice) => Box::from(slice),
1052 #[stable(feature = "box_from_slice", since = "1.17.0")]
1053 impl From<&str> for Box<str> {
1054 /// Converts a `&str` into a `Box<str>`
1056 /// This conversion allocates on the heap
1057 /// and performs a copy of `s`.
1061 /// let boxed: Box<str> = Box::from("hello");
1062 /// println!("{}", boxed);
1065 fn from(s: &str) -> Box<str> {
1066 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
1070 #[stable(feature = "box_from_cow", since = "1.45.0")]
1071 impl From<Cow<'_, str>> for Box<str> {
1073 fn from(cow: Cow<'_, str>) -> Box<str> {
1075 Cow::Borrowed(s) => Box::from(s),
1076 Cow::Owned(s) => Box::from(s),
1081 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
1082 impl<A: AllocRef> From<Box<str, A>> for Box<[u8], A> {
1083 /// Converts a `Box<str>` into a `Box<[u8]>`
1085 /// This conversion does not allocate on the heap and happens in place.
1089 /// // create a Box<str> which will be used to create a Box<[u8]>
1090 /// let boxed: Box<str> = Box::from("hello");
1091 /// let boxed_str: Box<[u8]> = Box::from(boxed);
1093 /// // create a &[u8] which will be used to create a Box<[u8]>
1094 /// let slice: &[u8] = &[104, 101, 108, 108, 111];
1095 /// let boxed_slice = Box::from(slice);
1097 /// assert_eq!(boxed_slice, boxed_str);
1100 fn from(s: Box<str, A>) -> Self {
1101 let (raw, alloc) = Box::into_raw_with_alloc(s);
1102 unsafe { Box::from_raw_in(raw as *mut [u8], alloc) }
1106 #[stable(feature = "box_from_array", since = "1.45.0")]
1107 impl<T, const N: usize> From<[T; N]> for Box<[T]> {
1108 /// Converts a `[T; N]` into a `Box<[T]>`
1110 /// This conversion moves the array to newly heap-allocated memory.
1114 /// let boxed: Box<[u8]> = Box::from([4, 2]);
1115 /// println!("{:?}", boxed);
1117 fn from(array: [T; N]) -> Box<[T]> {
1122 #[stable(feature = "boxed_slice_try_from", since = "1.43.0")]
1123 impl<T, const N: usize> TryFrom<Box<[T]>> for Box<[T; N]> {
1124 type Error = Box<[T]>;
1126 fn try_from(boxed_slice: Box<[T]>) -> Result<Self, Self::Error> {
1127 if boxed_slice.len() == N {
1128 Ok(unsafe { Box::from_raw(Box::into_raw(boxed_slice) as *mut [T; N]) })
1135 impl<A: AllocRef> Box<dyn Any, A> {
1137 #[stable(feature = "rust1", since = "1.0.0")]
1138 /// Attempt to downcast the box to a concrete type.
1143 /// use std::any::Any;
1145 /// fn print_if_string(value: Box<dyn Any>) {
1146 /// if let Ok(string) = value.downcast::<String>() {
1147 /// println!("String ({}): {}", string.len(), string);
1151 /// let my_string = "Hello World".to_string();
1152 /// print_if_string(Box::new(my_string));
1153 /// print_if_string(Box::new(0i8));
1155 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1158 let (raw, alloc): (*mut dyn Any, _) = Box::into_raw_with_alloc(self);
1159 Ok(Box::from_raw_in(raw as *mut T, alloc))
1167 impl<A: AllocRef> Box<dyn Any + Send, A> {
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 /// Attempt to downcast the box to a concrete type.
1175 /// use std::any::Any;
1177 /// fn print_if_string(value: Box<dyn Any + Send>) {
1178 /// if let Ok(string) = value.downcast::<String>() {
1179 /// println!("String ({}): {}", string.len(), string);
1183 /// let my_string = "Hello World".to_string();
1184 /// print_if_string(Box::new(my_string));
1185 /// print_if_string(Box::new(0i8));
1187 pub fn downcast<T: Any>(self) -> Result<Box<T, A>, Self> {
1190 let (raw, alloc): (*mut (dyn Any + Send), _) = Box::into_raw_with_alloc(self);
1191 Ok(Box::from_raw_in(raw as *mut T, alloc))
1199 #[stable(feature = "rust1", since = "1.0.0")]
1200 impl<T: fmt::Display + ?Sized, A: AllocRef> fmt::Display for Box<T, A> {
1201 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1202 fmt::Display::fmt(&**self, f)
1206 #[stable(feature = "rust1", since = "1.0.0")]
1207 impl<T: fmt::Debug + ?Sized, A: AllocRef> fmt::Debug for Box<T, A> {
1208 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1209 fmt::Debug::fmt(&**self, f)
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 impl<T: ?Sized, A: AllocRef> fmt::Pointer for Box<T, A> {
1215 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1216 // It's not possible to extract the inner Uniq directly from the Box,
1217 // instead we cast it to a *const which aliases the Unique
1218 let ptr: *const T = &**self;
1219 fmt::Pointer::fmt(&ptr, f)
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 impl<T: ?Sized, A: AllocRef> Deref for Box<T, A> {
1227 fn deref(&self) -> &T {
1232 #[stable(feature = "rust1", since = "1.0.0")]
1233 impl<T: ?Sized, A: AllocRef> DerefMut for Box<T, A> {
1234 fn deref_mut(&mut self) -> &mut T {
1239 #[unstable(feature = "receiver_trait", issue = "none")]
1240 impl<T: ?Sized, A: AllocRef> Receiver for Box<T, A> {}
1242 #[stable(feature = "rust1", since = "1.0.0")]
1243 impl<I: Iterator + ?Sized, A: AllocRef> Iterator for Box<I, A> {
1244 type Item = I::Item;
1245 fn next(&mut self) -> Option<I::Item> {
1248 fn size_hint(&self) -> (usize, Option<usize>) {
1249 (**self).size_hint()
1251 fn nth(&mut self, n: usize) -> Option<I::Item> {
1254 fn last(self) -> Option<I::Item> {
1261 fn last(self) -> Option<Self::Item>;
1264 impl<I: Iterator + ?Sized, A: AllocRef> BoxIter for Box<I, A> {
1265 type Item = I::Item;
1266 default fn last(self) -> Option<I::Item> {
1268 fn some<T>(_: Option<T>, x: T) -> Option<T> {
1272 self.fold(None, some)
1276 /// Specialization for sized `I`s that uses `I`s implementation of `last()`
1277 /// instead of the default.
1278 #[stable(feature = "rust1", since = "1.0.0")]
1279 impl<I: Iterator, A: AllocRef> BoxIter for Box<I, A> {
1280 fn last(self) -> Option<I::Item> {
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl<I: DoubleEndedIterator + ?Sized, A: AllocRef> DoubleEndedIterator for Box<I, A> {
1287 fn next_back(&mut self) -> Option<I::Item> {
1288 (**self).next_back()
1290 fn nth_back(&mut self, n: usize) -> Option<I::Item> {
1291 (**self).nth_back(n)
1294 #[stable(feature = "rust1", since = "1.0.0")]
1295 impl<I: ExactSizeIterator + ?Sized, A: AllocRef> ExactSizeIterator for Box<I, A> {
1296 fn len(&self) -> usize {
1299 fn is_empty(&self) -> bool {
1304 #[stable(feature = "fused", since = "1.26.0")]
1305 impl<I: FusedIterator + ?Sized, A: AllocRef> FusedIterator for Box<I, A> {}
1307 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1308 impl<Args, F: FnOnce<Args> + ?Sized, A: AllocRef> FnOnce<Args> for Box<F, A> {
1309 type Output = <F as FnOnce<Args>>::Output;
1311 extern "rust-call" fn call_once(self, args: Args) -> Self::Output {
1312 <F as FnOnce<Args>>::call_once(*self, args)
1316 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1317 impl<Args, F: FnMut<Args> + ?Sized, A: AllocRef> FnMut<Args> for Box<F, A> {
1318 extern "rust-call" fn call_mut(&mut self, args: Args) -> Self::Output {
1319 <F as FnMut<Args>>::call_mut(self, args)
1323 #[stable(feature = "boxed_closure_impls", since = "1.35.0")]
1324 impl<Args, F: Fn<Args> + ?Sized, A: AllocRef> Fn<Args> for Box<F, A> {
1325 extern "rust-call" fn call(&self, args: Args) -> Self::Output {
1326 <F as Fn<Args>>::call(self, args)
1330 #[unstable(feature = "coerce_unsized", issue = "27732")]
1331 impl<T: ?Sized + Unsize<U>, U: ?Sized, A: AllocRef> CoerceUnsized<Box<U, A>> for Box<T, A> {}
1333 #[unstable(feature = "dispatch_from_dyn", issue = "none")]
1334 impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global> {}
1336 #[stable(feature = "boxed_slice_from_iter", since = "1.32.0")]
1337 impl<I> FromIterator<I> for Box<[I]> {
1338 fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
1339 iter.into_iter().collect::<Vec<_>>().into_boxed_slice()
1343 #[stable(feature = "box_slice_clone", since = "1.3.0")]
1344 impl<T: Clone> Clone for Box<[T]> {
1345 fn clone(&self) -> Self {
1346 self.to_vec().into_boxed_slice()
1349 fn clone_from(&mut self, other: &Self) {
1350 if self.len() == other.len() {
1351 self.clone_from_slice(&other);
1353 *self = other.clone();
1358 #[stable(feature = "box_borrow", since = "1.1.0")]
1359 impl<T: ?Sized, A: AllocRef> borrow::Borrow<T> for Box<T, A> {
1360 fn borrow(&self) -> &T {
1365 #[stable(feature = "box_borrow", since = "1.1.0")]
1366 impl<T: ?Sized, A: AllocRef> borrow::BorrowMut<T> for Box<T, A> {
1367 fn borrow_mut(&mut self) -> &mut T {
1372 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1373 impl<T: ?Sized, A: AllocRef> AsRef<T> for Box<T, A> {
1374 fn as_ref(&self) -> &T {
1379 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
1380 impl<T: ?Sized, A: AllocRef> AsMut<T> for Box<T, A> {
1381 fn as_mut(&mut self) -> &mut T {
1388 * We could have chosen not to add this impl, and instead have written a
1389 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
1390 * because Box<T> implements Unpin even when T does not, as a result of
1393 * We chose this API instead of the alternative for a few reasons:
1394 * - Logically, it is helpful to understand pinning in regard to the
1395 * memory region being pointed to. For this reason none of the
1396 * standard library pointer types support projecting through a pin
1397 * (Box<T> is the only pointer type in std for which this would be
1399 * - It is in practice very useful to have Box<T> be unconditionally
1400 * Unpin because of trait objects, for which the structural auto
1401 * trait functionality does not apply (e.g., Box<dyn Foo> would
1402 * otherwise not be Unpin).
1404 * Another type with the same semantics as Box but only a conditional
1405 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
1406 * could have a method to project a Pin<T> from it.
1408 #[stable(feature = "pin", since = "1.33.0")]
1409 impl<T: ?Sized, A: AllocRef> Unpin for Box<T, A> {}
1411 #[unstable(feature = "generator_trait", issue = "43122")]
1412 impl<G: ?Sized + Generator<R> + Unpin, R, A: AllocRef> Generator<R> for Box<G, A> {
1413 type Yield = G::Yield;
1414 type Return = G::Return;
1416 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1417 G::resume(Pin::new(&mut *self), arg)
1421 #[unstable(feature = "generator_trait", issue = "43122")]
1422 impl<G: ?Sized + Generator<R>, R, A: AllocRef> Generator<R> for Pin<Box<G, A>> {
1423 type Yield = G::Yield;
1424 type Return = G::Return;
1426 fn resume(mut self: Pin<&mut Self>, arg: R) -> GeneratorState<Self::Yield, Self::Return> {
1427 G::resume((*self).as_mut(), arg)
1431 #[stable(feature = "futures_api", since = "1.36.0")]
1432 impl<F: ?Sized + Future + Unpin, A: AllocRef> Future for Box<F, A> {
1433 type Output = F::Output;
1435 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1436 F::poll(Pin::new(&mut *self), cx)