]> git.lizzy.rs Git - rust.git/blob - src/libcore/any.rs
Rollup merge of #35863 - matthew-piziak:shl-example, r=steveklabnik
[rust.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 use marker::Reflect;
77
78 ///////////////////////////////////////////////////////////////////////////////
79 // Any trait
80 ///////////////////////////////////////////////////////////////////////////////
81
82 /// A type to emulate dynamic typing.
83 ///
84 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
85 /// See the [module-level documentation][mod] for more details.
86 ///
87 /// [mod]: index.html
88 #[stable(feature = "rust1", since = "1.0.0")]
89 pub trait Any: Reflect + 'static {
90     /// Gets the `TypeId` of `self`.
91     ///
92     /// # Examples
93     ///
94     /// ```
95     /// #![feature(get_type_id)]
96     ///
97     /// use std::any::{Any, TypeId};
98     ///
99     /// fn is_string(s: &Any) -> bool {
100     ///     TypeId::of::<String>() == s.get_type_id()
101     /// }
102     ///
103     /// fn main() {
104     ///     assert_eq!(is_string(&0), false);
105     ///     assert_eq!(is_string(&"cookie monster".to_owned()), true);
106     /// }
107     /// ```
108     #[unstable(feature = "get_type_id",
109                reason = "this method will likely be replaced by an associated static",
110                issue = "27745")]
111     fn get_type_id(&self) -> TypeId;
112 }
113
114 #[stable(feature = "rust1", since = "1.0.0")]
115 impl<T: Reflect + 'static + ?Sized > Any for T {
116     fn get_type_id(&self) -> TypeId { TypeId::of::<T>() }
117 }
118
119 ///////////////////////////////////////////////////////////////////////////////
120 // Extension methods for Any trait objects.
121 ///////////////////////////////////////////////////////////////////////////////
122
123 #[stable(feature = "rust1", since = "1.0.0")]
124 impl fmt::Debug for Any {
125     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
126         f.pad("Any")
127     }
128 }
129
130 // Ensure that the result of e.g. joining a thread can be printed and
131 // hence used with `unwrap`. May eventually no longer be needed if
132 // dispatch works with upcasting.
133 #[stable(feature = "rust1", since = "1.0.0")]
134 impl fmt::Debug for Any + Send {
135     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
136         f.pad("Any")
137     }
138 }
139
140 impl Any {
141     /// Returns true if the boxed type is the same as `T`.
142     ///
143     /// # Examples
144     ///
145     /// ```
146     /// use std::any::Any;
147     ///
148     /// fn is_string(s: &Any) {
149     ///     if s.is::<String>() {
150     ///         println!("It's a string!");
151     ///     } else {
152     ///         println!("Not a string...");
153     ///     }
154     /// }
155     ///
156     /// fn main() {
157     ///     is_string(&0);
158     ///     is_string(&"cookie monster".to_owned());
159     /// }
160     /// ```
161     #[stable(feature = "rust1", since = "1.0.0")]
162     #[inline]
163     pub fn is<T: Any>(&self) -> bool {
164         // Get TypeId of the type this function is instantiated with
165         let t = TypeId::of::<T>();
166
167         // Get TypeId of the type in the trait object
168         let boxed = self.get_type_id();
169
170         // Compare both TypeIds on equality
171         t == boxed
172     }
173
174     /// Returns some reference to the boxed value if it is of type `T`, or
175     /// `None` if it isn't.
176     ///
177     /// # Examples
178     ///
179     /// ```
180     /// use std::any::Any;
181     ///
182     /// fn print_if_string(s: &Any) {
183     ///     if let Some(string) = s.downcast_ref::<String>() {
184     ///         println!("It's a string({}): '{}'", string.len(), string);
185     ///     } else {
186     ///         println!("Not a string...");
187     ///     }
188     /// }
189     ///
190     /// fn main() {
191     ///     print_if_string(&0);
192     ///     print_if_string(&"cookie monster".to_owned());
193     /// }
194     /// ```
195     #[stable(feature = "rust1", since = "1.0.0")]
196     #[inline]
197     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
198         if self.is::<T>() {
199             unsafe {
200                 Some(&*(self as *const Any as *const T))
201             }
202         } else {
203             None
204         }
205     }
206
207     /// Returns some mutable reference to the boxed value if it is of type `T`, or
208     /// `None` if it isn't.
209     ///
210     /// # Examples
211     ///
212     /// ```
213     /// use std::any::Any;
214     ///
215     /// fn modify_if_u32(s: &mut Any) {
216     ///     if let Some(num) = s.downcast_mut::<u32>() {
217     ///         *num = 42;
218     ///     }
219     /// }
220     ///
221     /// fn main() {
222     ///     let mut x = 10u32;
223     ///     let mut s = "starlord".to_owned();
224     ///
225     ///     modify_if_u32(&mut x);
226     ///     modify_if_u32(&mut s);
227     ///
228     ///     assert_eq!(x, 42);
229     ///     assert_eq!(&s, "starlord");
230     /// }
231     /// ```
232     #[stable(feature = "rust1", since = "1.0.0")]
233     #[inline]
234     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
235         if self.is::<T>() {
236             unsafe {
237                 Some(&mut *(self as *mut Any as *mut T))
238             }
239         } else {
240             None
241         }
242     }
243 }
244
245 impl Any+Send {
246     /// Forwards to the method defined on the type `Any`.
247     ///
248     /// # Examples
249     ///
250     /// ```
251     /// use std::any::Any;
252     ///
253     /// fn is_string(s: &(Any + Send)) {
254     ///     if s.is::<String>() {
255     ///         println!("It's a string!");
256     ///     } else {
257     ///         println!("Not a string...");
258     ///     }
259     /// }
260     ///
261     /// fn main() {
262     ///     is_string(&0);
263     ///     is_string(&"cookie monster".to_owned());
264     /// }
265     /// ```
266     #[stable(feature = "rust1", since = "1.0.0")]
267     #[inline]
268     pub fn is<T: Any>(&self) -> bool {
269         Any::is::<T>(self)
270     }
271
272     /// Forwards to the method defined on the type `Any`.
273     ///
274     /// # Examples
275     ///
276     /// ```
277     /// use std::any::Any;
278     ///
279     /// fn print_if_string(s: &(Any + Send)) {
280     ///     if let Some(string) = s.downcast_ref::<String>() {
281     ///         println!("It's a string({}): '{}'", string.len(), string);
282     ///     } else {
283     ///         println!("Not a string...");
284     ///     }
285     /// }
286     ///
287     /// fn main() {
288     ///     print_if_string(&0);
289     ///     print_if_string(&"cookie monster".to_owned());
290     /// }
291     /// ```
292     #[stable(feature = "rust1", since = "1.0.0")]
293     #[inline]
294     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
295         Any::downcast_ref::<T>(self)
296     }
297
298     /// Forwards to the method defined on the type `Any`.
299     ///
300     /// # Examples
301     ///
302     /// ```
303     /// use std::any::Any;
304     ///
305     /// fn modify_if_u32(s: &mut (Any+ Send)) {
306     ///     if let Some(num) = s.downcast_mut::<u32>() {
307     ///         *num = 42;
308     ///     }
309     /// }
310     ///
311     /// fn main() {
312     ///     let mut x = 10u32;
313     ///     let mut s = "starlord".to_owned();
314     ///
315     ///     modify_if_u32(&mut x);
316     ///     modify_if_u32(&mut s);
317     ///
318     ///     assert_eq!(x, 42);
319     ///     assert_eq!(&s, "starlord");
320     /// }
321     /// ```
322     #[stable(feature = "rust1", since = "1.0.0")]
323     #[inline]
324     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
325         Any::downcast_mut::<T>(self)
326     }
327 }
328
329
330 ///////////////////////////////////////////////////////////////////////////////
331 // TypeID and its methods
332 ///////////////////////////////////////////////////////////////////////////////
333
334 /// A `TypeId` represents a globally unique identifier for a type.
335 ///
336 /// Each `TypeId` is an opaque object which does not allow inspection of what's
337 /// inside but does allow basic operations such as cloning, comparison,
338 /// printing, and showing.
339 ///
340 /// A `TypeId` is currently only available for types which ascribe to `'static`,
341 /// but this limitation may be removed in the future.
342 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
343 #[stable(feature = "rust1", since = "1.0.0")]
344 pub struct TypeId {
345     t: u64,
346 }
347
348 impl TypeId {
349     /// Returns the `TypeId` of the type this generic function has been
350     /// instantiated with.
351     ///
352     /// # Examples
353     ///
354     /// ```
355     /// #![feature(get_type_id)]
356     ///
357     /// use std::any::{Any, TypeId};
358     ///
359     /// fn is_string(s: &Any) -> bool {
360     ///     TypeId::of::<String>() == s.get_type_id()
361     /// }
362     ///
363     /// fn main() {
364     ///     assert_eq!(is_string(&0), false);
365     ///     assert_eq!(is_string(&"cookie monster".to_owned()), true);
366     /// }
367     /// ```
368     #[stable(feature = "rust1", since = "1.0.0")]
369     pub fn of<T: ?Sized + Reflect + 'static>() -> TypeId {
370         TypeId {
371             t: unsafe { intrinsics::type_id::<T>() },
372         }
373     }
374 }