]> git.lizzy.rs Git - rust.git/blob - src/libcore/any.rs
Rollup merge of #69569 - matthiaskrgr:nonminimal_bool, 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, and we can rely on
198             // that check for memory safety because we have implemented Any for all types; no other
199             // impls can exist as they would conflict with our impl.
200             unsafe { Some(&*(self as *const dyn Any as *const T)) }
201         } else {
202             None
203         }
204     }
205
206     /// Returns some mutable reference to the boxed value if it is of type `T`, or
207     /// `None` if it isn't.
208     ///
209     /// # Examples
210     ///
211     /// ```
212     /// use std::any::Any;
213     ///
214     /// fn modify_if_u32(s: &mut dyn Any) {
215     ///     if let Some(num) = s.downcast_mut::<u32>() {
216     ///         *num = 42;
217     ///     }
218     /// }
219     ///
220     /// let mut x = 10u32;
221     /// let mut s = "starlord".to_string();
222     ///
223     /// modify_if_u32(&mut x);
224     /// modify_if_u32(&mut s);
225     ///
226     /// assert_eq!(x, 42);
227     /// assert_eq!(&s, "starlord");
228     /// ```
229     #[stable(feature = "rust1", since = "1.0.0")]
230     #[inline]
231     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
232         if self.is::<T>() {
233             // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
234             // that check for memory safety because we have implemented Any for all types; no other
235             // impls can exist as they would conflict with our impl.
236             unsafe { Some(&mut *(self as *mut dyn Any as *mut T)) }
237         } else {
238             None
239         }
240     }
241 }
242
243 impl dyn Any + Send {
244     /// Forwards to the method defined on the type `Any`.
245     ///
246     /// # Examples
247     ///
248     /// ```
249     /// use std::any::Any;
250     ///
251     /// fn is_string(s: &(dyn Any + Send)) {
252     ///     if s.is::<String>() {
253     ///         println!("It's a string!");
254     ///     } else {
255     ///         println!("Not a string...");
256     ///     }
257     /// }
258     ///
259     /// is_string(&0);
260     /// is_string(&"cookie monster".to_string());
261     /// ```
262     #[stable(feature = "rust1", since = "1.0.0")]
263     #[inline]
264     pub fn is<T: Any>(&self) -> bool {
265         Any::is::<T>(self)
266     }
267
268     /// Forwards to the method defined on the type `Any`.
269     ///
270     /// # Examples
271     ///
272     /// ```
273     /// use std::any::Any;
274     ///
275     /// fn print_if_string(s: &(dyn Any + Send)) {
276     ///     if let Some(string) = s.downcast_ref::<String>() {
277     ///         println!("It's a string({}): '{}'", string.len(), string);
278     ///     } else {
279     ///         println!("Not a string...");
280     ///     }
281     /// }
282     ///
283     /// print_if_string(&0);
284     /// print_if_string(&"cookie monster".to_string());
285     /// ```
286     #[stable(feature = "rust1", since = "1.0.0")]
287     #[inline]
288     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
289         Any::downcast_ref::<T>(self)
290     }
291
292     /// Forwards to the method defined on the type `Any`.
293     ///
294     /// # Examples
295     ///
296     /// ```
297     /// use std::any::Any;
298     ///
299     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
300     ///     if let Some(num) = s.downcast_mut::<u32>() {
301     ///         *num = 42;
302     ///     }
303     /// }
304     ///
305     /// let mut x = 10u32;
306     /// let mut s = "starlord".to_string();
307     ///
308     /// modify_if_u32(&mut x);
309     /// modify_if_u32(&mut s);
310     ///
311     /// assert_eq!(x, 42);
312     /// assert_eq!(&s, "starlord");
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     /// is_string(&0);
338     /// is_string(&"cookie monster".to_string());
339     /// ```
340     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
341     #[inline]
342     pub fn is<T: Any>(&self) -> bool {
343         Any::is::<T>(self)
344     }
345
346     /// Forwards to the method defined on the type `Any`.
347     ///
348     /// # Examples
349     ///
350     /// ```
351     /// use std::any::Any;
352     ///
353     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
354     ///     if let Some(string) = s.downcast_ref::<String>() {
355     ///         println!("It's a string({}): '{}'", string.len(), string);
356     ///     } else {
357     ///         println!("Not a string...");
358     ///     }
359     /// }
360     ///
361     /// print_if_string(&0);
362     /// print_if_string(&"cookie monster".to_string());
363     /// ```
364     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
365     #[inline]
366     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
367         Any::downcast_ref::<T>(self)
368     }
369
370     /// Forwards to the method defined on the type `Any`.
371     ///
372     /// # Examples
373     ///
374     /// ```
375     /// use std::any::Any;
376     ///
377     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
378     ///     if let Some(num) = s.downcast_mut::<u32>() {
379     ///         *num = 42;
380     ///     }
381     /// }
382     ///
383     /// let mut x = 10u32;
384     /// let mut s = "starlord".to_string();
385     ///
386     /// modify_if_u32(&mut x);
387     /// modify_if_u32(&mut s);
388     ///
389     /// assert_eq!(x, 42);
390     /// assert_eq!(&s, "starlord");
391     /// ```
392     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
393     #[inline]
394     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
395         Any::downcast_mut::<T>(self)
396     }
397 }
398
399 ///////////////////////////////////////////////////////////////////////////////
400 // TypeID and its methods
401 ///////////////////////////////////////////////////////////////////////////////
402
403 /// A `TypeId` represents a globally unique identifier for a type.
404 ///
405 /// Each `TypeId` is an opaque object which does not allow inspection of what's
406 /// inside but does allow basic operations such as cloning, comparison,
407 /// printing, and showing.
408 ///
409 /// A `TypeId` is currently only available for types which ascribe to `'static`,
410 /// but this limitation may be removed in the future.
411 ///
412 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
413 /// noting that the hashes and ordering will vary between Rust releases. Beware
414 /// of relying on them inside of your code!
415 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
416 #[stable(feature = "rust1", since = "1.0.0")]
417 pub struct TypeId {
418     t: u64,
419 }
420
421 impl TypeId {
422     /// Returns the `TypeId` of the type this generic function has been
423     /// instantiated with.
424     ///
425     /// # Examples
426     ///
427     /// ```
428     /// use std::any::{Any, TypeId};
429     ///
430     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
431     ///     TypeId::of::<String>() == TypeId::of::<T>()
432     /// }
433     ///
434     /// assert_eq!(is_string(&0), false);
435     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
436     /// ```
437     #[stable(feature = "rust1", since = "1.0.0")]
438     #[rustc_const_unstable(feature = "const_type_id", issue = "41875")]
439     pub const fn of<T: ?Sized + 'static>() -> TypeId {
440         TypeId { t: intrinsics::type_id::<T>() }
441     }
442 }
443
444 /// Returns the name of a type as a string slice.
445 ///
446 /// # Note
447 ///
448 /// This is intended for diagnostic use. The exact contents and format of the
449 /// string are not specified, other than being a best-effort description of the
450 /// type. For example, `type_name::<Option<String>>()` could return the
451 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
452 /// `"foobar"`. In addition, the output may change between versions of the
453 /// compiler.
454 ///
455 /// The type name should not be considered a unique identifier of a type;
456 /// multiple types may share the same type name.
457 ///
458 /// The current implementation uses the same infrastructure as compiler
459 /// diagnostics and debuginfo, but this is not guaranteed.
460 ///
461 /// # Examples
462 ///
463 /// ```rust
464 /// assert_eq!(
465 ///     std::any::type_name::<Option<String>>(),
466 ///     "core::option::Option<alloc::string::String>",
467 /// );
468 /// ```
469 #[stable(feature = "type_name", since = "1.38.0")]
470 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
471 pub const fn type_name<T: ?Sized>() -> &'static str {
472     intrinsics::type_name::<T>()
473 }
474
475 /// Returns the name of the type of the pointed-to value as a string slice.
476 /// This is the same as `type_name::<T>()`, but can be used where the type of a
477 /// variable is not easily available.
478 ///
479 /// # Note
480 ///
481 /// This is intended for diagnostic use. The exact contents and format of the
482 /// string are not specified, other than being a best-effort description of the
483 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
484 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
485 /// `"foobar"`. In addition, the output may change between versions of the
486 /// compiler.
487 ///
488 /// This function does not resolve trait objects,
489 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
490 /// may return `"dyn Debug"`, but not `"u32"`.
491 ///
492 /// The type name should not be considered a unique identifier of a type;
493 /// multiple types may share the same type name.
494 ///
495 /// The current implementation uses the same infrastructure as compiler
496 /// diagnostics and debuginfo, but this is not guaranteed.
497 ///
498 /// # Examples
499 ///
500 /// Prints the default integer and float types.
501 ///
502 /// ```rust
503 /// #![feature(type_name_of_val)]
504 /// use std::any::type_name_of_val;
505 ///
506 /// let x = 1;
507 /// println!("{}", type_name_of_val(&x));
508 /// let y = 1.0;
509 /// println!("{}", type_name_of_val(&y));
510 /// ```
511 #[unstable(feature = "type_name_of_val", issue = "66359")]
512 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
513 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
514     type_name::<T>()
515 }