]> git.lizzy.rs Git - rust.git/blob - src/libcore/any.rs
Rollup merge of #68409 - sinkuu:temp_path, r=Mark-Simulacrum
[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 `&dyn Any` (a borrowed trait object), it has the `is`
6 //! and `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 dyn Any`, there
8 //! is also the `downcast_mut` method, for getting a mutable reference to the
9 //! inner value. `Box<dyn 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 `&dyn 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 crate::fmt;
65 use crate::intrinsics;
66
67 ///////////////////////////////////////////////////////////////////////////////
68 // Any trait
69 ///////////////////////////////////////////////////////////////////////////////
70
71 /// A trait 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 // This trait is not unsafe, though we rely on the specifics of it's sole impl's
78 // `type_id` function in unsafe code (e.g., `downcast`). Normally, that would be
79 // a problem, but because the only impl of `Any` is a blanket implementation, no
80 // other code can implement `Any`.
81 //
82 // We could plausibly make this trait unsafe -- it would not cause breakage,
83 // since we control all the implementations -- but we choose not to as that's
84 // both not really necessary and may confuse users about the distinction of
85 // unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call,
86 // but we would likely want to indicate as such in documentation).
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     /// use std::any::{Any, TypeId};
95     ///
96     /// fn is_string(s: &dyn Any) -> bool {
97     ///     TypeId::of::<String>() == s.type_id()
98     /// }
99     ///
100     /// assert_eq!(is_string(&0), false);
101     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
102     /// ```
103     #[stable(feature = "get_type_id", since = "1.34.0")]
104     fn type_id(&self) -> TypeId;
105 }
106
107 #[stable(feature = "rust1", since = "1.0.0")]
108 impl<T: 'static + ?Sized> Any for T {
109     fn type_id(&self) -> TypeId {
110         TypeId::of::<T>()
111     }
112 }
113
114 ///////////////////////////////////////////////////////////////////////////////
115 // Extension methods for Any trait objects.
116 ///////////////////////////////////////////////////////////////////////////////
117
118 #[stable(feature = "rust1", since = "1.0.0")]
119 impl fmt::Debug for dyn Any {
120     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121         f.pad("Any")
122     }
123 }
124
125 // Ensure that the result of e.g., joining a thread can be printed and
126 // hence used with `unwrap`. May eventually no longer be needed if
127 // dispatch works with upcasting.
128 #[stable(feature = "rust1", since = "1.0.0")]
129 impl fmt::Debug for dyn Any + Send {
130     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131         f.pad("Any")
132     }
133 }
134
135 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
136 impl fmt::Debug for dyn Any + Send + Sync {
137     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138         f.pad("Any")
139     }
140 }
141
142 impl dyn 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: &dyn Any) {
151     ///     if s.is::<String>() {
152     ///         println!("It's a string!");
153     ///     } else {
154     ///         println!("Not a string...");
155     ///     }
156     /// }
157     ///
158     /// is_string(&0);
159     /// is_string(&"cookie monster".to_string());
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 concrete = self.type_id();
169
170         // Compare both `TypeId`s on equality.
171         t == concrete
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: &dyn 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     /// print_if_string(&0);
191     /// print_if_string(&"cookie monster".to_string());
192     /// ```
193     #[stable(feature = "rust1", since = "1.0.0")]
194     #[inline]
195     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
196         if self.is::<T>() {
197             // SAFETY: just checked whether we are pointing to the correct type
198             unsafe { Some(&*(self as *const dyn Any as *const T)) }
199         } else {
200             None
201         }
202     }
203
204     /// Returns some mutable reference to the boxed value if it is of type `T`, or
205     /// `None` if it isn't.
206     ///
207     /// # Examples
208     ///
209     /// ```
210     /// use std::any::Any;
211     ///
212     /// fn modify_if_u32(s: &mut dyn Any) {
213     ///     if let Some(num) = s.downcast_mut::<u32>() {
214     ///         *num = 42;
215     ///     }
216     /// }
217     ///
218     /// let mut x = 10u32;
219     /// let mut s = "starlord".to_string();
220     ///
221     /// modify_if_u32(&mut x);
222     /// modify_if_u32(&mut s);
223     ///
224     /// assert_eq!(x, 42);
225     /// assert_eq!(&s, "starlord");
226     /// ```
227     #[stable(feature = "rust1", since = "1.0.0")]
228     #[inline]
229     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
230         if self.is::<T>() {
231             // SAFETY: just checked whether we are pointing to the correct type
232             unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) }
233         } else {
234             None
235         }
236     }
237 }
238
239 impl dyn Any + Send {
240     /// Forwards to the method defined on the type `Any`.
241     ///
242     /// # Examples
243     ///
244     /// ```
245     /// use std::any::Any;
246     ///
247     /// fn is_string(s: &(dyn Any + Send)) {
248     ///     if s.is::<String>() {
249     ///         println!("It's a string!");
250     ///     } else {
251     ///         println!("Not a string...");
252     ///     }
253     /// }
254     ///
255     /// is_string(&0);
256     /// is_string(&"cookie monster".to_string());
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     /// print_if_string(&0);
280     /// print_if_string(&"cookie monster".to_string());
281     /// ```
282     #[stable(feature = "rust1", since = "1.0.0")]
283     #[inline]
284     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
285         Any::downcast_ref::<T>(self)
286     }
287
288     /// Forwards to the method defined on the type `Any`.
289     ///
290     /// # Examples
291     ///
292     /// ```
293     /// use std::any::Any;
294     ///
295     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
296     ///     if let Some(num) = s.downcast_mut::<u32>() {
297     ///         *num = 42;
298     ///     }
299     /// }
300     ///
301     /// let mut x = 10u32;
302     /// let mut s = "starlord".to_string();
303     ///
304     /// modify_if_u32(&mut x);
305     /// modify_if_u32(&mut s);
306     ///
307     /// assert_eq!(x, 42);
308     /// assert_eq!(&s, "starlord");
309     /// ```
310     #[stable(feature = "rust1", since = "1.0.0")]
311     #[inline]
312     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
313         Any::downcast_mut::<T>(self)
314     }
315 }
316
317 impl dyn Any + Send + Sync {
318     /// Forwards to the method defined on the type `Any`.
319     ///
320     /// # Examples
321     ///
322     /// ```
323     /// use std::any::Any;
324     ///
325     /// fn is_string(s: &(dyn Any + Send + Sync)) {
326     ///     if s.is::<String>() {
327     ///         println!("It's a string!");
328     ///     } else {
329     ///         println!("Not a string...");
330     ///     }
331     /// }
332     ///
333     /// is_string(&0);
334     /// is_string(&"cookie monster".to_string());
335     /// ```
336     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
337     #[inline]
338     pub fn is<T: Any>(&self) -> bool {
339         Any::is::<T>(self)
340     }
341
342     /// Forwards to the method defined on the type `Any`.
343     ///
344     /// # Examples
345     ///
346     /// ```
347     /// use std::any::Any;
348     ///
349     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
350     ///     if let Some(string) = s.downcast_ref::<String>() {
351     ///         println!("It's a string({}): '{}'", string.len(), string);
352     ///     } else {
353     ///         println!("Not a string...");
354     ///     }
355     /// }
356     ///
357     /// print_if_string(&0);
358     /// print_if_string(&"cookie monster".to_string());
359     /// ```
360     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
361     #[inline]
362     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
363         Any::downcast_ref::<T>(self)
364     }
365
366     /// Forwards to the method defined on the type `Any`.
367     ///
368     /// # Examples
369     ///
370     /// ```
371     /// use std::any::Any;
372     ///
373     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
374     ///     if let Some(num) = s.downcast_mut::<u32>() {
375     ///         *num = 42;
376     ///     }
377     /// }
378     ///
379     /// let mut x = 10u32;
380     /// let mut s = "starlord".to_string();
381     ///
382     /// modify_if_u32(&mut x);
383     /// modify_if_u32(&mut s);
384     ///
385     /// assert_eq!(x, 42);
386     /// assert_eq!(&s, "starlord");
387     /// ```
388     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
389     #[inline]
390     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
391         Any::downcast_mut::<T>(self)
392     }
393 }
394
395 ///////////////////////////////////////////////////////////////////////////////
396 // TypeID and its methods
397 ///////////////////////////////////////////////////////////////////////////////
398
399 /// A `TypeId` represents a globally unique identifier for a type.
400 ///
401 /// Each `TypeId` is an opaque object which does not allow inspection of what's
402 /// inside but does allow basic operations such as cloning, comparison,
403 /// printing, and showing.
404 ///
405 /// A `TypeId` is currently only available for types which ascribe to `'static`,
406 /// but this limitation may be removed in the future.
407 ///
408 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
409 /// noting that the hashes and ordering will vary between Rust releases. Beware
410 /// of relying on them inside of your code!
411 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
412 #[stable(feature = "rust1", since = "1.0.0")]
413 pub struct TypeId {
414     t: u64,
415 }
416
417 impl TypeId {
418     /// Returns the `TypeId` of the type this generic function has been
419     /// instantiated with.
420     ///
421     /// # Examples
422     ///
423     /// ```
424     /// use std::any::{Any, TypeId};
425     ///
426     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
427     ///     TypeId::of::<String>() == TypeId::of::<T>()
428     /// }
429     ///
430     /// assert_eq!(is_string(&0), false);
431     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
432     /// ```
433     #[stable(feature = "rust1", since = "1.0.0")]
434     #[rustc_const_unstable(feature = "const_type_id", issue = "41875")]
435     pub const fn of<T: ?Sized + 'static>() -> TypeId {
436         TypeId { t: intrinsics::type_id::<T>() }
437     }
438 }
439
440 /// Returns the name of a type as a string slice.
441 ///
442 /// # Note
443 ///
444 /// This is intended for diagnostic use. The exact contents and format of the
445 /// string are not specified, other than being a best-effort description of the
446 /// type. For example, `type_name::<Option<String>>()` could return the
447 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
448 /// `"foobar"`. In addition, the output may change between versions of the
449 /// compiler.
450 ///
451 /// The type name should not be considered a unique identifier of a type;
452 /// multiple types may share the same type name.
453 ///
454 /// The current implementation uses the same infrastructure as compiler
455 /// diagnostics and debuginfo, but this is not guaranteed.
456 ///
457 /// # Examples
458 ///
459 /// ```rust
460 /// assert_eq!(
461 ///     std::any::type_name::<Option<String>>(),
462 ///     "core::option::Option<alloc::string::String>",
463 /// );
464 /// ```
465 #[stable(feature = "type_name", since = "1.38.0")]
466 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
467 pub const fn type_name<T: ?Sized>() -> &'static str {
468     intrinsics::type_name::<T>()
469 }
470
471 /// Returns the name of the type of the pointed-to value as a string slice.
472 /// This is the same as `type_name::<T>()`, but can be used where the type of a
473 /// variable is not easily available.
474 ///
475 /// # Note
476 ///
477 /// This is intended for diagnostic use. The exact contents and format of the
478 /// string are not specified, other than being a best-effort description of the
479 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
480 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
481 /// `"foobar"`. In addition, the output may change between versions of the
482 /// compiler.
483 ///
484 /// This function does not resolve trait objects,
485 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
486 /// may return `"dyn Debug"`, but not `"u32"`.
487 ///
488 /// The type name should not be considered a unique identifier of a type;
489 /// multiple types may share the same type name.
490 ///
491 /// The current implementation uses the same infrastructure as compiler
492 /// diagnostics and debuginfo, but this is not guaranteed.
493 ///
494 /// # Examples
495 ///
496 /// Prints the default integer and float types.
497 ///
498 /// ```rust
499 /// #![feature(type_name_of_val)]
500 /// use std::any::type_name_of_val;
501 ///
502 /// let x = 1;
503 /// println!("{}", type_name_of_val(&x));
504 /// let y = 1.0;
505 /// println!("{}", type_name_of_val(&y));
506 /// ```
507 #[unstable(feature = "type_name_of_val", issue = "66359")]
508 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
509 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
510     type_name::<T>()
511 }