]> git.proxmox.com Git - rustc.git/blob - src/libcore/any.rs
New upstream version 1.28.0~beta.14+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 intrinsics;
76
77 ///////////////////////////////////////////////////////////////////////////////
78 // Any trait
79 ///////////////////////////////////////////////////////////////////////////////
80
81 /// A type to emulate dynamic typing.
82 ///
83 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
84 /// See the [module-level documentation][mod] for more details.
85 ///
86 /// [mod]: index.html
87 #[stable(feature = "rust1", since = "1.0.0")]
88 pub trait Any: 'static {
89 /// Gets the `TypeId` of `self`.
90 ///
91 /// # Examples
92 ///
93 /// ```
94 /// #![feature(get_type_id)]
95 ///
96 /// use std::any::{Any, TypeId};
97 ///
98 /// fn is_string(s: &Any) -> bool {
99 /// TypeId::of::<String>() == s.get_type_id()
100 /// }
101 ///
102 /// fn main() {
103 /// assert_eq!(is_string(&0), false);
104 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
105 /// }
106 /// ```
107 #[unstable(feature = "get_type_id",
108 reason = "this method will likely be replaced by an associated static",
109 issue = "27745")]
110 fn get_type_id(&self) -> TypeId;
111 }
112
113 #[stable(feature = "rust1", since = "1.0.0")]
114 impl<T: 'static + ?Sized > Any for T {
115 fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
116 }
117
118 ///////////////////////////////////////////////////////////////////////////////
119 // Extension methods for Any trait objects.
120 ///////////////////////////////////////////////////////////////////////////////
121
122 #[stable(feature = "rust1", since = "1.0.0")]
123 impl fmt::Debug for Any {
124 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
125 f.pad("Any")
126 }
127 }
128
129 // Ensure that the result of e.g. joining a thread can be printed and
130 // hence used with `unwrap`. May eventually no longer be needed if
131 // dispatch works with upcasting.
132 #[stable(feature = "rust1", since = "1.0.0")]
133 impl fmt::Debug for Any + Send {
134 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
135 f.pad("Any")
136 }
137 }
138
139 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
140 impl fmt::Debug for Any + Send + Sync {
141 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
142 f.pad("Any")
143 }
144 }
145
146 impl Any {
147 /// Returns `true` if the boxed type is the same as `T`.
148 ///
149 /// # Examples
150 ///
151 /// ```
152 /// use std::any::Any;
153 ///
154 /// fn is_string(s: &Any) {
155 /// if s.is::<String>() {
156 /// println!("It's a string!");
157 /// } else {
158 /// println!("Not a string...");
159 /// }
160 /// }
161 ///
162 /// fn main() {
163 /// is_string(&0);
164 /// is_string(&"cookie monster".to_string());
165 /// }
166 /// ```
167 #[stable(feature = "rust1", since = "1.0.0")]
168 #[inline]
169 pub fn is<T: Any>(&self) -> bool {
170 // Get TypeId of the type this function is instantiated with
171 let t = TypeId::of::<T>();
172
173 // Get TypeId of the type in the trait object
174 let boxed = self.get_type_id();
175
176 // Compare both TypeIds on equality
177 t == boxed
178 }
179
180 /// Returns some reference to the boxed value if it is of type `T`, or
181 /// `None` if it isn't.
182 ///
183 /// # Examples
184 ///
185 /// ```
186 /// use std::any::Any;
187 ///
188 /// fn print_if_string(s: &Any) {
189 /// if let Some(string) = s.downcast_ref::<String>() {
190 /// println!("It's a string({}): '{}'", string.len(), string);
191 /// } else {
192 /// println!("Not a string...");
193 /// }
194 /// }
195 ///
196 /// fn main() {
197 /// print_if_string(&0);
198 /// print_if_string(&"cookie monster".to_string());
199 /// }
200 /// ```
201 #[stable(feature = "rust1", since = "1.0.0")]
202 #[inline]
203 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
204 if self.is::<T>() {
205 unsafe {
206 Some(&*(self as *const Any as *const T))
207 }
208 } else {
209 None
210 }
211 }
212
213 /// Returns some mutable reference to the boxed value if it is of type `T`, or
214 /// `None` if it isn't.
215 ///
216 /// # Examples
217 ///
218 /// ```
219 /// use std::any::Any;
220 ///
221 /// fn modify_if_u32(s: &mut Any) {
222 /// if let Some(num) = s.downcast_mut::<u32>() {
223 /// *num = 42;
224 /// }
225 /// }
226 ///
227 /// fn main() {
228 /// let mut x = 10u32;
229 /// let mut s = "starlord".to_string();
230 ///
231 /// modify_if_u32(&mut x);
232 /// modify_if_u32(&mut s);
233 ///
234 /// assert_eq!(x, 42);
235 /// assert_eq!(&s, "starlord");
236 /// }
237 /// ```
238 #[stable(feature = "rust1", since = "1.0.0")]
239 #[inline]
240 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
241 if self.is::<T>() {
242 unsafe {
243 Some(&mut *(self as *mut Any as *mut T))
244 }
245 } else {
246 None
247 }
248 }
249 }
250
251 impl Any+Send {
252 /// Forwards to the method defined on the type `Any`.
253 ///
254 /// # Examples
255 ///
256 /// ```
257 /// use std::any::Any;
258 ///
259 /// fn is_string(s: &(Any + Send)) {
260 /// if s.is::<String>() {
261 /// println!("It's a string!");
262 /// } else {
263 /// println!("Not a string...");
264 /// }
265 /// }
266 ///
267 /// fn main() {
268 /// is_string(&0);
269 /// is_string(&"cookie monster".to_string());
270 /// }
271 /// ```
272 #[stable(feature = "rust1", since = "1.0.0")]
273 #[inline]
274 pub fn is<T: Any>(&self) -> bool {
275 Any::is::<T>(self)
276 }
277
278 /// Forwards to the method defined on the type `Any`.
279 ///
280 /// # Examples
281 ///
282 /// ```
283 /// use std::any::Any;
284 ///
285 /// fn print_if_string(s: &(Any + Send)) {
286 /// if let Some(string) = s.downcast_ref::<String>() {
287 /// println!("It's a string({}): '{}'", string.len(), string);
288 /// } else {
289 /// println!("Not a string...");
290 /// }
291 /// }
292 ///
293 /// fn main() {
294 /// print_if_string(&0);
295 /// print_if_string(&"cookie monster".to_string());
296 /// }
297 /// ```
298 #[stable(feature = "rust1", since = "1.0.0")]
299 #[inline]
300 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
301 Any::downcast_ref::<T>(self)
302 }
303
304 /// Forwards to the method defined on the type `Any`.
305 ///
306 /// # Examples
307 ///
308 /// ```
309 /// use std::any::Any;
310 ///
311 /// fn modify_if_u32(s: &mut (Any + Send)) {
312 /// if let Some(num) = s.downcast_mut::<u32>() {
313 /// *num = 42;
314 /// }
315 /// }
316 ///
317 /// fn main() {
318 /// let mut x = 10u32;
319 /// let mut s = "starlord".to_string();
320 ///
321 /// modify_if_u32(&mut x);
322 /// modify_if_u32(&mut s);
323 ///
324 /// assert_eq!(x, 42);
325 /// assert_eq!(&s, "starlord");
326 /// }
327 /// ```
328 #[stable(feature = "rust1", since = "1.0.0")]
329 #[inline]
330 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
331 Any::downcast_mut::<T>(self)
332 }
333 }
334
335 impl Any+Send+Sync {
336 /// Forwards to the method defined on the type `Any`.
337 ///
338 /// # Examples
339 ///
340 /// ```
341 /// use std::any::Any;
342 ///
343 /// fn is_string(s: &(Any + Send + Sync)) {
344 /// if s.is::<String>() {
345 /// println!("It's a string!");
346 /// } else {
347 /// println!("Not a string...");
348 /// }
349 /// }
350 ///
351 /// fn main() {
352 /// is_string(&0);
353 /// is_string(&"cookie monster".to_string());
354 /// }
355 /// ```
356 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
357 #[inline]
358 pub fn is<T: Any>(&self) -> bool {
359 Any::is::<T>(self)
360 }
361
362 /// Forwards to the method defined on the type `Any`.
363 ///
364 /// # Examples
365 ///
366 /// ```
367 /// use std::any::Any;
368 ///
369 /// fn print_if_string(s: &(Any + Send + Sync)) {
370 /// if let Some(string) = s.downcast_ref::<String>() {
371 /// println!("It's a string({}): '{}'", string.len(), string);
372 /// } else {
373 /// println!("Not a string...");
374 /// }
375 /// }
376 ///
377 /// fn main() {
378 /// print_if_string(&0);
379 /// print_if_string(&"cookie monster".to_string());
380 /// }
381 /// ```
382 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
383 #[inline]
384 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
385 Any::downcast_ref::<T>(self)
386 }
387
388 /// Forwards to the method defined on the type `Any`.
389 ///
390 /// # Examples
391 ///
392 /// ```
393 /// use std::any::Any;
394 ///
395 /// fn modify_if_u32(s: &mut (Any + Send + Sync)) {
396 /// if let Some(num) = s.downcast_mut::<u32>() {
397 /// *num = 42;
398 /// }
399 /// }
400 ///
401 /// fn main() {
402 /// let mut x = 10u32;
403 /// let mut s = "starlord".to_string();
404 ///
405 /// modify_if_u32(&mut x);
406 /// modify_if_u32(&mut s);
407 ///
408 /// assert_eq!(x, 42);
409 /// assert_eq!(&s, "starlord");
410 /// }
411 /// ```
412 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
413 #[inline]
414 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
415 Any::downcast_mut::<T>(self)
416 }
417 }
418
419 ///////////////////////////////////////////////////////////////////////////////
420 // TypeID and its methods
421 ///////////////////////////////////////////////////////////////////////////////
422
423 /// A `TypeId` represents a globally unique identifier for a type.
424 ///
425 /// Each `TypeId` is an opaque object which does not allow inspection of what's
426 /// inside but does allow basic operations such as cloning, comparison,
427 /// printing, and showing.
428 ///
429 /// A `TypeId` is currently only available for types which ascribe to `'static`,
430 /// but this limitation may be removed in the future.
431 ///
432 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
433 /// noting that the hashes and ordering will vary between Rust releases. Beware
434 /// of relying on them outside of your code!
435 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub struct TypeId {
438 t: u64,
439 }
440
441 impl TypeId {
442 /// Returns the `TypeId` of the type this generic function has been
443 /// instantiated with.
444 ///
445 /// # Examples
446 ///
447 /// ```
448 /// use std::any::{Any, TypeId};
449 ///
450 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
451 /// TypeId::of::<String>() == TypeId::of::<T>()
452 /// }
453 ///
454 /// fn main() {
455 /// assert_eq!(is_string(&0), false);
456 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
457 /// }
458 /// ```
459 #[stable(feature = "rust1", since = "1.0.0")]
460 #[rustc_const_unstable(feature="const_type_id")]
461 pub const fn of<T: ?Sized + 'static>() -> TypeId {
462 TypeId {
463 t: unsafe { intrinsics::type_id::<T>() },
464 }
465 }
466 }