1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A pointer type for heap allocation.
13 //! `Box<T>`, casually referred to as a 'box', provides the simplest form of
14 //! heap allocation in Rust. Boxes provide ownership for this allocation, and
15 //! drop their contents when they go out of scope.
22 //! let x = Box::new(5);
25 //! Creating a recursive data structure:
30 //! Cons(T, Box<List<T>>),
35 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
36 //! println!("{:?}", list);
40 //! This will print `Cons(1, Cons(2, Nil))`.
42 //! Recursive structures must be boxed, because if the definition of `Cons`
45 //! ```compile_fail,E0072
51 //! It wouldn't work. This is because the size of a `List` depends on how many
52 //! elements are in the list, and so we don't know how much memory to allocate
53 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
54 //! big `Cons` needs to be.
56 #![stable(feature = "rust1", since = "1.0.0")]
60 use core::cmp::Ordering;
61 use core::convert::From;
63 use core::future::Future;
64 use core::hash::{Hash, Hasher};
65 use core::iter::FusedIterator;
66 use core::marker::{Unpin, Unsize};
69 use core::ops::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState};
70 use core::ptr::{self, NonNull, Unique};
71 use core::task::{LocalWaker, Poll};
74 use str::from_boxed_utf8_unchecked;
76 /// A pointer type for heap allocation.
78 /// See the [module-level documentation](../../std/boxed/index.html) for more.
81 #[stable(feature = "rust1", since = "1.0.0")]
82 pub struct Box<T: ?Sized>(Unique<T>);
85 /// Allocates memory on the heap and then places `x` into it.
87 /// This doesn't actually allocate if `T` is zero-sized.
92 /// let five = Box::new(5);
94 #[stable(feature = "rust1", since = "1.0.0")]
96 pub fn new(x: T) -> Box<T> {
100 #[unstable(feature = "pin", issue = "49150")]
102 pub fn pinned(x: T) -> Pin<Box<T>> {
107 impl<T: ?Sized> Box<T> {
108 /// Constructs a box from a raw pointer.
110 /// After calling this function, the raw pointer is owned by the
111 /// resulting `Box`. Specifically, the `Box` destructor will call
112 /// the destructor of `T` and free the allocated memory. Since the
113 /// way `Box` allocates and releases memory is unspecified, the
114 /// only valid pointer to pass to this function is the one taken
115 /// from another `Box` via the [`Box::into_raw`] function.
117 /// This function is unsafe because improper use may lead to
118 /// memory problems. For example, a double-free may occur if the
119 /// function is called twice on the same raw pointer.
121 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
126 /// let x = Box::new(5);
127 /// let ptr = Box::into_raw(x);
128 /// let x = unsafe { Box::from_raw(ptr) };
130 #[stable(feature = "box_raw", since = "1.4.0")]
132 pub unsafe fn from_raw(raw: *mut T) -> Self {
133 Box(Unique::new_unchecked(raw))
136 /// Consumes the `Box`, returning a wrapped raw pointer.
138 /// The pointer will be properly aligned and non-null.
140 /// After calling this function, the caller is responsible for the
141 /// memory previously managed by the `Box`. In particular, the
142 /// caller should properly destroy `T` and release the memory. The
143 /// proper way to do so is to convert the raw pointer back into a
144 /// `Box` with the [`Box::from_raw`] function.
146 /// Note: this is an associated function, which means that you have
147 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
148 /// is so that there is no conflict with a method on the inner type.
150 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
155 /// let x = Box::new(5);
156 /// let ptr = Box::into_raw(x);
158 #[stable(feature = "box_raw", since = "1.4.0")]
160 pub fn into_raw(b: Box<T>) -> *mut T {
161 Box::into_raw_non_null(b).as_ptr()
164 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
166 /// After calling this function, the caller is responsible for the
167 /// memory previously managed by the `Box`. In particular, the
168 /// caller should properly destroy `T` and release the memory. The
169 /// proper way to do so is to convert the `NonNull<T>` pointer
170 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
173 /// Note: this is an associated function, which means that you have
174 /// to call it as `Box::into_raw_non_null(b)`
175 /// instead of `b.into_raw_non_null()`. This
176 /// is so that there is no conflict with a method on the inner type.
178 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
183 /// #![feature(box_into_raw_non_null)]
186 /// let x = Box::new(5);
187 /// let ptr = Box::into_raw_non_null(x);
190 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
192 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
193 Box::into_unique(b).into()
196 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
199 pub fn into_unique(b: Box<T>) -> Unique<T> {
205 /// Consumes and leaks the `Box`, returning a mutable reference,
206 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
207 /// `'a`. If the type has only static references, or none at all, then this
208 /// may be chosen to be `'static`.
210 /// This function is mainly useful for data that lives for the remainder of
211 /// the program's life. Dropping the returned reference will cause a memory
212 /// leak. If this is not acceptable, the reference should first be wrapped
213 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
214 /// then be dropped which will properly destroy `T` and release the
215 /// allocated memory.
217 /// Note: this is an associated function, which means that you have
218 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
219 /// is so that there is no conflict with a method on the inner type.
221 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
229 /// let x = Box::new(41);
230 /// let static_ref: &'static mut usize = Box::leak(x);
231 /// *static_ref += 1;
232 /// assert_eq!(*static_ref, 42);
240 /// let x = vec![1, 2, 3].into_boxed_slice();
241 /// let static_ref = Box::leak(x);
242 /// static_ref[0] = 4;
243 /// assert_eq!(*static_ref, [4, 2, 3]);
246 #[stable(feature = "box_leak", since = "1.26.0")]
248 pub fn leak<'a>(b: Box<T>) -> &'a mut T
250 T: 'a // Technically not needed, but kept to be explicit.
252 unsafe { &mut *Box::into_raw(b) }
256 #[stable(feature = "rust1", since = "1.0.0")]
257 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
259 // FIXME: Do nothing, drop is currently performed by compiler.
263 #[stable(feature = "rust1", since = "1.0.0")]
264 impl<T: Default> Default for Box<T> {
265 /// Creates a `Box<T>`, with the `Default` value for T.
266 fn default() -> Box<T> {
267 box Default::default()
271 #[stable(feature = "rust1", since = "1.0.0")]
272 impl<T> Default for Box<[T]> {
273 fn default() -> Box<[T]> {
274 Box::<[T; 0]>::new([])
278 #[stable(feature = "default_box_extra", since = "1.17.0")]
279 impl Default for Box<str> {
280 fn default() -> Box<str> {
281 unsafe { from_boxed_utf8_unchecked(Default::default()) }
285 #[stable(feature = "rust1", since = "1.0.0")]
286 impl<T: Clone> Clone for Box<T> {
287 /// Returns a new box with a `clone()` of this box's contents.
292 /// let x = Box::new(5);
293 /// let y = x.clone();
297 fn clone(&self) -> Box<T> {
298 box { (**self).clone() }
300 /// Copies `source`'s contents into `self` without creating a new allocation.
305 /// let x = Box::new(5);
306 /// let mut y = Box::new(10);
308 /// y.clone_from(&x);
310 /// assert_eq!(*y, 5);
313 fn clone_from(&mut self, source: &Box<T>) {
314 (**self).clone_from(&(**source));
319 #[stable(feature = "box_slice_clone", since = "1.3.0")]
320 impl Clone for Box<str> {
321 fn clone(&self) -> Self {
322 let len = self.len();
323 let buf = RawVec::with_capacity(len);
325 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
326 from_boxed_utf8_unchecked(buf.into_box())
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
334 fn eq(&self, other: &Box<T>) -> bool {
335 PartialEq::eq(&**self, &**other)
338 fn ne(&self, other: &Box<T>) -> bool {
339 PartialEq::ne(&**self, &**other)
342 #[stable(feature = "rust1", since = "1.0.0")]
343 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
345 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
346 PartialOrd::partial_cmp(&**self, &**other)
349 fn lt(&self, other: &Box<T>) -> bool {
350 PartialOrd::lt(&**self, &**other)
353 fn le(&self, other: &Box<T>) -> bool {
354 PartialOrd::le(&**self, &**other)
357 fn ge(&self, other: &Box<T>) -> bool {
358 PartialOrd::ge(&**self, &**other)
361 fn gt(&self, other: &Box<T>) -> bool {
362 PartialOrd::gt(&**self, &**other)
365 #[stable(feature = "rust1", since = "1.0.0")]
366 impl<T: ?Sized + Ord> Ord for Box<T> {
368 fn cmp(&self, other: &Box<T>) -> Ordering {
369 Ord::cmp(&**self, &**other)
372 #[stable(feature = "rust1", since = "1.0.0")]
373 impl<T: ?Sized + Eq> Eq for Box<T> {}
375 #[stable(feature = "rust1", since = "1.0.0")]
376 impl<T: ?Sized + Hash> Hash for Box<T> {
377 fn hash<H: Hasher>(&self, state: &mut H) {
378 (**self).hash(state);
382 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
383 impl<T: ?Sized + Hasher> Hasher for Box<T> {
384 fn finish(&self) -> u64 {
387 fn write(&mut self, bytes: &[u8]) {
388 (**self).write(bytes)
390 fn write_u8(&mut self, i: u8) {
393 fn write_u16(&mut self, i: u16) {
394 (**self).write_u16(i)
396 fn write_u32(&mut self, i: u32) {
397 (**self).write_u32(i)
399 fn write_u64(&mut self, i: u64) {
400 (**self).write_u64(i)
402 fn write_u128(&mut self, i: u128) {
403 (**self).write_u128(i)
405 fn write_usize(&mut self, i: usize) {
406 (**self).write_usize(i)
408 fn write_i8(&mut self, i: i8) {
411 fn write_i16(&mut self, i: i16) {
412 (**self).write_i16(i)
414 fn write_i32(&mut self, i: i32) {
415 (**self).write_i32(i)
417 fn write_i64(&mut self, i: i64) {
418 (**self).write_i64(i)
420 fn write_i128(&mut self, i: i128) {
421 (**self).write_i128(i)
423 fn write_isize(&mut self, i: isize) {
424 (**self).write_isize(i)
428 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
429 impl<T> From<T> for Box<T> {
430 fn from(t: T) -> Self {
435 #[unstable(feature = "pin", issue = "49150")]
436 impl<T> From<Box<T>> for Pin<Box<T>> {
437 fn from(boxed: Box<T>) -> Self {
438 // It's not possible to move or replace the insides of a `Pin<Box<T>>`
439 // when `T: !Unpin`, so it's safe to pin it directly without any
440 // additional requirements.
441 unsafe { Pin::new_unchecked(boxed) }
445 #[stable(feature = "box_from_slice", since = "1.17.0")]
446 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
447 fn from(slice: &'a [T]) -> Box<[T]> {
448 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
449 boxed.copy_from_slice(slice);
454 #[stable(feature = "box_from_slice", since = "1.17.0")]
455 impl<'a> From<&'a str> for Box<str> {
457 fn from(s: &'a str) -> Box<str> {
458 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
462 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
463 impl From<Box<str>> for Box<[u8]> {
465 fn from(s: Box<str>) -> Self {
466 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
472 #[stable(feature = "rust1", since = "1.0.0")]
473 /// Attempt to downcast the box to a concrete type.
478 /// use std::any::Any;
480 /// fn print_if_string(value: Box<Any>) {
481 /// if let Ok(string) = value.downcast::<String>() {
482 /// println!("String ({}): {}", string.len(), string);
487 /// let my_string = "Hello World".to_string();
488 /// print_if_string(Box::new(my_string));
489 /// print_if_string(Box::new(0i8));
492 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
495 let raw: *mut dyn Any = Box::into_raw(self);
496 Ok(Box::from_raw(raw as *mut T))
504 impl Box<dyn Any + Send> {
506 #[stable(feature = "rust1", since = "1.0.0")]
507 /// Attempt to downcast the box to a concrete type.
512 /// use std::any::Any;
514 /// fn print_if_string(value: Box<Any + Send>) {
515 /// if let Ok(string) = value.downcast::<String>() {
516 /// println!("String ({}): {}", string.len(), string);
521 /// let my_string = "Hello World".to_string();
522 /// print_if_string(Box::new(my_string));
523 /// print_if_string(Box::new(0i8));
526 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
527 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
528 // reapply the Send marker
529 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
534 #[stable(feature = "rust1", since = "1.0.0")]
535 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
537 fmt::Display::fmt(&**self, f)
541 #[stable(feature = "rust1", since = "1.0.0")]
542 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
543 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
544 fmt::Debug::fmt(&**self, f)
548 #[stable(feature = "rust1", since = "1.0.0")]
549 impl<T: ?Sized> fmt::Pointer for Box<T> {
550 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
551 // It's not possible to extract the inner Uniq directly from the Box,
552 // instead we cast it to a *const which aliases the Unique
553 let ptr: *const T = &**self;
554 fmt::Pointer::fmt(&ptr, f)
558 #[stable(feature = "rust1", since = "1.0.0")]
559 impl<T: ?Sized> Deref for Box<T> {
562 fn deref(&self) -> &T {
567 #[stable(feature = "rust1", since = "1.0.0")]
568 impl<T: ?Sized> DerefMut for Box<T> {
569 fn deref_mut(&mut self) -> &mut T {
574 #[stable(feature = "rust1", since = "1.0.0")]
575 impl<I: Iterator + ?Sized> Iterator for Box<I> {
577 fn next(&mut self) -> Option<I::Item> {
580 fn size_hint(&self) -> (usize, Option<usize>) {
583 fn nth(&mut self, n: usize) -> Option<I::Item> {
587 #[stable(feature = "rust1", since = "1.0.0")]
588 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
589 fn next_back(&mut self) -> Option<I::Item> {
593 #[stable(feature = "rust1", since = "1.0.0")]
594 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
595 fn len(&self) -> usize {
598 fn is_empty(&self) -> bool {
603 #[stable(feature = "fused", since = "1.26.0")]
604 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
607 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
608 /// closure objects. The idea is that where one would normally store a
609 /// `Box<FnOnce()>` in a data structure, you should use
610 /// `Box<FnBox()>`. The two traits behave essentially the same, except
611 /// that a `FnBox` closure can only be called if it is boxed. (Note
612 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
613 /// closures become directly usable.)
617 /// Here is a snippet of code which creates a hashmap full of boxed
618 /// once closures and then removes them one by one, calling each
619 /// closure as it is removed. Note that the type of the closures
620 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
624 /// #![feature(fnbox)]
626 /// use std::boxed::FnBox;
627 /// use std::collections::HashMap;
629 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
630 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
631 /// map.insert(1, Box::new(|| 22));
632 /// map.insert(2, Box::new(|| 44));
637 /// let mut map = make_map();
638 /// for i in &[1, 2] {
639 /// let f = map.remove(&i).unwrap();
640 /// assert_eq!(f(), i * 22);
645 #[unstable(feature = "fnbox",
646 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
650 fn call_box(self: Box<Self>, args: A) -> Self::Output;
653 #[unstable(feature = "fnbox",
654 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
655 impl<A, F> FnBox<A> for F
658 type Output = F::Output;
660 fn call_box(self: Box<F>, args: A) -> F::Output {
665 #[unstable(feature = "fnbox",
666 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
667 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> {
670 extern "rust-call" fn call_once(self, args: A) -> R {
675 #[unstable(feature = "fnbox",
676 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
677 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> {
680 extern "rust-call" fn call_once(self, args: A) -> R {
685 #[unstable(feature = "coerce_unsized", issue = "27732")]
686 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
688 #[stable(feature = "box_slice_clone", since = "1.3.0")]
689 impl<T: Clone> Clone for Box<[T]> {
690 fn clone(&self) -> Self {
691 let mut new = BoxBuilder {
692 data: RawVec::with_capacity(self.len()),
696 let mut target = new.data.ptr();
698 for item in self.iter() {
700 ptr::write(target, item.clone());
701 target = target.offset(1);
707 return unsafe { new.into_box() };
709 // Helper type for responding to panics correctly.
710 struct BoxBuilder<T> {
715 impl<T> BoxBuilder<T> {
716 unsafe fn into_box(self) -> Box<[T]> {
717 let raw = ptr::read(&self.data);
723 impl<T> Drop for BoxBuilder<T> {
725 let mut data = self.data.ptr();
726 let max = unsafe { data.add(self.len) };
731 data = data.offset(1);
739 #[stable(feature = "box_borrow", since = "1.1.0")]
740 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
741 fn borrow(&self) -> &T {
746 #[stable(feature = "box_borrow", since = "1.1.0")]
747 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
748 fn borrow_mut(&mut self) -> &mut T {
753 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
754 impl<T: ?Sized> AsRef<T> for Box<T> {
755 fn as_ref(&self) -> &T {
760 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
761 impl<T: ?Sized> AsMut<T> for Box<T> {
762 fn as_mut(&mut self) -> &mut T {
769 * We could have chosen not to add this impl, and instead have written a
770 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
771 * because Box<T> implements Unpin even when T does not, as a result of
774 * We chose this API instead of the alternative for a few reasons:
775 * - Logically, it is helpful to understand pinning in regard to the
776 * memory region being pointed to. For this reason none of the
777 * standard library pointer types support projecting through a pin
778 * (Box<T> is the only pointer type in std for which this would be
780 * - It is in practice very useful to have Box<T> be unconditionally
781 * Unpin because of trait objects, for which the structural auto
782 * trait functionality does not apply (e.g. Box<dyn Foo> would
783 * otherwise not be Unpin).
785 * Another type with the same semantics as Box but only a conditional
786 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
787 * could have a method to project a Pin<T> from it.
789 #[unstable(feature = "pin", issue = "49150")]
790 impl<T: ?Sized> Unpin for Box<T> { }
792 #[unstable(feature = "generator_trait", issue = "43122")]
793 impl<T> Generator for Box<T>
794 where T: Generator + ?Sized
796 type Yield = T::Yield;
797 type Return = T::Return;
798 unsafe fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> {
803 #[unstable(feature = "futures_api", issue = "50547")]
804 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
805 type Output = F::Output;
807 fn poll(mut self: Pin<&mut Self>, lw: &LocalWaker) -> Poll<Self::Output> {
808 F::poll(Pin::new(&mut *self), lw)