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