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