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