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