]> git.proxmox.com Git - rustc.git/blob - src/liballoc/boxed.rs
New upstream version 1.28.0~beta.14+dfsg1
[rustc.git] / src / liballoc / boxed.rs
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.
4 //
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.
10
11 //! A pointer type for heap allocation.
12 //!
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.
16 //!
17 //! # Examples
18 //!
19 //! Creating a box:
20 //!
21 //! ```
22 //! let x = Box::new(5);
23 //! ```
24 //!
25 //! Creating a recursive data structure:
26 //!
27 //! ```
28 //! #[derive(Debug)]
29 //! enum List<T> {
30 //! Cons(T, Box<List<T>>),
31 //! Nil,
32 //! }
33 //!
34 //! fn main() {
35 //! let list: List<i32> = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
36 //! println!("{:?}", list);
37 //! }
38 //! ```
39 //!
40 //! This will print `Cons(1, Cons(2, Nil))`.
41 //!
42 //! Recursive structures must be boxed, because if the definition of `Cons`
43 //! looked like this:
44 //!
45 //! ```compile_fail,E0072
46 //! # enum List<T> {
47 //! Cons(T, List<T>),
48 //! # }
49 //! ```
50 //!
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.
55
56 #![stable(feature = "rust1", since = "1.0.0")]
57
58 use core::any::Any;
59 use core::borrow;
60 use core::cmp::Ordering;
61 use core::fmt;
62 use core::future::Future;
63 use core::hash::{Hash, Hasher};
64 use core::iter::FusedIterator;
65 use core::marker::{Unpin, Unsize};
66 use core::mem::{self, PinMut};
67 use core::ops::{CoerceUnsized, Deref, DerefMut, Generator, GeneratorState};
68 use core::ptr::{self, NonNull, Unique};
69 use core::task::{Context, Poll, UnsafeTask, TaskObj};
70 use core::convert::From;
71
72 use raw_vec::RawVec;
73 use str::from_boxed_utf8_unchecked;
74
75 /// A pointer type for heap allocation.
76 ///
77 /// See the [module-level documentation](../../std/boxed/index.html) for more.
78 #[lang = "owned_box"]
79 #[fundamental]
80 #[stable(feature = "rust1", since = "1.0.0")]
81 pub struct Box<T: ?Sized>(Unique<T>);
82
83 impl<T> Box<T> {
84 /// Allocates memory on the heap and then places `x` into it.
85 ///
86 /// This doesn't actually allocate if `T` is zero-sized.
87 ///
88 /// # Examples
89 ///
90 /// ```
91 /// let five = Box::new(5);
92 /// ```
93 #[stable(feature = "rust1", since = "1.0.0")]
94 #[inline(always)]
95 pub fn new(x: T) -> Box<T> {
96 box x
97 }
98 }
99
100 impl<T: ?Sized> Box<T> {
101 /// Constructs a box from a raw pointer.
102 ///
103 /// After calling this function, the raw pointer is owned by the
104 /// resulting `Box`. Specifically, the `Box` destructor will call
105 /// the destructor of `T` and free the allocated memory. Since the
106 /// way `Box` allocates and releases memory is unspecified, the
107 /// only valid pointer to pass to this function is the one taken
108 /// from another `Box` via the [`Box::into_raw`] function.
109 ///
110 /// This function is unsafe because improper use may lead to
111 /// memory problems. For example, a double-free may occur if the
112 /// function is called twice on the same raw pointer.
113 ///
114 /// [`Box::into_raw`]: struct.Box.html#method.into_raw
115 ///
116 /// # Examples
117 ///
118 /// ```
119 /// let x = Box::new(5);
120 /// let ptr = Box::into_raw(x);
121 /// let x = unsafe { Box::from_raw(ptr) };
122 /// ```
123 #[stable(feature = "box_raw", since = "1.4.0")]
124 #[inline]
125 pub unsafe fn from_raw(raw: *mut T) -> Self {
126 Box(Unique::new_unchecked(raw))
127 }
128
129 /// Consumes the `Box`, returning the wrapped raw pointer.
130 ///
131 /// After calling this function, the caller is responsible for the
132 /// memory previously managed by the `Box`. In particular, the
133 /// caller should properly destroy `T` and release the memory. The
134 /// proper way to do so is to convert the raw pointer back into a
135 /// `Box` with the [`Box::from_raw`] function.
136 ///
137 /// Note: this is an associated function, which means that you have
138 /// to call it as `Box::into_raw(b)` instead of `b.into_raw()`. This
139 /// is so that there is no conflict with a method on the inner type.
140 ///
141 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// let x = Box::new(5);
147 /// let ptr = Box::into_raw(x);
148 /// ```
149 #[stable(feature = "box_raw", since = "1.4.0")]
150 #[inline]
151 pub fn into_raw(b: Box<T>) -> *mut T {
152 Box::into_raw_non_null(b).as_ptr()
153 }
154
155 /// Consumes the `Box`, returning the wrapped pointer as `NonNull<T>`.
156 ///
157 /// After calling this function, the caller is responsible for the
158 /// memory previously managed by the `Box`. In particular, the
159 /// caller should properly destroy `T` and release the memory. The
160 /// proper way to do so is to convert the `NonNull<T>` pointer
161 /// into a raw pointer and back into a `Box` with the [`Box::from_raw`]
162 /// function.
163 ///
164 /// Note: this is an associated function, which means that you have
165 /// to call it as `Box::into_raw_non_null(b)`
166 /// instead of `b.into_raw_non_null()`. This
167 /// is so that there is no conflict with a method on the inner type.
168 ///
169 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
170 ///
171 /// # Examples
172 ///
173 /// ```
174 /// #![feature(box_into_raw_non_null)]
175 ///
176 /// fn main() {
177 /// let x = Box::new(5);
178 /// let ptr = Box::into_raw_non_null(x);
179 /// }
180 /// ```
181 #[unstable(feature = "box_into_raw_non_null", issue = "47336")]
182 #[inline]
183 pub fn into_raw_non_null(b: Box<T>) -> NonNull<T> {
184 Box::into_unique(b).into()
185 }
186
187 #[unstable(feature = "ptr_internals", issue = "0", reason = "use into_raw_non_null instead")]
188 #[inline]
189 #[doc(hidden)]
190 pub fn into_unique(b: Box<T>) -> Unique<T> {
191 let unique = b.0;
192 mem::forget(b);
193 unique
194 }
195
196 /// Consumes and leaks the `Box`, returning a mutable reference,
197 /// `&'a mut T`. Here, the lifetime `'a` may be chosen to be `'static`.
198 ///
199 /// This function is mainly useful for data that lives for the remainder of
200 /// the program's life. Dropping the returned reference will cause a memory
201 /// leak. If this is not acceptable, the reference should first be wrapped
202 /// with the [`Box::from_raw`] function producing a `Box`. This `Box` can
203 /// then be dropped which will properly destroy `T` and release the
204 /// allocated memory.
205 ///
206 /// Note: this is an associated function, which means that you have
207 /// to call it as `Box::leak(b)` instead of `b.leak()`. This
208 /// is so that there is no conflict with a method on the inner type.
209 ///
210 /// [`Box::from_raw`]: struct.Box.html#method.from_raw
211 ///
212 /// # Examples
213 ///
214 /// Simple usage:
215 ///
216 /// ```
217 /// fn main() {
218 /// let x = Box::new(41);
219 /// let static_ref: &'static mut usize = Box::leak(x);
220 /// *static_ref += 1;
221 /// assert_eq!(*static_ref, 42);
222 /// }
223 /// ```
224 ///
225 /// Unsized data:
226 ///
227 /// ```
228 /// fn main() {
229 /// let x = vec![1, 2, 3].into_boxed_slice();
230 /// let static_ref = Box::leak(x);
231 /// static_ref[0] = 4;
232 /// assert_eq!(*static_ref, [4, 2, 3]);
233 /// }
234 /// ```
235 #[stable(feature = "box_leak", since = "1.26.0")]
236 #[inline]
237 pub fn leak<'a>(b: Box<T>) -> &'a mut T
238 where
239 T: 'a // Technically not needed, but kept to be explicit.
240 {
241 unsafe { &mut *Box::into_raw(b) }
242 }
243 }
244
245 #[stable(feature = "rust1", since = "1.0.0")]
246 unsafe impl<#[may_dangle] T: ?Sized> Drop for Box<T> {
247 fn drop(&mut self) {
248 // FIXME: Do nothing, drop is currently performed by compiler.
249 }
250 }
251
252 #[stable(feature = "rust1", since = "1.0.0")]
253 impl<T: Default> Default for Box<T> {
254 /// Creates a `Box<T>`, with the `Default` value for T.
255 fn default() -> Box<T> {
256 box Default::default()
257 }
258 }
259
260 #[stable(feature = "rust1", since = "1.0.0")]
261 impl<T> Default for Box<[T]> {
262 fn default() -> Box<[T]> {
263 Box::<[T; 0]>::new([])
264 }
265 }
266
267 #[stable(feature = "default_box_extra", since = "1.17.0")]
268 impl Default for Box<str> {
269 fn default() -> Box<str> {
270 unsafe { from_boxed_utf8_unchecked(Default::default()) }
271 }
272 }
273
274 #[stable(feature = "rust1", since = "1.0.0")]
275 impl<T: Clone> Clone for Box<T> {
276 /// Returns a new box with a `clone()` of this box's contents.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// let x = Box::new(5);
282 /// let y = x.clone();
283 /// ```
284 #[rustfmt_skip]
285 #[inline]
286 fn clone(&self) -> Box<T> {
287 box { (**self).clone() }
288 }
289 /// Copies `source`'s contents into `self` without creating a new allocation.
290 ///
291 /// # Examples
292 ///
293 /// ```
294 /// let x = Box::new(5);
295 /// let mut y = Box::new(10);
296 ///
297 /// y.clone_from(&x);
298 ///
299 /// assert_eq!(*y, 5);
300 /// ```
301 #[inline]
302 fn clone_from(&mut self, source: &Box<T>) {
303 (**self).clone_from(&(**source));
304 }
305 }
306
307
308 #[stable(feature = "box_slice_clone", since = "1.3.0")]
309 impl Clone for Box<str> {
310 fn clone(&self) -> Self {
311 let len = self.len();
312 let buf = RawVec::with_capacity(len);
313 unsafe {
314 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
315 from_boxed_utf8_unchecked(buf.into_box())
316 }
317 }
318 }
319
320 #[stable(feature = "rust1", since = "1.0.0")]
321 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
322 #[inline]
323 fn eq(&self, other: &Box<T>) -> bool {
324 PartialEq::eq(&**self, &**other)
325 }
326 #[inline]
327 fn ne(&self, other: &Box<T>) -> bool {
328 PartialEq::ne(&**self, &**other)
329 }
330 }
331 #[stable(feature = "rust1", since = "1.0.0")]
332 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
333 #[inline]
334 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
335 PartialOrd::partial_cmp(&**self, &**other)
336 }
337 #[inline]
338 fn lt(&self, other: &Box<T>) -> bool {
339 PartialOrd::lt(&**self, &**other)
340 }
341 #[inline]
342 fn le(&self, other: &Box<T>) -> bool {
343 PartialOrd::le(&**self, &**other)
344 }
345 #[inline]
346 fn ge(&self, other: &Box<T>) -> bool {
347 PartialOrd::ge(&**self, &**other)
348 }
349 #[inline]
350 fn gt(&self, other: &Box<T>) -> bool {
351 PartialOrd::gt(&**self, &**other)
352 }
353 }
354 #[stable(feature = "rust1", since = "1.0.0")]
355 impl<T: ?Sized + Ord> Ord for Box<T> {
356 #[inline]
357 fn cmp(&self, other: &Box<T>) -> Ordering {
358 Ord::cmp(&**self, &**other)
359 }
360 }
361 #[stable(feature = "rust1", since = "1.0.0")]
362 impl<T: ?Sized + Eq> Eq for Box<T> {}
363
364 #[stable(feature = "rust1", since = "1.0.0")]
365 impl<T: ?Sized + Hash> Hash for Box<T> {
366 fn hash<H: Hasher>(&self, state: &mut H) {
367 (**self).hash(state);
368 }
369 }
370
371 #[stable(feature = "indirect_hasher_impl", since = "1.22.0")]
372 impl<T: ?Sized + Hasher> Hasher for Box<T> {
373 fn finish(&self) -> u64 {
374 (**self).finish()
375 }
376 fn write(&mut self, bytes: &[u8]) {
377 (**self).write(bytes)
378 }
379 fn write_u8(&mut self, i: u8) {
380 (**self).write_u8(i)
381 }
382 fn write_u16(&mut self, i: u16) {
383 (**self).write_u16(i)
384 }
385 fn write_u32(&mut self, i: u32) {
386 (**self).write_u32(i)
387 }
388 fn write_u64(&mut self, i: u64) {
389 (**self).write_u64(i)
390 }
391 fn write_u128(&mut self, i: u128) {
392 (**self).write_u128(i)
393 }
394 fn write_usize(&mut self, i: usize) {
395 (**self).write_usize(i)
396 }
397 fn write_i8(&mut self, i: i8) {
398 (**self).write_i8(i)
399 }
400 fn write_i16(&mut self, i: i16) {
401 (**self).write_i16(i)
402 }
403 fn write_i32(&mut self, i: i32) {
404 (**self).write_i32(i)
405 }
406 fn write_i64(&mut self, i: i64) {
407 (**self).write_i64(i)
408 }
409 fn write_i128(&mut self, i: i128) {
410 (**self).write_i128(i)
411 }
412 fn write_isize(&mut self, i: isize) {
413 (**self).write_isize(i)
414 }
415 }
416
417 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
418 impl<T> From<T> for Box<T> {
419 fn from(t: T) -> Self {
420 Box::new(t)
421 }
422 }
423
424 #[stable(feature = "box_from_slice", since = "1.17.0")]
425 impl<'a, T: Copy> From<&'a [T]> for Box<[T]> {
426 fn from(slice: &'a [T]) -> Box<[T]> {
427 let mut boxed = unsafe { RawVec::with_capacity(slice.len()).into_box() };
428 boxed.copy_from_slice(slice);
429 boxed
430 }
431 }
432
433 #[stable(feature = "box_from_slice", since = "1.17.0")]
434 impl<'a> From<&'a str> for Box<str> {
435 #[inline]
436 fn from(s: &'a str) -> Box<str> {
437 unsafe { from_boxed_utf8_unchecked(Box::from(s.as_bytes())) }
438 }
439 }
440
441 #[stable(feature = "boxed_str_conv", since = "1.19.0")]
442 impl From<Box<str>> for Box<[u8]> {
443 #[inline]
444 fn from(s: Box<str>) -> Self {
445 unsafe { Box::from_raw(Box::into_raw(s) as *mut [u8]) }
446 }
447 }
448
449 impl Box<Any> {
450 #[inline]
451 #[stable(feature = "rust1", since = "1.0.0")]
452 /// Attempt to downcast the box to a concrete type.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// use std::any::Any;
458 ///
459 /// fn print_if_string(value: Box<Any>) {
460 /// if let Ok(string) = value.downcast::<String>() {
461 /// println!("String ({}): {}", string.len(), string);
462 /// }
463 /// }
464 ///
465 /// fn main() {
466 /// let my_string = "Hello World".to_string();
467 /// print_if_string(Box::new(my_string));
468 /// print_if_string(Box::new(0i8));
469 /// }
470 /// ```
471 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
472 if self.is::<T>() {
473 unsafe {
474 let raw: *mut Any = Box::into_raw(self);
475 Ok(Box::from_raw(raw as *mut T))
476 }
477 } else {
478 Err(self)
479 }
480 }
481 }
482
483 impl Box<Any + Send> {
484 #[inline]
485 #[stable(feature = "rust1", since = "1.0.0")]
486 /// Attempt to downcast the box to a concrete type.
487 ///
488 /// # Examples
489 ///
490 /// ```
491 /// use std::any::Any;
492 ///
493 /// fn print_if_string(value: Box<Any + Send>) {
494 /// if let Ok(string) = value.downcast::<String>() {
495 /// println!("String ({}): {}", string.len(), string);
496 /// }
497 /// }
498 ///
499 /// fn main() {
500 /// let my_string = "Hello World".to_string();
501 /// print_if_string(Box::new(my_string));
502 /// print_if_string(Box::new(0i8));
503 /// }
504 /// ```
505 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
506 <Box<Any>>::downcast(self).map_err(|s| unsafe {
507 // reapply the Send marker
508 Box::from_raw(Box::into_raw(s) as *mut (Any + Send))
509 })
510 }
511 }
512
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
515 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
516 fmt::Display::fmt(&**self, f)
517 }
518 }
519
520 #[stable(feature = "rust1", since = "1.0.0")]
521 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523 fmt::Debug::fmt(&**self, f)
524 }
525 }
526
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl<T: ?Sized> fmt::Pointer for Box<T> {
529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530 // It's not possible to extract the inner Uniq directly from the Box,
531 // instead we cast it to a *const which aliases the Unique
532 let ptr: *const T = &**self;
533 fmt::Pointer::fmt(&ptr, f)
534 }
535 }
536
537 #[stable(feature = "rust1", since = "1.0.0")]
538 impl<T: ?Sized> Deref for Box<T> {
539 type Target = T;
540
541 fn deref(&self) -> &T {
542 &**self
543 }
544 }
545
546 #[stable(feature = "rust1", since = "1.0.0")]
547 impl<T: ?Sized> DerefMut for Box<T> {
548 fn deref_mut(&mut self) -> &mut T {
549 &mut **self
550 }
551 }
552
553 #[stable(feature = "rust1", since = "1.0.0")]
554 impl<I: Iterator + ?Sized> Iterator for Box<I> {
555 type Item = I::Item;
556 fn next(&mut self) -> Option<I::Item> {
557 (**self).next()
558 }
559 fn size_hint(&self) -> (usize, Option<usize>) {
560 (**self).size_hint()
561 }
562 fn nth(&mut self, n: usize) -> Option<I::Item> {
563 (**self).nth(n)
564 }
565 }
566 #[stable(feature = "rust1", since = "1.0.0")]
567 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
568 fn next_back(&mut self) -> Option<I::Item> {
569 (**self).next_back()
570 }
571 }
572 #[stable(feature = "rust1", since = "1.0.0")]
573 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
574 fn len(&self) -> usize {
575 (**self).len()
576 }
577 fn is_empty(&self) -> bool {
578 (**self).is_empty()
579 }
580 }
581
582 #[stable(feature = "fused", since = "1.26.0")]
583 impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
584
585
586 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
587 /// closure objects. The idea is that where one would normally store a
588 /// `Box<FnOnce()>` in a data structure, you should use
589 /// `Box<FnBox()>`. The two traits behave essentially the same, except
590 /// that a `FnBox` closure can only be called if it is boxed. (Note
591 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
592 /// closures become directly usable.)
593 ///
594 /// # Examples
595 ///
596 /// Here is a snippet of code which creates a hashmap full of boxed
597 /// once closures and then removes them one by one, calling each
598 /// closure as it is removed. Note that the type of the closures
599 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
600 /// -> i32>`.
601 ///
602 /// ```
603 /// #![feature(fnbox)]
604 ///
605 /// use std::boxed::FnBox;
606 /// use std::collections::HashMap;
607 ///
608 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
609 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
610 /// map.insert(1, Box::new(|| 22));
611 /// map.insert(2, Box::new(|| 44));
612 /// map
613 /// }
614 ///
615 /// fn main() {
616 /// let mut map = make_map();
617 /// for i in &[1, 2] {
618 /// let f = map.remove(&i).unwrap();
619 /// assert_eq!(f(), i * 22);
620 /// }
621 /// }
622 /// ```
623 #[rustc_paren_sugar]
624 #[unstable(feature = "fnbox",
625 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
626 pub trait FnBox<A> {
627 type Output;
628
629 fn call_box(self: Box<Self>, args: A) -> Self::Output;
630 }
631
632 #[unstable(feature = "fnbox",
633 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
634 impl<A, F> FnBox<A> for F
635 where F: FnOnce<A>
636 {
637 type Output = F::Output;
638
639 fn call_box(self: Box<F>, args: A) -> F::Output {
640 self.call_once(args)
641 }
642 }
643
644 #[unstable(feature = "fnbox",
645 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
646 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + 'a> {
647 type Output = R;
648
649 extern "rust-call" fn call_once(self, args: A) -> R {
650 self.call_box(args)
651 }
652 }
653
654 #[unstable(feature = "fnbox",
655 reason = "will be deprecated if and when `Box<FnOnce>` becomes usable", issue = "28796")]
656 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + Send + 'a> {
657 type Output = R;
658
659 extern "rust-call" fn call_once(self, args: A) -> R {
660 self.call_box(args)
661 }
662 }
663
664 #[unstable(feature = "coerce_unsized", issue = "27732")]
665 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
666
667 #[stable(feature = "box_slice_clone", since = "1.3.0")]
668 impl<T: Clone> Clone for Box<[T]> {
669 fn clone(&self) -> Self {
670 let mut new = BoxBuilder {
671 data: RawVec::with_capacity(self.len()),
672 len: 0,
673 };
674
675 let mut target = new.data.ptr();
676
677 for item in self.iter() {
678 unsafe {
679 ptr::write(target, item.clone());
680 target = target.offset(1);
681 };
682
683 new.len += 1;
684 }
685
686 return unsafe { new.into_box() };
687
688 // Helper type for responding to panics correctly.
689 struct BoxBuilder<T> {
690 data: RawVec<T>,
691 len: usize,
692 }
693
694 impl<T> BoxBuilder<T> {
695 unsafe fn into_box(self) -> Box<[T]> {
696 let raw = ptr::read(&self.data);
697 mem::forget(self);
698 raw.into_box()
699 }
700 }
701
702 impl<T> Drop for BoxBuilder<T> {
703 fn drop(&mut self) {
704 let mut data = self.data.ptr();
705 let max = unsafe { data.offset(self.len as isize) };
706
707 while data != max {
708 unsafe {
709 ptr::read(data);
710 data = data.offset(1);
711 }
712 }
713 }
714 }
715 }
716 }
717
718 #[stable(feature = "box_borrow", since = "1.1.0")]
719 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
720 fn borrow(&self) -> &T {
721 &**self
722 }
723 }
724
725 #[stable(feature = "box_borrow", since = "1.1.0")]
726 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
727 fn borrow_mut(&mut self) -> &mut T {
728 &mut **self
729 }
730 }
731
732 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
733 impl<T: ?Sized> AsRef<T> for Box<T> {
734 fn as_ref(&self) -> &T {
735 &**self
736 }
737 }
738
739 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
740 impl<T: ?Sized> AsMut<T> for Box<T> {
741 fn as_mut(&mut self) -> &mut T {
742 &mut **self
743 }
744 }
745
746 #[unstable(feature = "generator_trait", issue = "43122")]
747 impl<T> Generator for Box<T>
748 where T: Generator + ?Sized
749 {
750 type Yield = T::Yield;
751 type Return = T::Return;
752 unsafe fn resume(&mut self) -> GeneratorState<Self::Yield, Self::Return> {
753 (**self).resume()
754 }
755 }
756
757 /// A pinned, heap allocated reference.
758 #[unstable(feature = "pin", issue = "49150")]
759 #[fundamental]
760 #[repr(transparent)]
761 pub struct PinBox<T: ?Sized> {
762 inner: Box<T>,
763 }
764
765 #[unstable(feature = "pin", issue = "49150")]
766 impl<T> PinBox<T> {
767 /// Allocate memory on the heap, move the data into it and pin it.
768 #[unstable(feature = "pin", issue = "49150")]
769 pub fn new(data: T) -> PinBox<T> {
770 PinBox { inner: Box::new(data) }
771 }
772 }
773
774 #[unstable(feature = "pin", issue = "49150")]
775 impl<T: ?Sized> PinBox<T> {
776 /// Get a pinned reference to the data in this PinBox.
777 #[inline]
778 pub fn as_pin_mut<'a>(&'a mut self) -> PinMut<'a, T> {
779 unsafe { PinMut::new_unchecked(&mut *self.inner) }
780 }
781
782 /// Constructs a `PinBox` from a raw pointer.
783 ///
784 /// After calling this function, the raw pointer is owned by the
785 /// resulting `PinBox`. Specifically, the `PinBox` destructor will call
786 /// the destructor of `T` and free the allocated memory. Since the
787 /// way `PinBox` allocates and releases memory is unspecified, the
788 /// only valid pointer to pass to this function is the one taken
789 /// from another `PinBox` via the [`PinBox::into_raw`] function.
790 ///
791 /// This function is unsafe because improper use may lead to
792 /// memory problems. For example, a double-free may occur if the
793 /// function is called twice on the same raw pointer.
794 ///
795 /// [`PinBox::into_raw`]: struct.PinBox.html#method.into_raw
796 ///
797 /// # Examples
798 ///
799 /// ```
800 /// #![feature(pin)]
801 /// use std::boxed::PinBox;
802 /// let x = PinBox::new(5);
803 /// let ptr = PinBox::into_raw(x);
804 /// let x = unsafe { PinBox::from_raw(ptr) };
805 /// ```
806 #[inline]
807 pub unsafe fn from_raw(raw: *mut T) -> Self {
808 PinBox { inner: Box::from_raw(raw) }
809 }
810
811 /// Consumes the `PinBox`, returning the wrapped raw pointer.
812 ///
813 /// After calling this function, the caller is responsible for the
814 /// memory previously managed by the `PinBox`. In particular, the
815 /// caller should properly destroy `T` and release the memory. The
816 /// proper way to do so is to convert the raw pointer back into a
817 /// `PinBox` with the [`PinBox::from_raw`] function.
818 ///
819 /// Note: this is an associated function, which means that you have
820 /// to call it as `PinBox::into_raw(b)` instead of `b.into_raw()`. This
821 /// is so that there is no conflict with a method on the inner type.
822 ///
823 /// [`PinBox::from_raw`]: struct.PinBox.html#method.from_raw
824 ///
825 /// # Examples
826 ///
827 /// ```
828 /// #![feature(pin)]
829 /// use std::boxed::PinBox;
830 /// let x = PinBox::new(5);
831 /// let ptr = PinBox::into_raw(x);
832 /// ```
833 #[inline]
834 pub fn into_raw(b: PinBox<T>) -> *mut T {
835 Box::into_raw(b.inner)
836 }
837
838 /// Get a mutable reference to the data inside this PinBox.
839 ///
840 /// This function is unsafe. Users must guarantee that the data is never
841 /// moved out of this reference.
842 #[inline]
843 pub unsafe fn get_mut<'a>(this: &'a mut PinBox<T>) -> &'a mut T {
844 &mut *this.inner
845 }
846
847 /// Convert this PinBox into an unpinned Box.
848 ///
849 /// This function is unsafe. Users must guarantee that the data is never
850 /// moved out of the box.
851 #[inline]
852 pub unsafe fn unpin(this: PinBox<T>) -> Box<T> {
853 this.inner
854 }
855 }
856
857 #[unstable(feature = "pin", issue = "49150")]
858 impl<T: ?Sized> From<Box<T>> for PinBox<T> {
859 fn from(boxed: Box<T>) -> PinBox<T> {
860 PinBox { inner: boxed }
861 }
862 }
863
864 #[unstable(feature = "pin", issue = "49150")]
865 impl<T: Unpin + ?Sized> From<PinBox<T>> for Box<T> {
866 fn from(pinned: PinBox<T>) -> Box<T> {
867 pinned.inner
868 }
869 }
870
871 #[unstable(feature = "pin", issue = "49150")]
872 impl<T: ?Sized> Deref for PinBox<T> {
873 type Target = T;
874
875 fn deref(&self) -> &T {
876 &*self.inner
877 }
878 }
879
880 #[unstable(feature = "pin", issue = "49150")]
881 impl<T: Unpin + ?Sized> DerefMut for PinBox<T> {
882 fn deref_mut(&mut self) -> &mut T {
883 &mut *self.inner
884 }
885 }
886
887 #[unstable(feature = "pin", issue = "49150")]
888 impl<T: fmt::Display + ?Sized> fmt::Display for PinBox<T> {
889 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
890 fmt::Display::fmt(&*self.inner, f)
891 }
892 }
893
894 #[unstable(feature = "pin", issue = "49150")]
895 impl<T: fmt::Debug + ?Sized> fmt::Debug for PinBox<T> {
896 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
897 fmt::Debug::fmt(&*self.inner, f)
898 }
899 }
900
901 #[unstable(feature = "pin", issue = "49150")]
902 impl<T: ?Sized> fmt::Pointer for PinBox<T> {
903 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
904 // It's not possible to extract the inner Uniq directly from the Box,
905 // instead we cast it to a *const which aliases the Unique
906 let ptr: *const T = &*self.inner;
907 fmt::Pointer::fmt(&ptr, f)
908 }
909 }
910
911 #[unstable(feature = "pin", issue = "49150")]
912 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<PinBox<U>> for PinBox<T> {}
913
914 #[unstable(feature = "pin", issue = "49150")]
915 impl<T: ?Sized> Unpin for PinBox<T> {}
916
917 #[unstable(feature = "futures_api", issue = "50547")]
918 impl<'a, F: ?Sized + Future + Unpin> Future for Box<F> {
919 type Output = F::Output;
920
921 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
922 PinMut::new(&mut **self).poll(cx)
923 }
924 }
925
926 #[unstable(feature = "futures_api", issue = "50547")]
927 impl<'a, F: ?Sized + Future> Future for PinBox<F> {
928 type Output = F::Output;
929
930 fn poll(mut self: PinMut<Self>, cx: &mut Context) -> Poll<Self::Output> {
931 self.as_pin_mut().poll(cx)
932 }
933 }
934
935 #[unstable(feature = "futures_api", issue = "50547")]
936 unsafe impl<F: Future<Output = ()> + Send + 'static> UnsafeTask for PinBox<F> {
937 fn into_raw(self) -> *mut () {
938 PinBox::into_raw(self) as *mut ()
939 }
940
941 unsafe fn poll(task: *mut (), cx: &mut Context) -> Poll<()> {
942 let ptr = task as *mut F;
943 let pin: PinMut<F> = PinMut::new_unchecked(&mut *ptr);
944 pin.poll(cx)
945 }
946
947 unsafe fn drop(task: *mut ()) {
948 drop(PinBox::from_raw(task as *mut F))
949 }
950 }
951
952 #[unstable(feature = "futures_api", issue = "50547")]
953 impl<F: Future<Output = ()> + Send + 'static> From<PinBox<F>> for TaskObj {
954 fn from(boxed: PinBox<F>) -> Self {
955 TaskObj::new(boxed)
956 }
957 }
958
959 #[unstable(feature = "futures_api", issue = "50547")]
960 impl<F: Future<Output = ()> + Send + 'static> From<Box<F>> for TaskObj {
961 fn from(boxed: Box<F>) -> Self {
962 TaskObj::new(PinBox::from(boxed))
963 }
964 }