]> git.proxmox.com Git - rustc.git/blob - src/libcore/any.rs
New upstream version 1.12.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 //! `downcast_ref` methods, to test if the contained value is of a given type,
17 //! and to get a reference to the inner value as a type. As `&mut Any`, there
18 //! is also the `downcast_mut` method, for getting a mutable reference to the
19 //! inner value. `Box<Any>` adds the `downcast` method, which attempts to
20 //! convert to a `Box<T>`. See the [`Box`] documentation 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 //! [`Box`]: ../../std/boxed/struct.Box.html
26 //!
27 //! # Examples
28 //!
29 //! Consider a situation where we want to log out a value passed to a function.
30 //! We know the value we're working on implements Debug, but we don't know its
31 //! concrete type. We want to give special treatment to certain types: in this
32 //! case printing out the length of String values prior to their value.
33 //! We don't know the concrete type of our value at compile time, so we need to
34 //! use runtime reflection instead.
35 //!
36 //! ```rust
37 //! use std::fmt::Debug;
38 //! use std::any::Any;
39 //!
40 //! // Logger function for any type that implements Debug.
41 //! fn log<T: Any + Debug>(value: &T) {
42 //! let value_any = value as &Any;
43 //!
44 //! // try to convert our value to a String. If successful, we want to
45 //! // output the String's length as well as its value. If not, it's a
46 //! // different type: just print it out unadorned.
47 //! match value_any.downcast_ref::<String>() {
48 //! Some(as_string) => {
49 //! println!("String ({}): {}", as_string.len(), as_string);
50 //! }
51 //! None => {
52 //! println!("{:?}", value);
53 //! }
54 //! }
55 //! }
56 //!
57 //! // This function wants to log its parameter out prior to doing work with it.
58 //! fn do_work<T: Any + Debug>(value: &T) {
59 //! log(value);
60 //! // ...do some other work
61 //! }
62 //!
63 //! fn main() {
64 //! let my_string = "Hello World".to_string();
65 //! do_work(&my_string);
66 //!
67 //! let my_i8: i8 = 100;
68 //! do_work(&my_i8);
69 //! }
70 //! ```
71
72 #![stable(feature = "rust1", since = "1.0.0")]
73
74 use fmt;
75 use marker::Send;
76 use mem::transmute;
77 use option::Option::{self, Some, None};
78 use raw::TraitObject;
79 use intrinsics;
80 use marker::{Reflect, Sized};
81
82 ///////////////////////////////////////////////////////////////////////////////
83 // Any trait
84 ///////////////////////////////////////////////////////////////////////////////
85
86 /// A type to emulate dynamic typing.
87 ///
88 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
89 /// See the [module-level documentation][mod] for more details.
90 ///
91 /// [mod]: index.html
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub trait Any: Reflect + 'static {
94 /// Gets the `TypeId` of `self`.
95 ///
96 /// # Examples
97 ///
98 /// ```
99 /// #![feature(get_type_id)]
100 ///
101 /// use std::any::{Any, TypeId};
102 ///
103 /// fn is_string(s: &Any) -> bool {
104 /// TypeId::of::<String>() == s.get_type_id()
105 /// }
106 ///
107 /// fn main() {
108 /// assert_eq!(is_string(&0), false);
109 /// assert_eq!(is_string(&"cookie monster".to_owned()), true);
110 /// }
111 /// ```
112 #[unstable(feature = "get_type_id",
113 reason = "this method will likely be replaced by an associated static",
114 issue = "27745")]
115 fn get_type_id(&self) -> TypeId;
116 }
117
118 #[stable(feature = "rust1", since = "1.0.0")]
119 impl<T: Reflect + 'static + ?Sized > Any for T {
120 fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
121 }
122
123 ///////////////////////////////////////////////////////////////////////////////
124 // Extension methods for Any trait objects.
125 ///////////////////////////////////////////////////////////////////////////////
126
127 #[stable(feature = "rust1", since = "1.0.0")]
128 impl fmt::Debug for Any {
129 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
130 f.pad("Any")
131 }
132 }
133
134 // Ensure that the result of e.g. joining a thread can be printed and
135 // hence used with `unwrap`. May eventually no longer be needed if
136 // dispatch works with upcasting.
137 #[stable(feature = "rust1", since = "1.0.0")]
138 impl fmt::Debug for Any + Send {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 f.pad("Any")
141 }
142 }
143
144 impl Any {
145 /// Returns true if the boxed type is the same as `T`.
146 ///
147 /// # Examples
148 ///
149 /// ```
150 /// use std::any::Any;
151 ///
152 /// fn is_string(s: &Any) {
153 /// if s.is::<String>() {
154 /// println!("It's a string!");
155 /// } else {
156 /// println!("Not a string...");
157 /// }
158 /// }
159 ///
160 /// fn main() {
161 /// is_string(&0);
162 /// is_string(&"cookie monster".to_owned());
163 /// }
164 /// ```
165 #[stable(feature = "rust1", since = "1.0.0")]
166 #[inline]
167 pub fn is<T: Any>(&self) -> bool {
168 // Get TypeId of the type this function is instantiated with
169 let t = TypeId::of::<T>();
170
171 // Get TypeId of the type in the trait object
172 let boxed = self.get_type_id();
173
174 // Compare both TypeIds on equality
175 t == boxed
176 }
177
178 /// Returns some reference to the boxed value if it is of type `T`, or
179 /// `None` if it isn't.
180 ///
181 /// # Examples
182 ///
183 /// ```
184 /// use std::any::Any;
185 ///
186 /// fn print_if_string(s: &Any) {
187 /// if let Some(string) = s.downcast_ref::<String>() {
188 /// println!("It's a string({}): '{}'", string.len(), string);
189 /// } else {
190 /// println!("Not a string...");
191 /// }
192 /// }
193 ///
194 /// fn main() {
195 /// print_if_string(&0);
196 /// print_if_string(&"cookie monster".to_owned());
197 /// }
198 /// ```
199 #[stable(feature = "rust1", since = "1.0.0")]
200 #[inline]
201 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
202 if self.is::<T>() {
203 unsafe {
204 // Get the raw representation of the trait object
205 let to: TraitObject = transmute(self);
206
207 // Extract the data pointer
208 Some(&*(to.data as *const T))
209 }
210 } else {
211 None
212 }
213 }
214
215 /// Returns some mutable reference to the boxed value if it is of type `T`, or
216 /// `None` if it isn't.
217 ///
218 /// # Examples
219 ///
220 /// ```
221 /// use std::any::Any;
222 ///
223 /// fn modify_if_u32(s: &mut Any) {
224 /// if let Some(num) = s.downcast_mut::<u32>() {
225 /// *num = 42;
226 /// }
227 /// }
228 ///
229 /// fn main() {
230 /// let mut x = 10u32;
231 /// let mut s = "starlord".to_owned();
232 ///
233 /// modify_if_u32(&mut x);
234 /// modify_if_u32(&mut s);
235 ///
236 /// assert_eq!(x, 42);
237 /// assert_eq!(&s, "starlord");
238 /// }
239 /// ```
240 #[stable(feature = "rust1", since = "1.0.0")]
241 #[inline]
242 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
243 if self.is::<T>() {
244 unsafe {
245 // Get the raw representation of the trait object
246 let to: TraitObject = transmute(self);
247
248 // Extract the data pointer
249 Some(&mut *(to.data as *const T as *mut T))
250 }
251 } else {
252 None
253 }
254 }
255 }
256
257 impl Any+Send {
258 /// Forwards to the method defined on the type `Any`.
259 ///
260 /// # Examples
261 ///
262 /// ```
263 /// use std::any::Any;
264 ///
265 /// fn is_string(s: &(Any + Send)) {
266 /// if s.is::<String>() {
267 /// println!("It's a string!");
268 /// } else {
269 /// println!("Not a string...");
270 /// }
271 /// }
272 ///
273 /// fn main() {
274 /// is_string(&0);
275 /// is_string(&"cookie monster".to_owned());
276 /// }
277 /// ```
278 #[stable(feature = "rust1", since = "1.0.0")]
279 #[inline]
280 pub fn is<T: Any>(&self) -> bool {
281 Any::is::<T>(self)
282 }
283
284 /// Forwards to the method defined on the type `Any`.
285 ///
286 /// # Examples
287 ///
288 /// ```
289 /// use std::any::Any;
290 ///
291 /// fn print_if_string(s: &(Any + Send)) {
292 /// if let Some(string) = s.downcast_ref::<String>() {
293 /// println!("It's a string({}): '{}'", string.len(), string);
294 /// } else {
295 /// println!("Not a string...");
296 /// }
297 /// }
298 ///
299 /// fn main() {
300 /// print_if_string(&0);
301 /// print_if_string(&"cookie monster".to_owned());
302 /// }
303 /// ```
304 #[stable(feature = "rust1", since = "1.0.0")]
305 #[inline]
306 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
307 Any::downcast_ref::<T>(self)
308 }
309
310 /// Forwards to the method defined on the type `Any`.
311 ///
312 /// # Examples
313 ///
314 /// ```
315 /// use std::any::Any;
316 ///
317 /// fn modify_if_u32(s: &mut (Any+ Send)) {
318 /// if let Some(num) = s.downcast_mut::<u32>() {
319 /// *num = 42;
320 /// }
321 /// }
322 ///
323 /// fn main() {
324 /// let mut x = 10u32;
325 /// let mut s = "starlord".to_owned();
326 ///
327 /// modify_if_u32(&mut x);
328 /// modify_if_u32(&mut s);
329 ///
330 /// assert_eq!(x, 42);
331 /// assert_eq!(&s, "starlord");
332 /// }
333 /// ```
334 #[stable(feature = "rust1", since = "1.0.0")]
335 #[inline]
336 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
337 Any::downcast_mut::<T>(self)
338 }
339 }
340
341
342 ///////////////////////////////////////////////////////////////////////////////
343 // TypeID and its methods
344 ///////////////////////////////////////////////////////////////////////////////
345
346 /// A `TypeId` represents a globally unique identifier for a type.
347 ///
348 /// Each `TypeId` is an opaque object which does not allow inspection of what's
349 /// inside but does allow basic operations such as cloning, comparison,
350 /// printing, and showing.
351 ///
352 /// A `TypeId` is currently only available for types which ascribe to `'static`,
353 /// but this limitation may be removed in the future.
354 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub struct TypeId {
357 t: u64,
358 }
359
360 impl TypeId {
361 /// Returns the `TypeId` of the type this generic function has been
362 /// instantiated with.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// #![feature(get_type_id)]
368 ///
369 /// use std::any::{Any, TypeId};
370 ///
371 /// fn is_string(s: &Any) -> bool {
372 /// TypeId::of::<String>() == s.get_type_id()
373 /// }
374 ///
375 /// fn main() {
376 /// assert_eq!(is_string(&0), false);
377 /// assert_eq!(is_string(&"cookie monster".to_owned()), true);
378 /// }
379 /// ```
380 #[stable(feature = "rust1", since = "1.0.0")]
381 pub fn of<T: ?Sized + Reflect + 'static>() -> TypeId {
382 TypeId {
383 t: unsafe { intrinsics::type_id::<T>() },
384 }
385 }
386 }