]> git.lizzy.rs Git - rust.git/blob - library/core/src/any.rs
Rollup merge of #96768 - m-ou-se:futex-fuchsia, r=tmandry
[rust.git] / library / core / src / any.rs
1 //! This module contains the `Any` trait, which enables dynamic typing
2 //! of any `'static` type through runtime reflection. It also contains the
3 //! `Provider` trait and accompanying API, which enable trait objects to provide
4 //! data based on typed requests, an alternate form of runtime reflection.
5 //!
6 //! # `Any` and `TypeId`
7 //!
8 //! `Any` itself can be used to get a `TypeId`, and has more features when used
9 //! as a trait object. As `&dyn Any` (a borrowed trait object), it has the `is`
10 //! and `downcast_ref` methods, to test if the contained value is of a given type,
11 //! and to get a reference to the inner value as a type. As `&mut dyn Any`, there
12 //! is also the `downcast_mut` method, for getting a mutable reference to the
13 //! inner value. `Box<dyn Any>` adds the `downcast` method, which attempts to
14 //! convert to a `Box<T>`. See the [`Box`] documentation for the full details.
15 //!
16 //! Note that `&dyn Any` is limited to testing whether a value is of a specified
17 //! concrete type, and cannot be used to test whether a type implements a trait.
18 //!
19 //! [`Box`]: ../../std/boxed/struct.Box.html
20 //!
21 //! # Smart pointers and `dyn Any`
22 //!
23 //! One piece of behavior to keep in mind when using `Any` as a trait object,
24 //! especially with types like `Box<dyn Any>` or `Arc<dyn Any>`, is that simply
25 //! calling `.type_id()` on the value will produce the `TypeId` of the
26 //! *container*, not the underlying trait object. This can be avoided by
27 //! converting the smart pointer into a `&dyn Any` instead, which will return
28 //! the object's `TypeId`. For example:
29 //!
30 //! ```
31 //! use std::any::{Any, TypeId};
32 //!
33 //! let boxed: Box<dyn Any> = Box::new(3_i32);
34 //!
35 //! // You're more likely to want this:
36 //! let actual_id = (&*boxed).type_id();
37 //! // ... than this:
38 //! let boxed_id = boxed.type_id();
39 //!
40 //! assert_eq!(actual_id, TypeId::of::<i32>());
41 //! assert_eq!(boxed_id, TypeId::of::<Box<dyn Any>>());
42 //! ```
43 //!
44 //! ## Examples
45 //!
46 //! Consider a situation where we want to log out a value passed to a function.
47 //! We know the value we're working on implements Debug, but we don't know its
48 //! concrete type. We want to give special treatment to certain types: in this
49 //! case printing out the length of String values prior to their value.
50 //! We don't know the concrete type of our value at compile time, so we need to
51 //! use runtime reflection instead.
52 //!
53 //! ```rust
54 //! use std::fmt::Debug;
55 //! use std::any::Any;
56 //!
57 //! // Logger function for any type that implements Debug.
58 //! fn log<T: Any + Debug>(value: &T) {
59 //!     let value_any = value as &dyn Any;
60 //!
61 //!     // Try to convert our value to a `String`. If successful, we want to
62 //!     // output the String`'s length as well as its value. If not, it's a
63 //!     // different type: just print it out unadorned.
64 //!     match value_any.downcast_ref::<String>() {
65 //!         Some(as_string) => {
66 //!             println!("String ({}): {}", as_string.len(), as_string);
67 //!         }
68 //!         None => {
69 //!             println!("{value:?}");
70 //!         }
71 //!     }
72 //! }
73 //!
74 //! // This function wants to log its parameter out prior to doing work with it.
75 //! fn do_work<T: Any + Debug>(value: &T) {
76 //!     log(value);
77 //!     // ...do some other work
78 //! }
79 //!
80 //! fn main() {
81 //!     let my_string = "Hello World".to_string();
82 //!     do_work(&my_string);
83 //!
84 //!     let my_i8: i8 = 100;
85 //!     do_work(&my_i8);
86 //! }
87 //! ```
88 //!
89 //! # `Provider` and `Demand`
90 //!
91 //! `Provider` and the associated APIs support generic, type-driven access to data, and a mechanism
92 //! for implementers to provide such data. The key parts of the interface are the `Provider`
93 //! trait for objects which can provide data, and the [`request_value`] and [`request_ref`]
94 //! functions for requesting data from an object which implements `Provider`. Generally, end users
95 //! should not call `request_*` directly, they are helper functions for intermediate implementers
96 //! to use to implement a user-facing interface. This is purely for the sake of ergonomics, there is
97 //! no safety concern here; intermediate implementers can typically support methods rather than
98 //! free functions and use more specific names.
99 //!
100 //! Typically, a data provider is a trait object of a trait which extends `Provider`. A user will
101 //! request data from a trait object by specifying the type of the data.
102 //!
103 //! ## Data flow
104 //!
105 //! * A user requests an object of a specific type, which is delegated to `request_value` or
106 //!   `request_ref`
107 //! * `request_*` creates a `Demand` object and passes it to `Provider::provide`
108 //! * The data provider's implementation of `Provider::provide` tries providing values of
109 //!   different types using `Demand::provide_*`. If the type matches the type requested by
110 //!   the user, the value will be stored in the `Demand` object.
111 //! * `request_*` unpacks the `Demand` object and returns any stored value to the user.
112 //!
113 //! ## Examples
114 //!
115 //! ```
116 //! # #![feature(provide_any)]
117 //! use std::any::{Provider, Demand, request_ref};
118 //!
119 //! // Definition of MyTrait, a data provider.
120 //! trait MyTrait: Provider {
121 //!     // ...
122 //! }
123 //!
124 //! // Methods on `MyTrait` trait objects.
125 //! impl dyn MyTrait + '_ {
126 //!     /// Get a reference to a field of the implementing struct.
127 //!     pub fn get_context_by_ref<T: ?Sized + 'static>(&self) -> Option<&T> {
128 //!         request_ref::<T, _>(self)
129 //!     }
130 //! }
131 //!
132 //! // Downstream implementation of `MyTrait` and `Provider`.
133 //! # struct SomeConcreteType { some_string: String }
134 //! impl MyTrait for SomeConcreteType {
135 //!     // ...
136 //! }
137 //!
138 //! impl Provider for SomeConcreteType {
139 //!     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
140 //!         // Provide a string reference. We could provide multiple values with
141 //!         // different types here.
142 //!         demand.provide_ref::<String>(&self.some_string);
143 //!     }
144 //! }
145 //!
146 //! // Downstream usage of `MyTrait`.
147 //! fn use_my_trait(obj: &dyn MyTrait) {
148 //!     // Request a &String from obj.
149 //!     let _ = obj.get_context_by_ref::<String>().unwrap();
150 //! }
151 //! ```
152 //!
153 //! In this example, if the concrete type of `obj` in `use_my_trait` is `SomeConcreteType`, then
154 //! the `get_context_ref` call will return a reference to `obj.some_string` with type `&String`.
155
156 #![stable(feature = "rust1", since = "1.0.0")]
157
158 use crate::fmt;
159 use crate::intrinsics;
160
161 ///////////////////////////////////////////////////////////////////////////////
162 // Any trait
163 ///////////////////////////////////////////////////////////////////////////////
164
165 /// A trait to emulate dynamic typing.
166 ///
167 /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
168 /// See the [module-level documentation][mod] for more details.
169 ///
170 /// [mod]: crate::any
171 // This trait is not unsafe, though we rely on the specifics of it's sole impl's
172 // `type_id` function in unsafe code (e.g., `downcast`). Normally, that would be
173 // a problem, but because the only impl of `Any` is a blanket implementation, no
174 // other code can implement `Any`.
175 //
176 // We could plausibly make this trait unsafe -- it would not cause breakage,
177 // since we control all the implementations -- but we choose not to as that's
178 // both not really necessary and may confuse users about the distinction of
179 // unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call,
180 // but we would likely want to indicate as such in documentation).
181 #[stable(feature = "rust1", since = "1.0.0")]
182 #[cfg_attr(not(test), rustc_diagnostic_item = "Any")]
183 pub trait Any: 'static {
184     /// Gets the `TypeId` of `self`.
185     ///
186     /// # Examples
187     ///
188     /// ```
189     /// use std::any::{Any, TypeId};
190     ///
191     /// fn is_string(s: &dyn Any) -> bool {
192     ///     TypeId::of::<String>() == s.type_id()
193     /// }
194     ///
195     /// assert_eq!(is_string(&0), false);
196     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
197     /// ```
198     #[stable(feature = "get_type_id", since = "1.34.0")]
199     fn type_id(&self) -> TypeId;
200 }
201
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<T: 'static + ?Sized> Any for T {
204     fn type_id(&self) -> TypeId {
205         TypeId::of::<T>()
206     }
207 }
208
209 ///////////////////////////////////////////////////////////////////////////////
210 // Extension methods for Any trait objects.
211 ///////////////////////////////////////////////////////////////////////////////
212
213 #[stable(feature = "rust1", since = "1.0.0")]
214 impl fmt::Debug for dyn Any {
215     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216         f.debug_struct("Any").finish_non_exhaustive()
217     }
218 }
219
220 // Ensure that the result of e.g., joining a thread can be printed and
221 // hence used with `unwrap`. May eventually no longer be needed if
222 // dispatch works with upcasting.
223 #[stable(feature = "rust1", since = "1.0.0")]
224 impl fmt::Debug for dyn Any + Send {
225     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226         f.debug_struct("Any").finish_non_exhaustive()
227     }
228 }
229
230 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
231 impl fmt::Debug for dyn Any + Send + Sync {
232     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233         f.debug_struct("Any").finish_non_exhaustive()
234     }
235 }
236
237 impl dyn Any {
238     /// Returns `true` if the inner type is the same as `T`.
239     ///
240     /// # Examples
241     ///
242     /// ```
243     /// use std::any::Any;
244     ///
245     /// fn is_string(s: &dyn Any) {
246     ///     if s.is::<String>() {
247     ///         println!("It's a string!");
248     ///     } else {
249     ///         println!("Not a string...");
250     ///     }
251     /// }
252     ///
253     /// is_string(&0);
254     /// is_string(&"cookie monster".to_string());
255     /// ```
256     #[stable(feature = "rust1", since = "1.0.0")]
257     #[inline]
258     pub fn is<T: Any>(&self) -> bool {
259         // Get `TypeId` of the type this function is instantiated with.
260         let t = TypeId::of::<T>();
261
262         // Get `TypeId` of the type in the trait object (`self`).
263         let concrete = self.type_id();
264
265         // Compare both `TypeId`s on equality.
266         t == concrete
267     }
268
269     /// Returns some reference to the inner value if it is of type `T`, or
270     /// `None` if it isn't.
271     ///
272     /// # Examples
273     ///
274     /// ```
275     /// use std::any::Any;
276     ///
277     /// fn print_if_string(s: &dyn Any) {
278     ///     if let Some(string) = s.downcast_ref::<String>() {
279     ///         println!("It's a string({}): '{}'", string.len(), string);
280     ///     } else {
281     ///         println!("Not a string...");
282     ///     }
283     /// }
284     ///
285     /// print_if_string(&0);
286     /// print_if_string(&"cookie monster".to_string());
287     /// ```
288     #[stable(feature = "rust1", since = "1.0.0")]
289     #[inline]
290     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
291         if self.is::<T>() {
292             // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
293             // that check for memory safety because we have implemented Any for all types; no other
294             // impls can exist as they would conflict with our impl.
295             unsafe { Some(self.downcast_ref_unchecked()) }
296         } else {
297             None
298         }
299     }
300
301     /// Returns some mutable reference to the inner value if it is of type `T`, or
302     /// `None` if it isn't.
303     ///
304     /// # Examples
305     ///
306     /// ```
307     /// use std::any::Any;
308     ///
309     /// fn modify_if_u32(s: &mut dyn Any) {
310     ///     if let Some(num) = s.downcast_mut::<u32>() {
311     ///         *num = 42;
312     ///     }
313     /// }
314     ///
315     /// let mut x = 10u32;
316     /// let mut s = "starlord".to_string();
317     ///
318     /// modify_if_u32(&mut x);
319     /// modify_if_u32(&mut s);
320     ///
321     /// assert_eq!(x, 42);
322     /// assert_eq!(&s, "starlord");
323     /// ```
324     #[stable(feature = "rust1", since = "1.0.0")]
325     #[inline]
326     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
327         if self.is::<T>() {
328             // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
329             // that check for memory safety because we have implemented Any for all types; no other
330             // impls can exist as they would conflict with our impl.
331             unsafe { Some(self.downcast_mut_unchecked()) }
332         } else {
333             None
334         }
335     }
336
337     /// Returns a reference to the inner value as type `dyn T`.
338     ///
339     /// # Examples
340     ///
341     /// ```
342     /// #![feature(downcast_unchecked)]
343     ///
344     /// use std::any::Any;
345     ///
346     /// let x: Box<dyn Any> = Box::new(1_usize);
347     ///
348     /// unsafe {
349     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
350     /// }
351     /// ```
352     ///
353     /// # Safety
354     ///
355     /// The contained value must be of type `T`. Calling this method
356     /// with the incorrect type is *undefined behavior*.
357     #[unstable(feature = "downcast_unchecked", issue = "90850")]
358     #[inline]
359     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
360         debug_assert!(self.is::<T>());
361         // SAFETY: caller guarantees that T is the correct type
362         unsafe { &*(self as *const dyn Any as *const T) }
363     }
364
365     /// Returns a mutable reference to the inner value as type `dyn T`.
366     ///
367     /// # Examples
368     ///
369     /// ```
370     /// #![feature(downcast_unchecked)]
371     ///
372     /// use std::any::Any;
373     ///
374     /// let mut x: Box<dyn Any> = Box::new(1_usize);
375     ///
376     /// unsafe {
377     ///     *x.downcast_mut_unchecked::<usize>() += 1;
378     /// }
379     ///
380     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
381     /// ```
382     ///
383     /// # Safety
384     ///
385     /// The contained value must be of type `T`. Calling this method
386     /// with the incorrect type is *undefined behavior*.
387     #[unstable(feature = "downcast_unchecked", issue = "90850")]
388     #[inline]
389     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
390         debug_assert!(self.is::<T>());
391         // SAFETY: caller guarantees that T is the correct type
392         unsafe { &mut *(self as *mut dyn Any as *mut T) }
393     }
394 }
395
396 impl dyn Any + Send {
397     /// Forwards to the method defined on the type `dyn Any`.
398     ///
399     /// # Examples
400     ///
401     /// ```
402     /// use std::any::Any;
403     ///
404     /// fn is_string(s: &(dyn Any + Send)) {
405     ///     if s.is::<String>() {
406     ///         println!("It's a string!");
407     ///     } else {
408     ///         println!("Not a string...");
409     ///     }
410     /// }
411     ///
412     /// is_string(&0);
413     /// is_string(&"cookie monster".to_string());
414     /// ```
415     #[stable(feature = "rust1", since = "1.0.0")]
416     #[inline]
417     pub fn is<T: Any>(&self) -> bool {
418         <dyn Any>::is::<T>(self)
419     }
420
421     /// Forwards to the method defined on the type `dyn Any`.
422     ///
423     /// # Examples
424     ///
425     /// ```
426     /// use std::any::Any;
427     ///
428     /// fn print_if_string(s: &(dyn Any + Send)) {
429     ///     if let Some(string) = s.downcast_ref::<String>() {
430     ///         println!("It's a string({}): '{}'", string.len(), string);
431     ///     } else {
432     ///         println!("Not a string...");
433     ///     }
434     /// }
435     ///
436     /// print_if_string(&0);
437     /// print_if_string(&"cookie monster".to_string());
438     /// ```
439     #[stable(feature = "rust1", since = "1.0.0")]
440     #[inline]
441     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
442         <dyn Any>::downcast_ref::<T>(self)
443     }
444
445     /// Forwards to the method defined on the type `dyn Any`.
446     ///
447     /// # Examples
448     ///
449     /// ```
450     /// use std::any::Any;
451     ///
452     /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
453     ///     if let Some(num) = s.downcast_mut::<u32>() {
454     ///         *num = 42;
455     ///     }
456     /// }
457     ///
458     /// let mut x = 10u32;
459     /// let mut s = "starlord".to_string();
460     ///
461     /// modify_if_u32(&mut x);
462     /// modify_if_u32(&mut s);
463     ///
464     /// assert_eq!(x, 42);
465     /// assert_eq!(&s, "starlord");
466     /// ```
467     #[stable(feature = "rust1", since = "1.0.0")]
468     #[inline]
469     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
470         <dyn Any>::downcast_mut::<T>(self)
471     }
472
473     /// Forwards to the method defined on the type `dyn Any`.
474     ///
475     /// # Examples
476     ///
477     /// ```
478     /// #![feature(downcast_unchecked)]
479     ///
480     /// use std::any::Any;
481     ///
482     /// let x: Box<dyn Any> = Box::new(1_usize);
483     ///
484     /// unsafe {
485     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
486     /// }
487     /// ```
488     ///
489     /// # Safety
490     ///
491     /// Same as the method on the type `dyn Any`.
492     #[unstable(feature = "downcast_unchecked", issue = "90850")]
493     #[inline]
494     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
495         // SAFETY: guaranteed by caller
496         unsafe { <dyn Any>::downcast_ref_unchecked::<T>(self) }
497     }
498
499     /// Forwards to the method defined on the type `dyn Any`.
500     ///
501     /// # Examples
502     ///
503     /// ```
504     /// #![feature(downcast_unchecked)]
505     ///
506     /// use std::any::Any;
507     ///
508     /// let mut x: Box<dyn Any> = Box::new(1_usize);
509     ///
510     /// unsafe {
511     ///     *x.downcast_mut_unchecked::<usize>() += 1;
512     /// }
513     ///
514     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
515     /// ```
516     ///
517     /// # Safety
518     ///
519     /// Same as the method on the type `dyn Any`.
520     #[unstable(feature = "downcast_unchecked", issue = "90850")]
521     #[inline]
522     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
523         // SAFETY: guaranteed by caller
524         unsafe { <dyn Any>::downcast_mut_unchecked::<T>(self) }
525     }
526 }
527
528 impl dyn Any + Send + Sync {
529     /// Forwards to the method defined on the type `Any`.
530     ///
531     /// # Examples
532     ///
533     /// ```
534     /// use std::any::Any;
535     ///
536     /// fn is_string(s: &(dyn Any + Send + Sync)) {
537     ///     if s.is::<String>() {
538     ///         println!("It's a string!");
539     ///     } else {
540     ///         println!("Not a string...");
541     ///     }
542     /// }
543     ///
544     /// is_string(&0);
545     /// is_string(&"cookie monster".to_string());
546     /// ```
547     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
548     #[inline]
549     pub fn is<T: Any>(&self) -> bool {
550         <dyn Any>::is::<T>(self)
551     }
552
553     /// Forwards to the method defined on the type `Any`.
554     ///
555     /// # Examples
556     ///
557     /// ```
558     /// use std::any::Any;
559     ///
560     /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
561     ///     if let Some(string) = s.downcast_ref::<String>() {
562     ///         println!("It's a string({}): '{}'", string.len(), string);
563     ///     } else {
564     ///         println!("Not a string...");
565     ///     }
566     /// }
567     ///
568     /// print_if_string(&0);
569     /// print_if_string(&"cookie monster".to_string());
570     /// ```
571     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
572     #[inline]
573     pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
574         <dyn Any>::downcast_ref::<T>(self)
575     }
576
577     /// Forwards to the method defined on the type `Any`.
578     ///
579     /// # Examples
580     ///
581     /// ```
582     /// use std::any::Any;
583     ///
584     /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
585     ///     if let Some(num) = s.downcast_mut::<u32>() {
586     ///         *num = 42;
587     ///     }
588     /// }
589     ///
590     /// let mut x = 10u32;
591     /// let mut s = "starlord".to_string();
592     ///
593     /// modify_if_u32(&mut x);
594     /// modify_if_u32(&mut s);
595     ///
596     /// assert_eq!(x, 42);
597     /// assert_eq!(&s, "starlord");
598     /// ```
599     #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
600     #[inline]
601     pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
602         <dyn Any>::downcast_mut::<T>(self)
603     }
604
605     /// Forwards to the method defined on the type `Any`.
606     ///
607     /// # Examples
608     ///
609     /// ```
610     /// #![feature(downcast_unchecked)]
611     ///
612     /// use std::any::Any;
613     ///
614     /// let x: Box<dyn Any> = Box::new(1_usize);
615     ///
616     /// unsafe {
617     ///     assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
618     /// }
619     /// ```
620     #[unstable(feature = "downcast_unchecked", issue = "90850")]
621     #[inline]
622     pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
623         // SAFETY: guaranteed by caller
624         unsafe { <dyn Any>::downcast_ref_unchecked::<T>(self) }
625     }
626
627     /// Forwards to the method defined on the type `Any`.
628     ///
629     /// # Examples
630     ///
631     /// ```
632     /// #![feature(downcast_unchecked)]
633     ///
634     /// use std::any::Any;
635     ///
636     /// let mut x: Box<dyn Any> = Box::new(1_usize);
637     ///
638     /// unsafe {
639     ///     *x.downcast_mut_unchecked::<usize>() += 1;
640     /// }
641     ///
642     /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
643     /// ```
644     #[unstable(feature = "downcast_unchecked", issue = "90850")]
645     #[inline]
646     pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
647         // SAFETY: guaranteed by caller
648         unsafe { <dyn Any>::downcast_mut_unchecked::<T>(self) }
649     }
650 }
651
652 ///////////////////////////////////////////////////////////////////////////////
653 // TypeID and its methods
654 ///////////////////////////////////////////////////////////////////////////////
655
656 /// A `TypeId` represents a globally unique identifier for a type.
657 ///
658 /// Each `TypeId` is an opaque object which does not allow inspection of what's
659 /// inside but does allow basic operations such as cloning, comparison,
660 /// printing, and showing.
661 ///
662 /// A `TypeId` is currently only available for types which ascribe to `'static`,
663 /// but this limitation may be removed in the future.
664 ///
665 /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
666 /// noting that the hashes and ordering will vary between Rust releases. Beware
667 /// of relying on them inside of your code!
668 #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub struct TypeId {
671     t: u64,
672 }
673
674 impl TypeId {
675     /// Returns the `TypeId` of the type this generic function has been
676     /// instantiated with.
677     ///
678     /// # Examples
679     ///
680     /// ```
681     /// use std::any::{Any, TypeId};
682     ///
683     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
684     ///     TypeId::of::<String>() == TypeId::of::<T>()
685     /// }
686     ///
687     /// assert_eq!(is_string(&0), false);
688     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
689     /// ```
690     #[must_use]
691     #[stable(feature = "rust1", since = "1.0.0")]
692     #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
693     pub const fn of<T: ?Sized + 'static>() -> TypeId {
694         TypeId { t: intrinsics::type_id::<T>() }
695     }
696 }
697
698 /// Returns the name of a type as a string slice.
699 ///
700 /// # Note
701 ///
702 /// This is intended for diagnostic use. The exact contents and format of the
703 /// string returned are not specified, other than being a best-effort
704 /// description of the type. For example, amongst the strings
705 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
706 /// `"std::option::Option<std::string::String>"`.
707 ///
708 /// The returned string must not be considered to be a unique identifier of a
709 /// type as multiple types may map to the same type name. Similarly, there is no
710 /// guarantee that all parts of a type will appear in the returned string: for
711 /// example, lifetime specifiers are currently not included. In addition, the
712 /// output may change between versions of the compiler.
713 ///
714 /// The current implementation uses the same infrastructure as compiler
715 /// diagnostics and debuginfo, but this is not guaranteed.
716 ///
717 /// # Examples
718 ///
719 /// ```rust
720 /// assert_eq!(
721 ///     std::any::type_name::<Option<String>>(),
722 ///     "core::option::Option<alloc::string::String>",
723 /// );
724 /// ```
725 #[must_use]
726 #[stable(feature = "type_name", since = "1.38.0")]
727 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
728 pub const fn type_name<T: ?Sized>() -> &'static str {
729     intrinsics::type_name::<T>()
730 }
731
732 /// Returns the name of the type of the pointed-to value as a string slice.
733 /// This is the same as `type_name::<T>()`, but can be used where the type of a
734 /// variable is not easily available.
735 ///
736 /// # Note
737 ///
738 /// This is intended for diagnostic use. The exact contents and format of the
739 /// string are not specified, other than being a best-effort description of the
740 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
741 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
742 /// `"foobar"`. In addition, the output may change between versions of the
743 /// compiler.
744 ///
745 /// This function does not resolve trait objects,
746 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
747 /// may return `"dyn Debug"`, but not `"u32"`.
748 ///
749 /// The type name should not be considered a unique identifier of a type;
750 /// multiple types may share the same type name.
751 ///
752 /// The current implementation uses the same infrastructure as compiler
753 /// diagnostics and debuginfo, but this is not guaranteed.
754 ///
755 /// # Examples
756 ///
757 /// Prints the default integer and float types.
758 ///
759 /// ```rust
760 /// #![feature(type_name_of_val)]
761 /// use std::any::type_name_of_val;
762 ///
763 /// let x = 1;
764 /// println!("{}", type_name_of_val(&x));
765 /// let y = 1.0;
766 /// println!("{}", type_name_of_val(&y));
767 /// ```
768 #[must_use]
769 #[unstable(feature = "type_name_of_val", issue = "66359")]
770 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
771 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
772     type_name::<T>()
773 }
774
775 ///////////////////////////////////////////////////////////////////////////////
776 // Provider trait
777 ///////////////////////////////////////////////////////////////////////////////
778
779 /// Trait implemented by a type which can dynamically provide values based on type.
780 #[unstable(feature = "provide_any", issue = "96024")]
781 pub trait Provider {
782     /// Data providers should implement this method to provide *all* values they are able to
783     /// provide by using `demand`.
784     ///
785     /// Note that the `provide_*` methods on `Demand` have short-circuit semantics: if an earlier
786     /// method has successfully provided a value, then later methods will not get an opportunity to
787     /// provide.
788     ///
789     /// # Examples
790     ///
791     /// Provides a reference to a field with type `String` as a `&str`, and a value of
792     /// type `i32`.
793     ///
794     /// ```rust
795     /// # #![feature(provide_any)]
796     /// use std::any::{Provider, Demand};
797     /// # struct SomeConcreteType { field: String, num_field: i32 }
798     ///
799     /// impl Provider for SomeConcreteType {
800     ///     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
801     ///         demand.provide_ref::<str>(&self.field)
802     ///             .provide_value::<i32, _>(|| self.num_field);
803     ///     }
804     /// }
805     /// ```
806     #[unstable(feature = "provide_any", issue = "96024")]
807     fn provide<'a>(&'a self, demand: &mut Demand<'a>);
808 }
809
810 /// Request a value from the `Provider`.
811 ///
812 /// # Examples
813 ///
814 /// Get a string value from a provider.
815 ///
816 /// ```rust
817 /// # #![feature(provide_any)]
818 /// use std::any::{Provider, request_value};
819 ///
820 /// fn get_string<P: Provider>(provider: &P) -> String {
821 ///     request_value::<String, _>(provider).unwrap()
822 /// }
823 /// ```
824 #[unstable(feature = "provide_any", issue = "96024")]
825 pub fn request_value<'a, T, P>(provider: &'a P) -> Option<T>
826 where
827     T: 'static,
828     P: Provider + ?Sized,
829 {
830     request_by_type_tag::<'a, tags::Value<T>, P>(provider)
831 }
832
833 /// Request a reference from the `Provider`.
834 ///
835 /// # Examples
836 ///
837 /// Get a string reference from a provider.
838 ///
839 /// ```rust
840 /// # #![feature(provide_any)]
841 /// use std::any::{Provider, request_ref};
842 ///
843 /// fn get_str<P: Provider>(provider: &P) -> &str {
844 ///     request_ref::<str, _>(provider).unwrap()
845 /// }
846 /// ```
847 #[unstable(feature = "provide_any", issue = "96024")]
848 pub fn request_ref<'a, T, P>(provider: &'a P) -> Option<&'a T>
849 where
850     T: 'static + ?Sized,
851     P: Provider + ?Sized,
852 {
853     request_by_type_tag::<'a, tags::Ref<tags::MaybeSizedValue<T>>, P>(provider)
854 }
855
856 /// Request a specific value by tag from the `Provider`.
857 fn request_by_type_tag<'a, I, P>(provider: &'a P) -> Option<I::Reified>
858 where
859     I: tags::Type<'a>,
860     P: Provider + ?Sized,
861 {
862     let mut tagged = TaggedOption::<'a, I>(None);
863     provider.provide(tagged.as_demand());
864     tagged.0
865 }
866
867 ///////////////////////////////////////////////////////////////////////////////
868 // Demand and its methods
869 ///////////////////////////////////////////////////////////////////////////////
870
871 /// A helper object for providing data by type.
872 ///
873 /// A data provider provides values by calling this type's provide methods.
874 #[unstable(feature = "provide_any", issue = "96024")]
875 #[repr(transparent)]
876 pub struct Demand<'a>(dyn Erased<'a> + 'a);
877
878 impl<'a> Demand<'a> {
879     /// Create a new `&mut Demand` from a `&mut dyn Erased` trait object.
880     fn new<'b>(erased: &'b mut (dyn Erased<'a> + 'a)) -> &'b mut Demand<'a> {
881         // SAFETY: transmuting `&mut (dyn Erased<'a> + 'a)` to `&mut Demand<'a>` is safe since
882         // `Demand` is repr(transparent).
883         unsafe { &mut *(erased as *mut dyn Erased<'a> as *mut Demand<'a>) }
884     }
885
886     /// Provide a value or other type with only static lifetimes.
887     ///
888     /// # Examples
889     ///
890     /// Provides a `String` by cloning.
891     ///
892     /// ```rust
893     /// # #![feature(provide_any)]
894     /// use std::any::{Provider, Demand};
895     /// # struct SomeConcreteType { field: String }
896     ///
897     /// impl Provider for SomeConcreteType {
898     ///     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
899     ///         demand.provide_value::<String, _>(|| self.field.clone());
900     ///     }
901     /// }
902     /// ```
903     #[unstable(feature = "provide_any", issue = "96024")]
904     pub fn provide_value<T, F>(&mut self, fulfil: F) -> &mut Self
905     where
906         T: 'static,
907         F: FnOnce() -> T,
908     {
909         self.provide_with::<tags::Value<T>, F>(fulfil)
910     }
911
912     /// Provide a reference, note that the referee type must be bounded by `'static`,
913     /// but may be unsized.
914     ///
915     /// # Examples
916     ///
917     /// Provides a reference to a field as a `&str`.
918     ///
919     /// ```rust
920     /// # #![feature(provide_any)]
921     /// use std::any::{Provider, Demand};
922     /// # struct SomeConcreteType { field: String }
923     ///
924     /// impl Provider for SomeConcreteType {
925     ///     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
926     ///         demand.provide_ref::<str>(&self.field);
927     ///     }
928     /// }
929     /// ```
930     #[unstable(feature = "provide_any", issue = "96024")]
931     pub fn provide_ref<T: ?Sized + 'static>(&mut self, value: &'a T) -> &mut Self {
932         self.provide::<tags::Ref<tags::MaybeSizedValue<T>>>(value)
933     }
934
935     /// Provide a value with the given `Type` tag.
936     fn provide<I>(&mut self, value: I::Reified) -> &mut Self
937     where
938         I: tags::Type<'a>,
939     {
940         if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
941             res.0 = Some(value);
942         }
943         self
944     }
945
946     /// Provide a value with the given `Type` tag, using a closure to prevent unnecessary work.
947     fn provide_with<I, F>(&mut self, fulfil: F) -> &mut Self
948     where
949         I: tags::Type<'a>,
950         F: FnOnce() -> I::Reified,
951     {
952         if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
953             res.0 = Some(fulfil());
954         }
955         self
956     }
957 }
958
959 #[unstable(feature = "provide_any", issue = "96024")]
960 impl<'a> fmt::Debug for Demand<'a> {
961     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
962         f.debug_struct("Demand").finish_non_exhaustive()
963     }
964 }
965
966 ///////////////////////////////////////////////////////////////////////////////
967 // Type tags
968 ///////////////////////////////////////////////////////////////////////////////
969
970 mod tags {
971     //! Type tags are used to identify a type using a separate value. This module includes type tags
972     //! for some very common types.
973     //!
974     //! Currently type tags are not exposed to the user. But in the future, if you want to use the
975     //! Provider API with more complex types (typically those including lifetime parameters), you
976     //! will need to write your own tags.
977
978     use crate::marker::PhantomData;
979
980     /// This trait is implemented by specific tag types in order to allow
981     /// describing a type which can be requested for a given lifetime `'a`.
982     ///
983     /// A few example implementations for type-driven tags can be found in this
984     /// module, although crates may also implement their own tags for more
985     /// complex types with internal lifetimes.
986     pub trait Type<'a>: Sized + 'static {
987         /// The type of values which may be tagged by this tag for the given
988         /// lifetime.
989         type Reified: 'a;
990     }
991
992     /// Similar to the [`Type`] trait, but represents a type which may be unsized (i.e., has a
993     /// `?Sized` bound). E.g., `str`.
994     pub trait MaybeSizedType<'a>: Sized + 'static {
995         type Reified: 'a + ?Sized;
996     }
997
998     impl<'a, T: Type<'a>> MaybeSizedType<'a> for T {
999         type Reified = T::Reified;
1000     }
1001
1002     /// Type-based tag for types bounded by `'static`, i.e., with no borrowed elements.
1003     #[derive(Debug)]
1004     pub struct Value<T: 'static>(PhantomData<T>);
1005
1006     impl<'a, T: 'static> Type<'a> for Value<T> {
1007         type Reified = T;
1008     }
1009
1010     /// Type-based tag similar to [`Value`] but which may be unsized (i.e., has a `?Sized` bound).
1011     #[derive(Debug)]
1012     pub struct MaybeSizedValue<T: ?Sized + 'static>(PhantomData<T>);
1013
1014     impl<'a, T: ?Sized + 'static> MaybeSizedType<'a> for MaybeSizedValue<T> {
1015         type Reified = T;
1016     }
1017
1018     /// Type-based tag for reference types (`&'a T`, where T is represented by
1019     /// `<I as MaybeSizedType<'a>>::Reified`.
1020     #[derive(Debug)]
1021     pub struct Ref<I>(PhantomData<I>);
1022
1023     impl<'a, I: MaybeSizedType<'a>> Type<'a> for Ref<I> {
1024         type Reified = &'a I::Reified;
1025     }
1026 }
1027
1028 /// An `Option` with a type tag `I`.
1029 ///
1030 /// Since this struct implements `Erased`, the type can be erased to make a dynamically typed
1031 /// option. The type can be checked dynamically using `Erased::tag_id` and since this is statically
1032 /// checked for the concrete type, there is some degree of type safety.
1033 #[repr(transparent)]
1034 struct TaggedOption<'a, I: tags::Type<'a>>(Option<I::Reified>);
1035
1036 impl<'a, I: tags::Type<'a>> TaggedOption<'a, I> {
1037     fn as_demand(&mut self) -> &mut Demand<'a> {
1038         Demand::new(self as &mut (dyn Erased<'a> + 'a))
1039     }
1040 }
1041
1042 /// Represents a type-erased but identifiable object.
1043 ///
1044 /// This trait is exclusively implemented by the `TaggedOption` type.
1045 unsafe trait Erased<'a>: 'a {
1046     /// The `TypeId` of the erased type.
1047     fn tag_id(&self) -> TypeId;
1048 }
1049
1050 unsafe impl<'a, I: tags::Type<'a>> Erased<'a> for TaggedOption<'a, I> {
1051     fn tag_id(&self) -> TypeId {
1052         TypeId::of::<I>()
1053     }
1054 }
1055
1056 #[unstable(feature = "provide_any", issue = "96024")]
1057 impl<'a> dyn Erased<'a> + 'a {
1058     /// Returns some reference to the dynamic value if it is tagged with `I`,
1059     /// or `None` otherwise.
1060     #[inline]
1061     fn downcast_mut<I>(&mut self) -> Option<&mut TaggedOption<'a, I>>
1062     where
1063         I: tags::Type<'a>,
1064     {
1065         if self.tag_id() == TypeId::of::<I>() {
1066             // SAFETY: Just checked whether we're pointing to an I.
1067             Some(unsafe { &mut *(self as *mut Self).cast::<TaggedOption<'a, I>>() })
1068         } else {
1069             None
1070         }
1071     }
1072 }