// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! Operations on unique pointer types use any::{Any, AnyRefExt}; use clone::Clone; use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering}; use default::Default; use intrinsics; use mem; use raw::TraitObject; use result::{Ok, Err, Result}; /// A value that represents the global exchange heap. This is the default /// place that the `box` keyword allocates into when no place is supplied. /// /// The following two examples are equivalent: /// /// let foo = box(HEAP) Bar::new(...); /// let foo = box Bar::new(...); #[lang="exchange_heap"] pub static HEAP: () = (); /// A type that represents a uniquely-owned value. #[lang="owned_box"] pub struct Box(*T); impl Default for Box { fn default() -> Box { box Default::default() } } impl Clone for Box { /// Return a copy of the owned box. #[inline] fn clone(&self) -> Box { box {(**self).clone()} } /// Perform copy-assignment from `source` by reusing the existing allocation. #[inline] fn clone_from(&mut self, source: &Box) { (**self).clone_from(&(**source)); } } // box pointers impl Eq for Box { #[inline] fn eq(&self, other: &Box) -> bool { *(*self) == *(*other) } #[inline] fn ne(&self, other: &Box) -> bool { *(*self) != *(*other) } } impl Ord for Box { #[inline] fn lt(&self, other: &Box) -> bool { *(*self) < *(*other) } #[inline] fn le(&self, other: &Box) -> bool { *(*self) <= *(*other) } #[inline] fn ge(&self, other: &Box) -> bool { *(*self) >= *(*other) } #[inline] fn gt(&self, other: &Box) -> bool { *(*self) > *(*other) } } impl TotalOrd for Box { #[inline] fn cmp(&self, other: &Box) -> Ordering { (**self).cmp(*other) } } impl TotalEq for Box {} /// Extension methods for an owning `Any` trait object pub trait AnyOwnExt { /// Returns the boxed value if it is of type `T`, or /// `Err(Self)` if it isn't. fn move(self) -> Result, Self>; } impl AnyOwnExt for Box { #[inline] fn move(self) -> Result, Box> { if self.is::() { unsafe { // Get the raw representation of the trait object let to: TraitObject = *mem::transmute::<&Box, &TraitObject>(&self); // Prevent destructor on self being run intrinsics::forget(self); // Extract the data pointer Ok(mem::transmute(to.data)) } } else { Err(self) } } }