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