]> git.lizzy.rs Git - rust.git/blob - src/libcore/any.rs
Rollup merge of #58595 - stjepang:make-duration-consts-associated, r=oli-obk
[rust.git] / src / libcore / any.rs
1 //! This module implements the `Any` trait, which enables dynamic typing
2 //! of any `'static` type through runtime reflection.
3 //!
4 //! `Any` itself can be used to get a `TypeId`, and has more features when used
5 //! as a trait object. As `&Any` (a borrowed trait object), it has the `is` and
6 //! `downcast_ref` methods, to test if the contained value is of a given type,
7 //! and to get a reference to the inner value as a type. As `&mut Any`, there
8 //! is also the `downcast_mut` method, for getting a mutable reference to the
9 //! inner value. `Box<Any>` adds the `downcast` method, which attempts to
10 //! convert to a `Box<T>`. See the [`Box`] documentation for the full details.
11 //!
12 //! Note that &Any is limited to testing whether a value is of a specified
13 //! concrete type, and cannot be used to test whether a type implements a trait.
14 //!
15 //! [`Box`]: ../../std/boxed/struct.Box.html
16 //!
17 //! # Examples
18 //!
19 //! Consider a situation where we want to log out a value passed to a function.
20 //! We know the value we're working on implements Debug, but we don't know its
21 //! concrete type. We want to give special treatment to certain types: in this
22 //! case printing out the length of String values prior to their value.
23 //! We don't know the concrete type of our value at compile time, so we need to
24 //! use runtime reflection instead.
25 //!
26 //! ```rust
27 //! use std::fmt::Debug;
28 //! use std::any::Any;
29 //!
30 //! // Logger function for any type that implements Debug.
31 //! fn log<T: Any + Debug>(value: &T) {
32 //!     let value_any = value as &dyn Any;
33 //!
34 //!     // Try to convert our value to a `String`. If successful, we want to
35 //!     // output the String`'s length as well as its value. If not, it's a
36 //!     // different type: just print it out unadorned.
37 //!     match value_any.downcast_ref::<String>() {
38 //!         Some(as_string) => {
39 //!             println!("String ({}): {}", as_string.len(), as_string);
40 //!         }
41 //!         None => {
42 //!             println!("{:?}", value);
43 //!         }
44 //!     }
45 //! }
46 //!
47 //! // This function wants to log its parameter out prior to doing work with it.
48 //! fn do_work<T: Any + Debug>(value: &T) {
49 //!     log(value);
50 //!     // ...do some other work
51 //! }
52 //!
53 //! fn main() {
54 //!     let my_string = "Hello World".to_string();
55 //!     do_work(&my_string);
56 //!
57 //!     let my_i8: i8 = 100;
58 //!     do_work(&my_i8);
59 //! }
60 //! ```
61
62 #![stable(feature = "rust1", since = "1.0.0")]
63
64 use fmt;
65 use intrinsics;
66
67 ///////////////////////////////////////////////////////////////////////////////
68 // Any trait
69 ///////////////////////////////////////////////////////////////////////////////
70
71 /// A type to emulate dynamic typing.
72 ///
73 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
74 /// See the [module-level documentation][mod] for more details.
75 ///
76 /// [mod]: index.html
77 #[stable(feature = "rust1", since = "1.0.0")]
78 pub trait Any: 'static {
79     /// Gets the `TypeId` of `self`.
80     ///
81     /// # Examples
82     ///
83     /// ```
84     /// use std::any::{Any, TypeId};
85     ///
86     /// fn is_string(s: &dyn Any) -> bool {
87     ///     TypeId::of::<String>() == s.type_id()
88     /// }
89     ///
90     /// fn main() {
91     ///     assert_eq!(is_string(&0), false);
92     ///     assert_eq!(is_string(&"cookie monster".to_string()), true);
93     /// }
94     /// ```
95     #[stable(feature = "get_type_id", since = "1.34.0")]
96     fn type_id(&self) -> TypeId;
97 }
98
99 #[stable(feature = "rust1", since = "1.0.0")]
100 impl<T: 'static + ?Sized > Any for T {
101     fn type_id(&self) -> TypeId { TypeId::of::<T>() }
102 }
103
104 ///////////////////////////////////////////////////////////////////////////////
105 // Extension methods for Any trait objects.
106 ///////////////////////////////////////////////////////////////////////////////
107
108 #[stable(feature = "rust1", since = "1.0.0")]
109 impl fmt::Debug for dyn Any {
110     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
111         f.pad("Any")
112     }
113 }
114
115 // Ensure that the result of e.g., joining a thread can be printed and
116 // hence used with `unwrap`. May eventually no longer be needed if
117 // dispatch works with upcasting.
118 #[stable(feature = "rust1", since = "1.0.0")]
119 impl fmt::Debug for dyn Any + Send {
120     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
121         f.pad("Any")
122     }
123 }
124
125 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
126 impl fmt::Debug for dyn Any + Send + Sync {
127     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
128         f.pad("Any")
129     }
130 }
131
132 impl dyn Any {
133     /// Returns `true` if the boxed type is the same as `T`.
134     ///
135     /// # Examples
136     ///
137     /// ```
138     /// use std::any::Any;
139     ///
140     /// fn is_string(s: &dyn Any) {
141     ///     if s.is::<String>() {
142     ///         println!("It's a string!");
143     ///     } else {
144     ///         println!("Not a string...");
145     ///     }
146     /// }
147     ///
148     /// fn main() {
149     ///     is_string(&0);
150     ///     is_string(&"cookie monster".to_string());
151     /// }
152     /// ```
153     #[stable(feature = "rust1", since = "1.0.0")]
154     #[inline]
155     pub fn is<T: Any>(&self) -> bool {
156         // Get TypeId of the type this function is instantiated with
157         let t = TypeId::of::<T>();
158
159         // Get TypeId of the type in the trait object
160         let concrete = self.type_id();
161
162         // Compare both TypeIds on equality
163         t == concrete
164     }
165
166     /// Returns some reference to the boxed value if it is of type `T`, or
167     /// `None` if it isn't.
168     ///
169     /// # Examples
170     ///
171     /// ```
172     /// use std::any::Any;
173     ///
174     /// fn print_if_string(s: &dyn Any) {
175     ///     if let Some(string) = s.downcast_ref::<String>() {
176     ///         println!("It's a string({}): '{}'", string.len(), string);
177     ///     } else {
178     ///         println!("Not a string...");
179     ///     }
180     /// }
181     ///
182     /// fn main() {
183     ///     print_if_string(&0);
184     ///     print_if_string(&"cookie monster".to_string());
185     /// }
186     /// ```
187     #[stable(feature = "rust1", since = "1.0.0")]
188     #[inline]
189     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
190         if self.is::<T>() {
191             unsafe {
192                 Some(&*(self as *const dyn Any as *const T))
193             }
194         } else {
195             None
196         }
197     }
198
199     /// Returns some mutable reference to the boxed value if it is of type `T`, or
200     /// `None` if it isn't.
201     ///
202     /// # Examples
203     ///
204     /// ```
205     /// use std::any::Any;
206     ///
207     /// fn modify_if_u32(s: &mut dyn Any) {
208     ///     if let Some(num) = s.downcast_mut::<u32>() {
209     ///         *num = 42;
210     ///     }
211     /// }
212     ///
213     /// fn main() {
214     ///     let mut x = 10u32;
215     ///     let mut s = "starlord".to_string();
216     ///
217     ///     modify_if_u32(&mut x);
218     ///     modify_if_u32(&mut s);
219     ///
220     ///     assert_eq!(x, 42);
221     ///     assert_eq!(&s, "starlord");
222     /// }
223     /// ```
224     #[stable(feature = "rust1", since = "1.0.0")]
225     #[inline]
226     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
227         if self.is::<T>() {
228             unsafe {
229                 Some(&mut *(self as *mut dyn Any as *mut T))
230             }
231         } else {
232             None
233         }
234     }
235 }
236
237 impl dyn Any+Send {
238     /// Forwards to the method defined on the type `Any`.
239     ///
240     /// # Examples
241     ///
242     /// ```
243     /// use std::any::Any;
244     ///
245     /// fn is_string(s: &(dyn Any + Send)) {
246     ///     if s.is::<String>() {
247     ///         println!("It's a string!");
248     ///     } else {
249     ///         println!("Not a string...");
250     ///     }
251     /// }
252     ///
253     /// fn main() {
254     ///     is_string(&0);
255     ///     is_string(&"cookie monster".to_string());
256     /// }
257     /// ```
258     #[stable(feature = "rust1", since = "1.0.0")]
259     #[inline]
260     pub fn is<T: Any>(&self) -> bool {
261         Any::is::<T>(self)
262     }
263
264     /// Forwards to the method defined on the type `Any`.
265     ///
266     /// # Examples
267     ///
268     /// ```
269     /// use std::any::Any;
270     ///
271     /// fn print_if_string(s: &(dyn Any + Send)) {
272     ///     if let Some(string) = s.downcast_ref::<String>() {
273     ///         println!("It's a string({}): '{}'", string.len(), string);
274     ///     } else {
275     ///         println!("Not a string...");
276     ///     }
277     /// }
278     ///
279     /// fn main() {
280     ///     print_if_string(&0);
281     ///     print_if_string(&"cookie monster".to_string());
282     /// }
283     /// ```
284     #[stable(feature = "rust1", since = "1.0.0")]
285     #[inline]
286     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
287         Any::downcast_ref::<T>(self)
288     }
289
290     /// Forwards to the method defined on the type `Any`.
291     ///
292     /// # Examples
293     ///
294     /// ```
295     /// use std::any::Any;
296     ///
297     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
298     ///     if let Some(num) = s.downcast_mut::<u32>() {
299     ///         *num = 42;
300     ///     }
301     /// }
302     ///
303     /// fn main() {
304     ///     let mut x = 10u32;
305     ///     let mut s = "starlord".to_string();
306     ///
307     ///     modify_if_u32(&mut x);
308     ///     modify_if_u32(&mut s);
309     ///
310     ///     assert_eq!(x, 42);
311     ///     assert_eq!(&s, "starlord");
312     /// }
313     /// ```
314     #[stable(feature = "rust1", since = "1.0.0")]
315     #[inline]
316     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
317         Any::downcast_mut::<T>(self)
318     }
319 }
320
321 impl dyn Any+Send+Sync {
322     /// Forwards to the method defined on the type `Any`.
323     ///
324     /// # Examples
325     ///
326     /// ```
327     /// use std::any::Any;
328     ///
329     /// fn is_string(s: &(dyn Any + Send + Sync)) {
330     ///     if s.is::<String>() {
331     ///         println!("It's a string!");
332     ///     } else {
333     ///         println!("Not a string...");
334     ///     }
335     /// }
336     ///
337     /// fn main() {
338     ///     is_string(&0);
339     ///     is_string(&"cookie monster".to_string());
340     /// }
341     /// ```
342     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
343     #[inline]
344     pub fn is<T: Any>(&self) -> bool {
345         Any::is::<T>(self)
346     }
347
348     /// Forwards to the method defined on the type `Any`.
349     ///
350     /// # Examples
351     ///
352     /// ```
353     /// use std::any::Any;
354     ///
355     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
356     ///     if let Some(string) = s.downcast_ref::<String>() {
357     ///         println!("It's a string({}): '{}'", string.len(), string);
358     ///     } else {
359     ///         println!("Not a string...");
360     ///     }
361     /// }
362     ///
363     /// fn main() {
364     ///     print_if_string(&0);
365     ///     print_if_string(&"cookie monster".to_string());
366     /// }
367     /// ```
368     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
369     #[inline]
370     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
371         Any::downcast_ref::<T>(self)
372     }
373
374     /// Forwards to the method defined on the type `Any`.
375     ///
376     /// # Examples
377     ///
378     /// ```
379     /// use std::any::Any;
380     ///
381     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
382     ///     if let Some(num) = s.downcast_mut::<u32>() {
383     ///         *num = 42;
384     ///     }
385     /// }
386     ///
387     /// fn main() {
388     ///     let mut x = 10u32;
389     ///     let mut s = "starlord".to_string();
390     ///
391     ///     modify_if_u32(&mut x);
392     ///     modify_if_u32(&mut s);
393     ///
394     ///     assert_eq!(x, 42);
395     ///     assert_eq!(&s, "starlord");
396     /// }
397     /// ```
398     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
399     #[inline]
400     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
401         Any::downcast_mut::<T>(self)
402     }
403 }
404
405 ///////////////////////////////////////////////////////////////////////////////
406 // TypeID and its methods
407 ///////////////////////////////////////////////////////////////////////////////
408
409 /// A `TypeId` represents a globally unique identifier for a type.
410 ///
411 /// Each `TypeId` is an opaque object which does not allow inspection of what's
412 /// inside but does allow basic operations such as cloning, comparison,
413 /// printing, and showing.
414 ///
415 /// A `TypeId` is currently only available for types which ascribe to `'static`,
416 /// but this limitation may be removed in the future.
417 ///
418 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
419 /// noting that the hashes and ordering will vary between Rust releases. Beware
420 /// of relying on them inside of your code!
421 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub struct TypeId {
424     t: u64,
425 }
426
427 impl TypeId {
428     /// Returns the `TypeId` of the type this generic function has been
429     /// instantiated with.
430     ///
431     /// # Examples
432     ///
433     /// ```
434     /// use std::any::{Any, TypeId};
435     ///
436     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
437     ///     TypeId::of::<String>() == TypeId::of::<T>()
438     /// }
439     ///
440     /// fn main() {
441     ///     assert_eq!(is_string(&0), false);
442     ///     assert_eq!(is_string(&"cookie monster".to_string()), true);
443     /// }
444     /// ```
445     #[stable(feature = "rust1", since = "1.0.0")]
446     #[rustc_const_unstable(feature="const_type_id")]
447     pub const fn of<T: ?Sized + 'static>() -> TypeId {
448         TypeId {
449             t: unsafe { intrinsics::type_id::<T>() },
450         }
451     }
452 }