]> git.proxmox.com Git - rustc.git/blob - src/libcore/any.rs
Imported Upstream version 1.3.0+dfsg1
[rustc.git] / src / libcore / any.rs
1 // Copyright 2013-2014 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 //! This module implements the `Any` trait, which enables dynamic typing
12 //! of any `'static` type through runtime reflection.
13 //!
14 //! `Any` itself can be used to get a `TypeId`, and has more features when used
15 //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and
16 //! `as_ref` methods, to test if the contained value is of a given type, and to
17 //! get a reference to the inner value as a type. As `&mut Any`, there is also
18 //! the `as_mut` method, for getting a mutable reference to the inner value.
19 //! `Box<Any>` adds the `move` method, which will unwrap a `Box<T>` from the
20 //! object. See the extension traits (`*Ext`) for the full details.
21 //!
22 //! Note that &Any is limited to testing whether a value is of a specified
23 //! concrete type, and cannot be used to test whether a type implements a trait.
24 //!
25 //! # Examples
26 //!
27 //! Consider a situation where we want to log out a value passed to a function.
28 //! We know the value we're working on implements Debug, but we don't know its
29 //! concrete type. We want to give special treatment to certain types: in this
30 //! case printing out the length of String values prior to their value.
31 //! We don't know the concrete type of our value at compile time, so we need to
32 //! use runtime reflection instead.
33 //!
34 //! ```rust
35 //! use std::fmt::Debug;
36 //! use std::any::Any;
37 //!
38 //! // Logger function for any type that implements Debug.
39 //! fn log<T: Any + Debug>(value: &T) {
40 //! let value_any = value as &Any;
41 //!
42 //! // try to convert our value to a String. If successful, we want to
43 //! // output the String's length as well as its value. If not, it's a
44 //! // different type: just print it out unadorned.
45 //! match value_any.downcast_ref::<String>() {
46 //! Some(as_string) => {
47 //! println!("String ({}): {}", as_string.len(), as_string);
48 //! }
49 //! None => {
50 //! println!("{:?}", value);
51 //! }
52 //! }
53 //! }
54 //!
55 //! // This function wants to log its parameter out prior to doing work with it.
56 //! fn do_work<T: Any + Debug>(value: &T) {
57 //! log(value);
58 //! // ...do some other work
59 //! }
60 //!
61 //! fn main() {
62 //! let my_string = "Hello World".to_string();
63 //! do_work(&my_string);
64 //!
65 //! let my_i8: i8 = 100;
66 //! do_work(&my_i8);
67 //! }
68 //! ```
69
70 #![stable(feature = "rust1", since = "1.0.0")]
71
72 use fmt;
73 use marker::Send;
74 use mem::transmute;
75 use option::Option::{self, Some, None};
76 use raw::TraitObject;
77 use intrinsics;
78 use marker::{Reflect, Sized};
79
80 ///////////////////////////////////////////////////////////////////////////////
81 // Any trait
82 ///////////////////////////////////////////////////////////////////////////////
83
84 /// A type to emulate dynamic typing.
85 ///
86 /// Every type with no non-`'static` references implements `Any`.
87 /// See the [module-level documentation][mod] for more details.
88 ///
89 /// [mod]: index.html
90 #[stable(feature = "rust1", since = "1.0.0")]
91 pub trait Any: Reflect + 'static {
92 /// Gets the `TypeId` of `self`.
93 #[unstable(feature = "get_type_id",
94 reason = "this method will likely be replaced by an associated static")]
95 fn get_type_id(&self) -> TypeId;
96 }
97
98 impl<T: Reflect + 'static> Any for T {
99 fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
100 }
101
102 ///////////////////////////////////////////////////////////////////////////////
103 // Extension methods for Any trait objects.
104 ///////////////////////////////////////////////////////////////////////////////
105
106 #[stable(feature = "rust1", since = "1.0.0")]
107 impl fmt::Debug for Any {
108 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
109 f.pad("Any")
110 }
111 }
112
113 // Ensure that the result of e.g. joining a thread can be printed and
114 // hence used with `unwrap`. May eventually no longer be needed if
115 // dispatch works with upcasting.
116 #[stable(feature = "rust1", since = "1.0.0")]
117 impl fmt::Debug for Any + Send {
118 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
119 f.pad("Any")
120 }
121 }
122
123 impl Any {
124 /// Returns true if the boxed type is the same as `T`
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[inline]
127 pub fn is<T: Any>(&self) -> bool {
128 // Get TypeId of the type this function is instantiated with
129 let t = TypeId::of::<T>();
130
131 // Get TypeId of the type in the trait object
132 let boxed = self.get_type_id();
133
134 // Compare both TypeIds on equality
135 t == boxed
136 }
137
138 /// Returns some reference to the boxed value if it is of type `T`, or
139 /// `None` if it isn't.
140 #[stable(feature = "rust1", since = "1.0.0")]
141 #[inline]
142 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
143 if self.is::<T>() {
144 unsafe {
145 // Get the raw representation of the trait object
146 let to: TraitObject = transmute(self);
147
148 // Extract the data pointer
149 Some(transmute(to.data))
150 }
151 } else {
152 None
153 }
154 }
155
156 /// Returns some mutable reference to the boxed value if it is of type `T`, or
157 /// `None` if it isn't.
158 #[stable(feature = "rust1", since = "1.0.0")]
159 #[inline]
160 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
161 if self.is::<T>() {
162 unsafe {
163 // Get the raw representation of the trait object
164 let to: TraitObject = transmute(self);
165
166 // Extract the data pointer
167 Some(transmute(to.data))
168 }
169 } else {
170 None
171 }
172 }
173 }
174
175 impl Any+Send {
176 /// Forwards to the method defined on the type `Any`.
177 #[stable(feature = "rust1", since = "1.0.0")]
178 #[inline]
179 pub fn is<T: Any>(&self) -> bool {
180 Any::is::<T>(self)
181 }
182
183 /// Forwards to the method defined on the type `Any`.
184 #[stable(feature = "rust1", since = "1.0.0")]
185 #[inline]
186 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
187 Any::downcast_ref::<T>(self)
188 }
189
190 /// Forwards to the method defined on the type `Any`.
191 #[stable(feature = "rust1", since = "1.0.0")]
192 #[inline]
193 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
194 Any::downcast_mut::<T>(self)
195 }
196 }
197
198
199 ///////////////////////////////////////////////////////////////////////////////
200 // TypeID and its methods
201 ///////////////////////////////////////////////////////////////////////////////
202
203 /// A `TypeId` represents a globally unique identifier for a type.
204 ///
205 /// Each `TypeId` is an opaque object which does not allow inspection of what's
206 /// inside but does allow basic operations such as cloning, comparison,
207 /// printing, and showing.
208 ///
209 /// A `TypeId` is currently only available for types which ascribe to `'static`,
210 /// but this limitation may be removed in the future.
211 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
212 #[stable(feature = "rust1", since = "1.0.0")]
213 pub struct TypeId {
214 t: u64,
215 }
216
217 impl TypeId {
218 /// Returns the `TypeId` of the type this generic function has been
219 /// instantiated with
220 #[stable(feature = "rust1", since = "1.0.0")]
221 pub fn of<T: ?Sized + Reflect + 'static>() -> TypeId {
222 TypeId {
223 t: unsafe { intrinsics::type_id::<T>() },
224 }
225 }
226 }