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, FutureObj, LocalFutureObj, UnsafeFutureObj};
64 use core::hash::{Hash, Hasher};
65 use core::iter::FusedIterator;
66 use core::marker::{Unpin, Unsize};
68 use core::pin::PinMut;
69 use core::ops::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState};
70 use core::ptr::{self, NonNull, Unique};
71 use core::task::{Context, Poll, Spawn, SpawnErrorKind, SpawnObjError};
75 use str::from_boxed_utf8_unchecked;
77 /// A pointer type for heap allocation.
79 /// See the [module-level documentation](../../std/boxed/index.html) for more.
82 #[stable(feature = "rust1", since = "1.0.0")]
83 pub struct Box<T: ?Sized>(Unique<T>);
86 /// Allocates memory on the heap and then places `x` into it.
88 /// This doesn't actually allocate if `T` is zero-sized.
93 /// let five = Box::new(5);
95 #[stable(feature = "rust1", since = "1.0.0")]
97 pub fn new(x: T) -> Box<T> {
102 impl<T: ?Sized> Box<T> {
103 /// Constructs a box from a raw pointer.
105 /// After calling this function, the raw pointer is owned by the
106 /// resulting `Box`. Specifically, the `Box` destructor will call
107 /// the destructor of `T` and free the allocated memory. Since the
108 /// way `Box` allocates and releases memory is unspecified, the
109 /// only valid pointer to pass to this function is the one taken
110 /// from another `Box` via the [`Box::into_raw`] function.
112 /// This function is unsafe because improper use may lead to
113 /// memory problems. For example, a double-free may occur if the
114 /// function is called twice on the same raw pointer.
116 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
121 /// let x = Box::new(5);
122 /// let ptr = Box::into_raw(x);
123 /// let x = unsafe { Box::from_raw(ptr) };
125 #[stable(feature = "box_raw", since = "1.4.0")]
127 pub unsafe fn from_raw(raw: *mut T) -> Self {
128 Box(Unique::new_unchecked(raw))
131 /// Consumes the `Box`, returning a wrapped raw pointer.
133 /// The pointer will be properly aligned and non-null.
135 /// After calling this function, the caller is responsible for the
136 /// memory previously managed by the `Box`. In particular, the
137 /// caller should properly destroy `T` and release the memory. The
138 /// proper way to do so is to convert the raw pointer back into a
139 /// `Box` with the [`Box::from_raw`] function.
141 /// Note: this is an associated function, which means that you have
142 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
143 /// is so that there is no conflict with a method on the inner type.
145 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
150 /// let x = Box::new(5);
151 /// let ptr = Box::into_raw(x);
153 #[stable(feature = "box_raw", since = "1.4.0")]
155 pub fn into_raw(b: Box<T>) -> *mut T {
156 Box::into_raw_non_null(b).as_ptr()
159 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
161 /// After calling this function, the caller is responsible for the
162 /// memory previously managed by the `Box`. In particular, the
163 /// caller should properly destroy `T` and release the memory. The
164 /// proper way to do so is to convert the `NonNull<T>` pointer
165 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
168 /// Note: this is an associated function, which means that you have
169 /// to call it as `Box::into_raw_non_null(b)`
170 /// instead of `b.into_raw_non_null()`. This
171 /// is so that there is no conflict with a method on the inner type.
173 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
178 /// #![feature(box_into_raw_non_null)]
181 /// let x = Box::new(5);
182 /// let ptr = Box::into_raw_non_null(x);
185 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
187 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
188 Box::into_unique(b).into()
191 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
194 pub fn into_unique(b: Box<T>) -> Unique<T> {
200 /// Consumes and leaks the `Box`, returning a mutable reference,
201 /// `&'a mut T`. Note that the type `T` must outlive the chosen lifetime
202 /// `'a`. If the type has only static references, or none at all, then this
203 /// may be chosen to be `'static`.
205 /// This function is mainly useful for data that lives for the remainder of
206 /// the program's life. Dropping the returned reference will cause a memory
207 /// leak. If this is not acceptable, the reference should first be wrapped
208 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
209 /// then be dropped which will properly destroy `T` and release the
210 /// allocated memory.
212 /// Note: this is an associated function, which means that you have
213 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
214 /// is so that there is no conflict with a method on the inner type.
216 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
224 /// let x = Box::new(41);
225 /// let static_ref: &'static mut usize = Box::leak(x);
226 /// *static_ref += 1;
227 /// assert_eq!(*static_ref, 42);
235 /// let x = vec![1, 2, 3].into_boxed_slice();
236 /// let static_ref = Box::leak(x);
237 /// static_ref[0] = 4;
238 /// assert_eq!(*static_ref, [4, 2, 3]);
241 #[stable(feature = "box_leak", since = "1.26.0")]
243 pub fn leak<'a>(b: Box<T>) -> &'a mut T
245 T: 'a // Technically not needed, but kept to be explicit.
247 unsafe { &mut *Box::into_raw(b) }
251 #[stable(feature = "rust1", since = "1.0.0")]
252 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
254 // FIXME: Do nothing, drop is currently performed by compiler.
258 #[stable(feature = "rust1", since = "1.0.0")]
259 impl<T: Default> Default for Box<T> {
260 /// Creates a `Box<T>`, with the `Default` value for T.
261 fn default() -> Box<T> {
262 box Default::default()
266 #[stable(feature = "rust1", since = "1.0.0")]
267 impl<T> Default for Box<[T]> {
268 fn default() -> Box<[T]> {
269 Box::<[T; 0]>::new([])
273 #[stable(feature = "default_box_extra", since = "1.17.0")]
274 impl Default for Box<str> {
275 fn default() -> Box<str> {
276 unsafe { from_boxed_utf8_unchecked(Default::default()) }
280 #[stable(feature = "rust1", since = "1.0.0")]
281 impl<T: Clone> Clone for Box<T> {
282 /// Returns a new box with a `clone()` of this box's contents.
287 /// let x = Box::new(5);
288 /// let y = x.clone();
292 fn clone(&self) -> Box<T> {
293 box { (**self).clone() }
295 /// Copies `source`'s contents into `self` without creating a new allocation.
300 /// let x = Box::new(5);
301 /// let mut y = Box::new(10);
303 /// y.clone_from(&x);
305 /// assert_eq!(*y, 5);
308 fn clone_from(&mut self, source: &Box<T>) {
309 (**self).clone_from(&(**source));
314 #[stable(feature = "box_slice_clone", since = "1.3.0")]
315 impl Clone for Box<str> {
316 fn clone(&self) -> Self {
317 let len = self.len();
318 let buf = RawVec::with_capacity(len);
320 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
321 from_boxed_utf8_unchecked(buf.into_box())
326 #[stable(feature = "rust1", since = "1.0.0")]
327 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
329 fn eq(&self, other: &Box<T>) -> bool {
330 PartialEq::eq(&**self, &**other)
333 fn ne(&self, other: &Box<T>) -> bool {
334 PartialEq::ne(&**self, &**other)
337 #[stable(feature = "rust1", since = "1.0.0")]
338 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
340 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
341 PartialOrd::partial_cmp(&**self, &**other)
344 fn lt(&self, other: &Box<T>) -> bool {
345 PartialOrd::lt(&**self, &**other)
348 fn le(&self, other: &Box<T>) -> bool {
349 PartialOrd::le(&**self, &**other)
352 fn ge(&self, other: &Box<T>) -> bool {
353 PartialOrd::ge(&**self, &**other)
356 fn gt(&self, other: &Box<T>) -> bool {
357 PartialOrd::gt(&**self, &**other)
360 #[stable(feature = "rust1", since = "1.0.0")]
361 impl<T: ?Sized + Ord> Ord for Box<T> {
363 fn cmp(&self, other: &Box<T>) -> Ordering {
364 Ord::cmp(&**self, &**other)
367 #[stable(feature = "rust1", since = "1.0.0")]
368 impl<T: ?Sized + Eq> Eq for Box<T> {}
370 #[stable(feature = "rust1", since = "1.0.0")]
371 impl<T: ?Sized + Hash> Hash for Box<T> {
372 fn hash<H: Hasher>(&self, state: &mut H) {
373 (**self).hash(state);
377 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
378 impl<T: ?Sized + Hasher> Hasher for Box<T> {
379 fn finish(&self) -> u64 {
382 fn write(&mut self, bytes: &[u8]) {
383 (**self).write(bytes)
385 fn write_u8(&mut self, i: u8) {
388 fn write_u16(&mut self, i: u16) {
389 (**self).write_u16(i)
391 fn write_u32(&mut self, i: u32) {
392 (**self).write_u32(i)
394 fn write_u64(&mut self, i: u64) {
395 (**self).write_u64(i)
397 fn write_u128(&mut self, i: u128) {
398 (**self).write_u128(i)
400 fn write_usize(&mut self, i: usize) {
401 (**self).write_usize(i)
403 fn write_i8(&mut self, i: i8) {
406 fn write_i16(&mut self, i: i16) {
407 (**self).write_i16(i)
409 fn write_i32(&mut self, i: i32) {
410 (**self).write_i32(i)
412 fn write_i64(&mut self, i: i64) {
413 (**self).write_i64(i)
415 fn write_i128(&mut self, i: i128) {
416 (**self).write_i128(i)
418 fn write_isize(&mut self, i: isize) {
419 (**self).write_isize(i)
423 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
424 impl<T> From<T> for Box<T> {
425 fn from(t: T) -> Self {
430 #[stable(feature = "box_from_slice", since = "1.17.0")]
431 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
432 fn from(slice: &'a [T]) -> Box<[T]> {
433 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
434 boxed.copy_from_slice(slice);
439 #[stable(feature = "box_from_slice", since = "1.17.0")]
440 impl<'a> From<&'a str> for Box<str> {
442 fn from(s: &'a str) -> Box<str> {
443 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
447 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
448 impl From<Box<str>> for Box<[u8]> {
450 fn from(s: Box<str>) -> Self {
451 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
457 #[stable(feature = "rust1", since = "1.0.0")]
458 /// Attempt to downcast the box to a concrete type.
463 /// use std::any::Any;
465 /// fn print_if_string(value: Box<Any>) {
466 /// if let Ok(string) = value.downcast::<String>() {
467 /// println!("String ({}): {}", string.len(), string);
472 /// let my_string = "Hello World".to_string();
473 /// print_if_string(Box::new(my_string));
474 /// print_if_string(Box::new(0i8));
477 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any>> {
480 let raw: *mut dyn Any = Box::into_raw(self);
481 Ok(Box::from_raw(raw as *mut T))
489 impl Box<dyn Any + Send> {
491 #[stable(feature = "rust1", since = "1.0.0")]
492 /// Attempt to downcast the box to a concrete type.
497 /// use std::any::Any;
499 /// fn print_if_string(value: Box<Any + Send>) {
500 /// if let Ok(string) = value.downcast::<String>() {
501 /// println!("String ({}): {}", string.len(), string);
506 /// let my_string = "Hello World".to_string();
507 /// print_if_string(Box::new(my_string));
508 /// print_if_string(Box::new(0i8));
511 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<dyn Any + Send>> {
512 <Box<dyn Any>>::downcast(self).map_err(|s| unsafe {
513 // reapply the Send marker
514 Box::from_raw(Box::into_raw(s) as *mut (dyn Any + Send))
519 #[stable(feature = "rust1", since = "1.0.0")]
520 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
521 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
522 fmt::Display::fmt(&**self, f)
526 #[stable(feature = "rust1", since = "1.0.0")]
527 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
529 fmt::Debug::fmt(&**self, f)
533 #[stable(feature = "rust1", since = "1.0.0")]
534 impl<T: ?Sized> fmt::Pointer for Box<T> {
535 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
536 // It's not possible to extract the inner Uniq directly from the Box,
537 // instead we cast it to a *const which aliases the Unique
538 let ptr: *const T = &**self;
539 fmt::Pointer::fmt(&ptr, f)
543 #[stable(feature = "rust1", since = "1.0.0")]
544 impl<T: ?Sized> Deref for Box<T> {
547 fn deref(&self) -> &T {
552 #[stable(feature = "rust1", since = "1.0.0")]
553 impl<T: ?Sized> DerefMut for Box<T> {
554 fn deref_mut(&mut self) -> &mut T {
559 #[stable(feature = "rust1", since = "1.0.0")]
560 impl<I: Iterator + ?Sized> Iterator for Box<I> {
562 fn next(&mut self) -> Option<I::Item> {
565 fn size_hint(&self) -> (usize, Option<usize>) {
568 fn nth(&mut self, n: usize) -> Option<I::Item> {
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
574 fn next_back(&mut self) -> Option<I::Item> {
578 #[stable(feature = "rust1", since = "1.0.0")]
579 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
580 fn len(&self) -> usize {
583 fn is_empty(&self) -> bool {
588 #[stable(feature = "fused", since = "1.26.0")]
589 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
592 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
593 /// closure objects. The idea is that where one would normally store a
594 /// `Box<FnOnce()>` in a data structure, you should use
595 /// `Box<FnBox()>`. The two traits behave essentially the same, except
596 /// that a `FnBox` closure can only be called if it is boxed. (Note
597 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
598 /// closures become directly usable.)
602 /// Here is a snippet of code which creates a hashmap full of boxed
603 /// once closures and then removes them one by one, calling each
604 /// closure as it is removed. Note that the type of the closures
605 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
609 /// #![feature(fnbox)]
611 /// use std::boxed::FnBox;
612 /// use std::collections::HashMap;
614 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
615 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
616 /// map.insert(1, Box::new(|| 22));
617 /// map.insert(2, Box::new(|| 44));
622 /// let mut map = make_map();
623 /// for i in &[1, 2] {
624 /// let f = map.remove(&i).unwrap();
625 /// assert_eq!(f(), i * 22);
630 #[unstable(feature = "fnbox",
631 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
635 fn call_box(self: Box<Self>, args: A) -> Self::Output;
638 #[unstable(feature = "fnbox",
639 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
640 impl<A, F> FnBox<A> for F
643 type Output = F::Output;
645 fn call_box(self: Box<F>, args: A) -> F::Output {
650 #[unstable(feature = "fnbox",
651 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
652 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + 'a> {
655 extern "rust-call" fn call_once(self, args: A) -> R {
660 #[unstable(feature = "fnbox",
661 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
662 impl<'a, A, R> FnOnce<A> for Box<dyn FnBox<A, Output = R> + Send + 'a> {
665 extern "rust-call" fn call_once(self, args: A) -> R {
670 #[unstable(feature = "coerce_unsized", issue = "27732")]
671 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
673 #[stable(feature = "box_slice_clone", since = "1.3.0")]
674 impl<T: Clone> Clone for Box<[T]> {
675 fn clone(&self) -> Self {
676 let mut new = BoxBuilder {
677 data: RawVec::with_capacity(self.len()),
681 let mut target = new.data.ptr();
683 for item in self.iter() {
685 ptr::write(target, item.clone());
686 target = target.offset(1);
692 return unsafe { new.into_box() };
694 // Helper type for responding to panics correctly.
695 struct BoxBuilder<T> {
700 impl<T> BoxBuilder<T> {
701 unsafe fn into_box(self) -> Box<[T]> {
702 let raw = ptr::read(&self.data);
708 impl<T> Drop for BoxBuilder<T> {
710 let mut data = self.data.ptr();
711 let max = unsafe { data.add(self.len) };
716 data = data.offset(1);
724 #[stable(feature = "box_borrow", since = "1.1.0")]
725 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
726 fn borrow(&self) -> &T {
731 #[stable(feature = "box_borrow", since = "1.1.0")]
732 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
733 fn borrow_mut(&mut self) -> &mut T {
738 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
739 impl<T: ?Sized> AsRef<T> for Box<T> {
740 fn as_ref(&self) -> &T {
745 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
746 impl<T: ?Sized> AsMut<T> for Box<T> {
747 fn as_mut(&mut self) -> &mut T {
754 * We could have chosen not to add this impl, and instead have written a
755 * function of Pin<Box<T>> to Pin<T>. Such a function would not be sound,
756 * because Box<T> implements Unpin even when T does not, as a result of
759 * We chose this API instead of the alternative for a few reasons:
760 * - Logically, it is helpful to understand pinning in regard to the
761 * memory region being pointed to. For this reason none of the
762 * standard library pointer types support projecting through a pin
763 * (Box<T> is the only pointer type in std for which this would be
765 * - It is in practice very useful to have Box<T> be unconditionally
766 * Unpin because of trait objects, for which the structural auto
767 * trait functionality does not apply (e.g. Box<dyn Foo> would
768 * otherwise not be Unpin).
770 * Another type with the same semantics as Box but only a conditional
771 * implementation of `Unpin` (where `T: Unpin`) would be valid/safe, and
772 * could have a method to project a Pin<T> from it.
774 #[unstable(feature = "pin", issue = "49150")]
775 impl<T: ?Sized> Unpin for Box<T> { }
777 #[unstable(feature = "generator_trait", issue = "43122")]
778 impl<T> Generator for Box<T>
779 where T: Generator + ?Sized
781 type Yield = T::Yield;
782 type Return = T::Return;
783 unsafe fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> {
788 #[unstable(feature = "futures_api", issue = "50547")]
789 impl<F: ?Sized + Future + Unpin> Future for Box<F> {
790 type Output = F::Output;
792 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
793 PinMut::new(&mut **self).poll(cx)
797 #[unstable(feature = "futures_api", issue = "50547")]
798 unsafe impl<'a, T, F> UnsafeFutureObj<'a, T> for Box<F>
799 where F: Future<Output = T> + 'a
801 fn into_raw(self) -> *mut () {
802 Box::into_raw(self) as *mut ()
805 unsafe fn poll(ptr: *mut (), cx: &mut Context) -> Poll<T> {
806 let ptr = ptr as *mut F;
807 let pin: PinMut<F> = PinMut::new_unchecked(&mut *ptr);
811 unsafe fn drop(ptr: *mut ()) {
812 drop(Box::from_raw(ptr as *mut F))
816 #[unstable(feature = "futures_api", issue = "50547")]
817 impl<Sp> Spawn for Box<Sp>
818 where Sp: Spawn + ?Sized
822 future: FutureObj<'static, ()>,
823 ) -> Result<(), SpawnObjError> {
824 (**self).spawn_obj(future)
827 fn status(&self) -> Result<(), SpawnErrorKind> {
832 #[unstable(feature = "futures_api", issue = "50547")]
833 impl<'a, F: Future<Output = ()> + Send + 'a> From<Box<F>> for FutureObj<'a, ()> {
834 fn from(boxed: Box<F>) -> Self {
835 FutureObj::new(boxed)
839 #[unstable(feature = "futures_api", issue = "50547")]
840 impl<'a, F: Future<Output = ()> + 'a> From<Box<F>> for LocalFutureObj<'a, ()> {
841 fn from(boxed: Box<F>) -> Self {
842 LocalFutureObj::new(boxed)
846 #[unstable(feature = "pin", issue = "49150")]
847 impl<T: Unpin + ?Sized> From<PinBox<T>> for Box<T> {
848 fn from(pinned: PinBox<T>) -> Box<T> {
849 unsafe { PinBox::unpin(pinned) }