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