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