]> git.proxmox.com Git - rustc.git/blob - src/liballoc/boxed.rs
New upstream version 1.12.0+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 //! ```rust,ignore
46 //! Cons(T, List<T>),
47 //! ```
48 //!
49 //! It wouldn't work. This is because the size of a `List` depends on how many
50 //! elements are in the list, and so we don't know how much memory to allocate
51 //! for a `Cons`. By introducing a `Box`, which has a defined size, we know how
52 //! big `Cons` needs to be.
53
54 #![stable(feature = "rust1", since = "1.0.0")]
55
56 use heap;
57 use raw_vec::RawVec;
58
59 use core::any::Any;
60 use core::borrow;
61 use core::cmp::Ordering;
62 use core::fmt;
63 use core::hash::{self, Hash};
64 use core::marker::{self, Unsize};
65 use core::mem;
66 use core::ops::{CoerceUnsized, Deref, DerefMut};
67 use core::ops::{BoxPlace, Boxed, InPlace, Place, Placer};
68 use core::ptr::{self, Unique};
69 use core::raw::TraitObject;
70 use core::convert::From;
71
72 /// A value that represents the heap. This is the default place that the `box`
73 /// keyword allocates into when no place is supplied.
74 ///
75 /// The following two examples are equivalent:
76 ///
77 /// ```
78 /// #![feature(box_heap)]
79 ///
80 /// #![feature(box_syntax, placement_in_syntax)]
81 /// use std::boxed::HEAP;
82 ///
83 /// fn main() {
84 /// let foo: Box<i32> = in HEAP { 5 };
85 /// let foo = box 5;
86 /// }
87 /// ```
88 #[unstable(feature = "box_heap",
89 reason = "may be renamed; uncertain about custom allocator design",
90 issue = "27779")]
91 pub const HEAP: ExchangeHeapSingleton = ExchangeHeapSingleton { _force_singleton: () };
92
93 /// This the singleton type used solely for `boxed::HEAP`.
94 #[unstable(feature = "box_heap",
95 reason = "may be renamed; uncertain about custom allocator design",
96 issue = "27779")]
97 #[derive(Copy, Clone)]
98 pub struct ExchangeHeapSingleton {
99 _force_singleton: (),
100 }
101
102 /// A pointer type for heap allocation.
103 ///
104 /// See the [module-level documentation](../../std/boxed/index.html) for more.
105 #[lang = "owned_box"]
106 #[stable(feature = "rust1", since = "1.0.0")]
107 pub struct Box<T: ?Sized>(Unique<T>);
108
109 /// `IntermediateBox` represents uninitialized backing storage for `Box`.
110 ///
111 /// FIXME (pnkfelix): Ideally we would just reuse `Box<T>` instead of
112 /// introducing a separate `IntermediateBox<T>`; but then you hit
113 /// issues when you e.g. attempt to destructure an instance of `Box`,
114 /// since it is a lang item and so it gets special handling by the
115 /// compiler. Easier just to make this parallel type for now.
116 ///
117 /// FIXME (pnkfelix): Currently the `box` protocol only supports
118 /// creating instances of sized types. This IntermediateBox is
119 /// designed to be forward-compatible with a future protocol that
120 /// supports creating instances of unsized types; that is why the type
121 /// parameter has the `?Sized` generalization marker, and is also why
122 /// this carries an explicit size. However, it probably does not need
123 /// to carry the explicit alignment; that is just a work-around for
124 /// the fact that the `align_of` intrinsic currently requires the
125 /// input type to be Sized (which I do not think is strictly
126 /// necessary).
127 #[unstable(feature = "placement_in",
128 reason = "placement box design is still being worked out.",
129 issue = "27779")]
130 pub struct IntermediateBox<T: ?Sized> {
131 ptr: *mut u8,
132 size: usize,
133 align: usize,
134 marker: marker::PhantomData<*mut T>,
135 }
136
137 #[unstable(feature = "placement_in",
138 reason = "placement box design is still being worked out.",
139 issue = "27779")]
140 impl<T> Place<T> for IntermediateBox<T> {
141 fn pointer(&mut self) -> *mut T {
142 self.ptr as *mut T
143 }
144 }
145
146 unsafe fn finalize<T>(b: IntermediateBox<T>) -> Box<T> {
147 let p = b.ptr as *mut T;
148 mem::forget(b);
149 mem::transmute(p)
150 }
151
152 fn make_place<T>() -> IntermediateBox<T> {
153 let size = mem::size_of::<T>();
154 let align = mem::align_of::<T>();
155
156 let p = if size == 0 {
157 heap::EMPTY as *mut u8
158 } else {
159 let p = unsafe { heap::allocate(size, align) };
160 if p.is_null() {
161 panic!("Box make_place allocation failure.");
162 }
163 p
164 };
165
166 IntermediateBox {
167 ptr: p,
168 size: size,
169 align: align,
170 marker: marker::PhantomData,
171 }
172 }
173
174 #[unstable(feature = "placement_in",
175 reason = "placement box design is still being worked out.",
176 issue = "27779")]
177 impl<T> BoxPlace<T> for IntermediateBox<T> {
178 fn make_place() -> IntermediateBox<T> {
179 make_place()
180 }
181 }
182
183 #[unstable(feature = "placement_in",
184 reason = "placement box design is still being worked out.",
185 issue = "27779")]
186 impl<T> InPlace<T> for IntermediateBox<T> {
187 type Owner = Box<T>;
188 unsafe fn finalize(self) -> Box<T> {
189 finalize(self)
190 }
191 }
192
193 #[unstable(feature = "placement_new_protocol", issue = "27779")]
194 impl<T> Boxed for Box<T> {
195 type Data = T;
196 type Place = IntermediateBox<T>;
197 unsafe fn finalize(b: IntermediateBox<T>) -> Box<T> {
198 finalize(b)
199 }
200 }
201
202 #[unstable(feature = "placement_in",
203 reason = "placement box design is still being worked out.",
204 issue = "27779")]
205 impl<T> Placer<T> for ExchangeHeapSingleton {
206 type Place = IntermediateBox<T>;
207
208 fn make_place(self) -> IntermediateBox<T> {
209 make_place()
210 }
211 }
212
213 #[unstable(feature = "placement_in",
214 reason = "placement box design is still being worked out.",
215 issue = "27779")]
216 impl<T: ?Sized> Drop for IntermediateBox<T> {
217 fn drop(&mut self) {
218 if self.size > 0 {
219 unsafe { heap::deallocate(self.ptr, self.size, self.align) }
220 }
221 }
222 }
223
224 impl<T> Box<T> {
225 /// Allocates memory on the heap and then places `x` into it.
226 ///
227 /// # Examples
228 ///
229 /// ```
230 /// let five = Box::new(5);
231 /// ```
232 #[stable(feature = "rust1", since = "1.0.0")]
233 #[inline(always)]
234 pub fn new(x: T) -> Box<T> {
235 box x
236 }
237 }
238
239 impl<T: ?Sized> Box<T> {
240 /// Constructs a box from a raw pointer.
241 ///
242 /// After calling this function, the raw pointer is owned by the
243 /// resulting `Box`. Specifically, the `Box` destructor will call
244 /// the destructor of `T` and free the allocated memory. Since the
245 /// way `Box` allocates and releases memory is unspecified, the
246 /// only valid pointer to pass to this function is the one taken
247 /// from another `Box` via the `Box::into_raw` function.
248 ///
249 /// This function is unsafe because improper use may lead to
250 /// memory problems. For example, a double-free may occur if the
251 /// function is called twice on the same raw pointer.
252 ///
253 /// # Examples
254 ///
255 /// ```
256 /// let x = Box::new(5);
257 /// let ptr = Box::into_raw(x);
258 /// let x = unsafe { Box::from_raw(ptr) };
259 /// ```
260 #[stable(feature = "box_raw", since = "1.4.0")]
261 #[inline]
262 pub unsafe fn from_raw(raw: *mut T) -> Self {
263 mem::transmute(raw)
264 }
265
266 /// Consumes the `Box`, returning the wrapped raw pointer.
267 ///
268 /// After calling this function, the caller is responsible for the
269 /// memory previously managed by the `Box`. In particular, the
270 /// caller should properly destroy `T` and release the memory. The
271 /// proper way to do so is to convert the raw pointer back into a
272 /// `Box` with the `Box::from_raw` function.
273 ///
274 /// # Examples
275 ///
276 /// ```
277 /// let x = Box::new(5);
278 /// let ptr = Box::into_raw(x);
279 /// ```
280 #[stable(feature = "box_raw", since = "1.4.0")]
281 #[inline]
282 pub fn into_raw(b: Box<T>) -> *mut T {
283 unsafe { mem::transmute(b) }
284 }
285 }
286
287 #[stable(feature = "rust1", since = "1.0.0")]
288 impl<T: Default> Default for Box<T> {
289 fn default() -> Box<T> {
290 box Default::default()
291 }
292 }
293
294 #[stable(feature = "rust1", since = "1.0.0")]
295 impl<T> Default for Box<[T]> {
296 fn default() -> Box<[T]> {
297 Box::<[T; 0]>::new([])
298 }
299 }
300
301 #[stable(feature = "rust1", since = "1.0.0")]
302 impl<T: Clone> Clone for Box<T> {
303 /// Returns a new box with a `clone()` of this box's contents.
304 ///
305 /// # Examples
306 ///
307 /// ```
308 /// let x = Box::new(5);
309 /// let y = x.clone();
310 /// ```
311 #[rustfmt_skip]
312 #[inline]
313 fn clone(&self) -> Box<T> {
314 box { (**self).clone() }
315 }
316 /// Copies `source`'s contents into `self` without creating a new allocation.
317 ///
318 /// # Examples
319 ///
320 /// ```
321 /// let x = Box::new(5);
322 /// let mut y = Box::new(10);
323 ///
324 /// y.clone_from(&x);
325 ///
326 /// assert_eq!(*y, 5);
327 /// ```
328 #[inline]
329 fn clone_from(&mut self, source: &Box<T>) {
330 (**self).clone_from(&(**source));
331 }
332 }
333
334
335 #[stable(feature = "box_slice_clone", since = "1.3.0")]
336 impl Clone for Box<str> {
337 fn clone(&self) -> Self {
338 let len = self.len();
339 let buf = RawVec::with_capacity(len);
340 unsafe {
341 ptr::copy_nonoverlapping(self.as_ptr(), buf.ptr(), len);
342 mem::transmute(buf.into_box()) // bytes to str ~magic
343 }
344 }
345 }
346
347 #[stable(feature = "rust1", since = "1.0.0")]
348 impl<T: ?Sized + PartialEq> PartialEq for Box<T> {
349 #[inline]
350 fn eq(&self, other: &Box<T>) -> bool {
351 PartialEq::eq(&**self, &**other)
352 }
353 #[inline]
354 fn ne(&self, other: &Box<T>) -> bool {
355 PartialEq::ne(&**self, &**other)
356 }
357 }
358 #[stable(feature = "rust1", since = "1.0.0")]
359 impl<T: ?Sized + PartialOrd> PartialOrd for Box<T> {
360 #[inline]
361 fn partial_cmp(&self, other: &Box<T>) -> Option<Ordering> {
362 PartialOrd::partial_cmp(&**self, &**other)
363 }
364 #[inline]
365 fn lt(&self, other: &Box<T>) -> bool {
366 PartialOrd::lt(&**self, &**other)
367 }
368 #[inline]
369 fn le(&self, other: &Box<T>) -> bool {
370 PartialOrd::le(&**self, &**other)
371 }
372 #[inline]
373 fn ge(&self, other: &Box<T>) -> bool {
374 PartialOrd::ge(&**self, &**other)
375 }
376 #[inline]
377 fn gt(&self, other: &Box<T>) -> bool {
378 PartialOrd::gt(&**self, &**other)
379 }
380 }
381 #[stable(feature = "rust1", since = "1.0.0")]
382 impl<T: ?Sized + Ord> Ord for Box<T> {
383 #[inline]
384 fn cmp(&self, other: &Box<T>) -> Ordering {
385 Ord::cmp(&**self, &**other)
386 }
387 }
388 #[stable(feature = "rust1", since = "1.0.0")]
389 impl<T: ?Sized + Eq> Eq for Box<T> {}
390
391 #[stable(feature = "rust1", since = "1.0.0")]
392 impl<T: ?Sized + Hash> Hash for Box<T> {
393 fn hash<H: hash::Hasher>(&self, state: &mut H) {
394 (**self).hash(state);
395 }
396 }
397
398 #[stable(feature = "from_for_ptrs", since = "1.6.0")]
399 impl<T> From<T> for Box<T> {
400 fn from(t: T) -> Self {
401 Box::new(t)
402 }
403 }
404
405 impl Box<Any> {
406 #[inline]
407 #[stable(feature = "rust1", since = "1.0.0")]
408 /// Attempt to downcast the box to a concrete type.
409 ///
410 /// # Examples
411 ///
412 /// ```
413 /// use std::any::Any;
414 ///
415 /// fn print_if_string(value: Box<Any>) {
416 /// if let Ok(string) = value.downcast::<String>() {
417 /// println!("String ({}): {}", string.len(), string);
418 /// }
419 /// }
420 ///
421 /// fn main() {
422 /// let my_string = "Hello World".to_string();
423 /// print_if_string(Box::new(my_string));
424 /// print_if_string(Box::new(0i8));
425 /// }
426 /// ```
427 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any>> {
428 if self.is::<T>() {
429 unsafe {
430 // Get the raw representation of the trait object
431 let raw = Box::into_raw(self);
432 let to: TraitObject = mem::transmute::<*mut Any, TraitObject>(raw);
433
434 // Extract the data pointer
435 Ok(Box::from_raw(to.data as *mut T))
436 }
437 } else {
438 Err(self)
439 }
440 }
441 }
442
443 impl Box<Any + Send> {
444 #[inline]
445 #[stable(feature = "rust1", since = "1.0.0")]
446 /// Attempt to downcast the box to a concrete type.
447 ///
448 /// # Examples
449 ///
450 /// ```
451 /// use std::any::Any;
452 ///
453 /// fn print_if_string(value: Box<Any + Send>) {
454 /// if let Ok(string) = value.downcast::<String>() {
455 /// println!("String ({}): {}", string.len(), string);
456 /// }
457 /// }
458 ///
459 /// fn main() {
460 /// let my_string = "Hello World".to_string();
461 /// print_if_string(Box::new(my_string));
462 /// print_if_string(Box::new(0i8));
463 /// }
464 /// ```
465 pub fn downcast<T: Any>(self) -> Result<Box<T>, Box<Any + Send>> {
466 <Box<Any>>::downcast(self).map_err(|s| unsafe {
467 // reapply the Send marker
468 mem::transmute::<Box<Any>, Box<Any + Send>>(s)
469 })
470 }
471 }
472
473 #[stable(feature = "rust1", since = "1.0.0")]
474 impl<T: fmt::Display + ?Sized> fmt::Display for Box<T> {
475 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
476 fmt::Display::fmt(&**self, f)
477 }
478 }
479
480 #[stable(feature = "rust1", since = "1.0.0")]
481 impl<T: fmt::Debug + ?Sized> fmt::Debug for Box<T> {
482 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
483 fmt::Debug::fmt(&**self, f)
484 }
485 }
486
487 #[stable(feature = "rust1", since = "1.0.0")]
488 impl<T: ?Sized> fmt::Pointer for Box<T> {
489 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
490 // It's not possible to extract the inner Uniq directly from the Box,
491 // instead we cast it to a *const which aliases the Unique
492 let ptr: *const T = &**self;
493 fmt::Pointer::fmt(&ptr, f)
494 }
495 }
496
497 #[stable(feature = "rust1", since = "1.0.0")]
498 impl<T: ?Sized> Deref for Box<T> {
499 type Target = T;
500
501 fn deref(&self) -> &T {
502 &**self
503 }
504 }
505
506 #[stable(feature = "rust1", since = "1.0.0")]
507 impl<T: ?Sized> DerefMut for Box<T> {
508 fn deref_mut(&mut self) -> &mut T {
509 &mut **self
510 }
511 }
512
513 #[stable(feature = "rust1", since = "1.0.0")]
514 impl<I: Iterator + ?Sized> Iterator for Box<I> {
515 type Item = I::Item;
516 fn next(&mut self) -> Option<I::Item> {
517 (**self).next()
518 }
519 fn size_hint(&self) -> (usize, Option<usize>) {
520 (**self).size_hint()
521 }
522 }
523 #[stable(feature = "rust1", since = "1.0.0")]
524 impl<I: DoubleEndedIterator + ?Sized> DoubleEndedIterator for Box<I> {
525 fn next_back(&mut self) -> Option<I::Item> {
526 (**self).next_back()
527 }
528 }
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {}
531
532
533 /// `FnBox` is a version of the `FnOnce` intended for use with boxed
534 /// closure objects. The idea is that where one would normally store a
535 /// `Box<FnOnce()>` in a data structure, you should use
536 /// `Box<FnBox()>`. The two traits behave essentially the same, except
537 /// that a `FnBox` closure can only be called if it is boxed. (Note
538 /// that `FnBox` may be deprecated in the future if `Box<FnOnce()>`
539 /// closures become directly usable.)
540 ///
541 /// ### Example
542 ///
543 /// Here is a snippet of code which creates a hashmap full of boxed
544 /// once closures and then removes them one by one, calling each
545 /// closure as it is removed. Note that the type of the closures
546 /// stored in the map is `Box<FnBox() -> i32>` and not `Box<FnOnce()
547 /// -> i32>`.
548 ///
549 /// ```
550 /// #![feature(fnbox)]
551 ///
552 /// use std::boxed::FnBox;
553 /// use std::collections::HashMap;
554 ///
555 /// fn make_map() -> HashMap<i32, Box<FnBox() -> i32>> {
556 /// let mut map: HashMap<i32, Box<FnBox() -> i32>> = HashMap::new();
557 /// map.insert(1, Box::new(|| 22));
558 /// map.insert(2, Box::new(|| 44));
559 /// map
560 /// }
561 ///
562 /// fn main() {
563 /// let mut map = make_map();
564 /// for i in &[1, 2] {
565 /// let f = map.remove(&i).unwrap();
566 /// assert_eq!(f(), i * 22);
567 /// }
568 /// }
569 /// ```
570 #[rustc_paren_sugar]
571 #[unstable(feature = "fnbox",
572 reason = "will be deprecated if and when Box<FnOnce> becomes usable", issue = "28796")]
573 pub trait FnBox<A> {
574 type Output;
575
576 fn call_box(self: Box<Self>, args: A) -> Self::Output;
577 }
578
579 #[unstable(feature = "fnbox",
580 reason = "will be deprecated if and when Box<FnOnce> becomes usable", issue = "28796")]
581 impl<A, F> FnBox<A> for F
582 where F: FnOnce<A>
583 {
584 type Output = F::Output;
585
586 fn call_box(self: Box<F>, args: A) -> F::Output {
587 self.call_once(args)
588 }
589 }
590
591 #[unstable(feature = "fnbox",
592 reason = "will be deprecated if and when Box<FnOnce> becomes usable", issue = "28796")]
593 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + 'a> {
594 type Output = R;
595
596 extern "rust-call" fn call_once(self, args: A) -> R {
597 self.call_box(args)
598 }
599 }
600
601 #[unstable(feature = "fnbox",
602 reason = "will be deprecated if and when Box<FnOnce> becomes usable", issue = "28796")]
603 impl<'a, A, R> FnOnce<A> for Box<FnBox<A, Output = R> + Send + 'a> {
604 type Output = R;
605
606 extern "rust-call" fn call_once(self, args: A) -> R {
607 self.call_box(args)
608 }
609 }
610
611 #[unstable(feature = "coerce_unsized", issue = "27732")]
612 impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
613
614 #[stable(feature = "box_slice_clone", since = "1.3.0")]
615 impl<T: Clone> Clone for Box<[T]> {
616 fn clone(&self) -> Self {
617 let mut new = BoxBuilder {
618 data: RawVec::with_capacity(self.len()),
619 len: 0,
620 };
621
622 let mut target = new.data.ptr();
623
624 for item in self.iter() {
625 unsafe {
626 ptr::write(target, item.clone());
627 target = target.offset(1);
628 };
629
630 new.len += 1;
631 }
632
633 return unsafe { new.into_box() };
634
635 // Helper type for responding to panics correctly.
636 struct BoxBuilder<T> {
637 data: RawVec<T>,
638 len: usize,
639 }
640
641 impl<T> BoxBuilder<T> {
642 unsafe fn into_box(self) -> Box<[T]> {
643 let raw = ptr::read(&self.data);
644 mem::forget(self);
645 raw.into_box()
646 }
647 }
648
649 impl<T> Drop for BoxBuilder<T> {
650 fn drop(&mut self) {
651 let mut data = self.data.ptr();
652 let max = unsafe { data.offset(self.len as isize) };
653
654 while data != max {
655 unsafe {
656 ptr::read(data);
657 data = data.offset(1);
658 }
659 }
660 }
661 }
662 }
663 }
664
665 #[stable(feature = "rust1", since = "1.0.0")]
666 impl<T: ?Sized> borrow::Borrow<T> for Box<T> {
667 fn borrow(&self) -> &T {
668 &**self
669 }
670 }
671
672 #[stable(feature = "rust1", since = "1.0.0")]
673 impl<T: ?Sized> borrow::BorrowMut<T> for Box<T> {
674 fn borrow_mut(&mut self) -> &mut T {
675 &mut **self
676 }
677 }
678
679 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
680 impl<T: ?Sized> AsRef<T> for Box<T> {
681 fn as_ref(&self) -> &T {
682 &**self
683 }
684 }
685
686 #[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
687 impl<T: ?Sized> AsMut<T> for Box<T> {
688 fn as_mut(&mut self) -> &mut T {
689 &mut **self
690 }
691 }