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