]> git.lizzy.rs Git - rust.git/blob - library/core/src/any.rs
Rollup merge of #101285 - TaKO8Ki:do-not-suggest-adding-move-when-closure-is-already...
[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_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, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
666 #[stable(feature = "rust1", since = "1.0.0")]
667 pub struct TypeId {
668     t: u64,
669 }
670
671 impl TypeId {
672     /// Returns the `TypeId` of the type this generic function has been
673     /// instantiated with.
674     ///
675     /// # Examples
676     ///
677     /// ```
678     /// use std::any::{Any, TypeId};
679     ///
680     /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
681     ///     TypeId::of::<String>() == TypeId::of::<T>()
682     /// }
683     ///
684     /// assert_eq!(is_string(&0), false);
685     /// assert_eq!(is_string(&"cookie monster".to_string()), true);
686     /// ```
687     #[must_use]
688     #[stable(feature = "rust1", since = "1.0.0")]
689     #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
690     pub const fn of<T: ?Sized + 'static>() -> TypeId {
691         TypeId { t: intrinsics::type_id::<T>() }
692     }
693 }
694
695 /// Returns the name of a type as a string slice.
696 ///
697 /// # Note
698 ///
699 /// This is intended for diagnostic use. The exact contents and format of the
700 /// string returned are not specified, other than being a best-effort
701 /// description of the type. For example, amongst the strings
702 /// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
703 /// `"std::option::Option<std::string::String>"`.
704 ///
705 /// The returned string must not be considered to be a unique identifier of a
706 /// type as multiple types may map to the same type name. Similarly, there is no
707 /// guarantee that all parts of a type will appear in the returned string: for
708 /// example, lifetime specifiers are currently not included. In addition, the
709 /// output may change between versions of the compiler.
710 ///
711 /// The current implementation uses the same infrastructure as compiler
712 /// diagnostics and debuginfo, but this is not guaranteed.
713 ///
714 /// # Examples
715 ///
716 /// ```rust
717 /// assert_eq!(
718 ///     std::any::type_name::<Option<String>>(),
719 ///     "core::option::Option<alloc::string::String>",
720 /// );
721 /// ```
722 #[must_use]
723 #[stable(feature = "type_name", since = "1.38.0")]
724 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
725 pub const fn type_name<T: ?Sized>() -> &'static str {
726     intrinsics::type_name::<T>()
727 }
728
729 /// Returns the name of the type of the pointed-to value as a string slice.
730 /// This is the same as `type_name::<T>()`, but can be used where the type of a
731 /// variable is not easily available.
732 ///
733 /// # Note
734 ///
735 /// This is intended for diagnostic use. The exact contents and format of the
736 /// string are not specified, other than being a best-effort description of the
737 /// type. For example, `type_name_of_val::<Option<String>>(None)` could return
738 /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
739 /// `"foobar"`. In addition, the output may change between versions of the
740 /// compiler.
741 ///
742 /// This function does not resolve trait objects,
743 /// meaning that `type_name_of_val(&7u32 as &dyn Debug)`
744 /// may return `"dyn Debug"`, but not `"u32"`.
745 ///
746 /// The type name should not be considered a unique identifier of a type;
747 /// multiple types may share the same type name.
748 ///
749 /// The current implementation uses the same infrastructure as compiler
750 /// diagnostics and debuginfo, but this is not guaranteed.
751 ///
752 /// # Examples
753 ///
754 /// Prints the default integer and float types.
755 ///
756 /// ```rust
757 /// #![feature(type_name_of_val)]
758 /// use std::any::type_name_of_val;
759 ///
760 /// let x = 1;
761 /// println!("{}", type_name_of_val(&x));
762 /// let y = 1.0;
763 /// println!("{}", type_name_of_val(&y));
764 /// ```
765 #[must_use]
766 #[unstable(feature = "type_name_of_val", issue = "66359")]
767 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
768 pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
769     type_name::<T>()
770 }
771
772 ///////////////////////////////////////////////////////////////////////////////
773 // Provider trait
774 ///////////////////////////////////////////////////////////////////////////////
775
776 /// Trait implemented by a type which can dynamically provide values based on type.
777 #[unstable(feature = "provide_any", issue = "96024")]
778 pub trait Provider {
779     /// Data providers should implement this method to provide *all* values they are able to
780     /// provide by using `demand`.
781     ///
782     /// Note that the `provide_*` methods on `Demand` have short-circuit semantics: if an earlier
783     /// method has successfully provided a value, then later methods will not get an opportunity to
784     /// provide.
785     ///
786     /// # Examples
787     ///
788     /// Provides a reference to a field with type `String` as a `&str`, and a value of
789     /// type `i32`.
790     ///
791     /// ```rust
792     /// # #![feature(provide_any)]
793     /// use std::any::{Provider, Demand};
794     /// # struct SomeConcreteType { field: String, num_field: i32 }
795     ///
796     /// impl Provider for SomeConcreteType {
797     ///     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
798     ///         demand.provide_ref::<str>(&self.field)
799     ///             .provide_value::<i32>(|| self.num_field);
800     ///     }
801     /// }
802     /// ```
803     #[unstable(feature = "provide_any", issue = "96024")]
804     fn provide<'a>(&'a self, demand: &mut Demand<'a>);
805 }
806
807 /// Request a value from the `Provider`.
808 ///
809 /// # Examples
810 ///
811 /// Get a string value from a provider.
812 ///
813 /// ```rust
814 /// # #![feature(provide_any)]
815 /// use std::any::{Provider, request_value};
816 ///
817 /// fn get_string(provider: &impl Provider) -> String {
818 ///     request_value::<String>(provider).unwrap()
819 /// }
820 /// ```
821 #[unstable(feature = "provide_any", issue = "96024")]
822 pub fn request_value<'a, T>(provider: &'a (impl Provider + ?Sized)) -> Option<T>
823 where
824     T: 'static,
825 {
826     request_by_type_tag::<'a, tags::Value<T>>(provider)
827 }
828
829 /// Request a reference from the `Provider`.
830 ///
831 /// # Examples
832 ///
833 /// Get a string reference from a provider.
834 ///
835 /// ```rust
836 /// # #![feature(provide_any)]
837 /// use std::any::{Provider, request_ref};
838 ///
839 /// fn get_str(provider: &impl Provider) -> &str {
840 ///     request_ref::<str>(provider).unwrap()
841 /// }
842 /// ```
843 #[unstable(feature = "provide_any", issue = "96024")]
844 pub fn request_ref<'a, T>(provider: &'a (impl Provider + ?Sized)) -> Option<&'a T>
845 where
846     T: 'static + ?Sized,
847 {
848     request_by_type_tag::<'a, tags::Ref<tags::MaybeSizedValue<T>>>(provider)
849 }
850
851 /// Request a specific value by tag from the `Provider`.
852 fn request_by_type_tag<'a, I>(provider: &'a (impl Provider + ?Sized)) -> Option<I::Reified>
853 where
854     I: tags::Type<'a>,
855 {
856     let mut tagged = TaggedOption::<'a, I>(None);
857     provider.provide(tagged.as_demand());
858     tagged.0
859 }
860
861 ///////////////////////////////////////////////////////////////////////////////
862 // Demand and its methods
863 ///////////////////////////////////////////////////////////////////////////////
864
865 /// A helper object for providing data by type.
866 ///
867 /// A data provider provides values by calling this type's provide methods.
868 #[unstable(feature = "provide_any", issue = "96024")]
869 #[repr(transparent)]
870 pub struct Demand<'a>(dyn Erased<'a> + 'a);
871
872 impl<'a> Demand<'a> {
873     /// Create a new `&mut Demand` from a `&mut dyn Erased` trait object.
874     fn new<'b>(erased: &'b mut (dyn Erased<'a> + 'a)) -> &'b mut Demand<'a> {
875         // SAFETY: transmuting `&mut (dyn Erased<'a> + 'a)` to `&mut Demand<'a>` is safe since
876         // `Demand` is repr(transparent).
877         unsafe { &mut *(erased as *mut dyn Erased<'a> as *mut Demand<'a>) }
878     }
879
880     /// Provide a value or other type with only static lifetimes.
881     ///
882     /// # Examples
883     ///
884     /// Provides a `String` by cloning.
885     ///
886     /// ```rust
887     /// # #![feature(provide_any)]
888     /// use std::any::{Provider, Demand};
889     /// # struct SomeConcreteType { field: String }
890     ///
891     /// impl Provider for SomeConcreteType {
892     ///     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
893     ///         demand.provide_value::<String>(|| self.field.clone());
894     ///     }
895     /// }
896     /// ```
897     #[unstable(feature = "provide_any", issue = "96024")]
898     pub fn provide_value<T>(&mut self, fulfil: impl FnOnce() -> T) -> &mut Self
899     where
900         T: 'static,
901     {
902         self.provide_with::<tags::Value<T>>(fulfil)
903     }
904
905     /// Provide a reference, note that the referee type must be bounded by `'static`,
906     /// but may be unsized.
907     ///
908     /// # Examples
909     ///
910     /// Provides a reference to a field as a `&str`.
911     ///
912     /// ```rust
913     /// # #![feature(provide_any)]
914     /// use std::any::{Provider, Demand};
915     /// # struct SomeConcreteType { field: String }
916     ///
917     /// impl Provider for SomeConcreteType {
918     ///     fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
919     ///         demand.provide_ref::<str>(&self.field);
920     ///     }
921     /// }
922     /// ```
923     #[unstable(feature = "provide_any", issue = "96024")]
924     pub fn provide_ref<T: ?Sized + 'static>(&mut self, value: &'a T) -> &mut Self {
925         self.provide::<tags::Ref<tags::MaybeSizedValue<T>>>(value)
926     }
927
928     /// Provide a value with the given `Type` tag.
929     fn provide<I>(&mut self, value: I::Reified) -> &mut Self
930     where
931         I: tags::Type<'a>,
932     {
933         if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
934             res.0 = Some(value);
935         }
936         self
937     }
938
939     /// Provide a value with the given `Type` tag, using a closure to prevent unnecessary work.
940     fn provide_with<I>(&mut self, fulfil: impl FnOnce() -> I::Reified) -> &mut Self
941     where
942         I: tags::Type<'a>,
943     {
944         if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
945             res.0 = Some(fulfil());
946         }
947         self
948     }
949 }
950
951 #[unstable(feature = "provide_any", issue = "96024")]
952 impl<'a> fmt::Debug for Demand<'a> {
953     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
954         f.debug_struct("Demand").finish_non_exhaustive()
955     }
956 }
957
958 ///////////////////////////////////////////////////////////////////////////////
959 // Type tags
960 ///////////////////////////////////////////////////////////////////////////////
961
962 mod tags {
963     //! Type tags are used to identify a type using a separate value. This module includes type tags
964     //! for some very common types.
965     //!
966     //! Currently type tags are not exposed to the user. But in the future, if you want to use the
967     //! Provider API with more complex types (typically those including lifetime parameters), you
968     //! will need to write your own tags.
969
970     use crate::marker::PhantomData;
971
972     /// This trait is implemented by specific tag types in order to allow
973     /// describing a type which can be requested for a given lifetime `'a`.
974     ///
975     /// A few example implementations for type-driven tags can be found in this
976     /// module, although crates may also implement their own tags for more
977     /// complex types with internal lifetimes.
978     pub trait Type<'a>: Sized + 'static {
979         /// The type of values which may be tagged by this tag for the given
980         /// lifetime.
981         type Reified: 'a;
982     }
983
984     /// Similar to the [`Type`] trait, but represents a type which may be unsized (i.e., has a
985     /// `?Sized` bound). E.g., `str`.
986     pub trait MaybeSizedType<'a>: Sized + 'static {
987         type Reified: 'a + ?Sized;
988     }
989
990     impl<'a, T: Type<'a>> MaybeSizedType<'a> for T {
991         type Reified = T::Reified;
992     }
993
994     /// Type-based tag for types bounded by `'static`, i.e., with no borrowed elements.
995     #[derive(Debug)]
996     pub struct Value<T: 'static>(PhantomData<T>);
997
998     impl<'a, T: 'static> Type<'a> for Value<T> {
999         type Reified = T;
1000     }
1001
1002     /// Type-based tag similar to [`Value`] but which may be unsized (i.e., has a `?Sized` bound).
1003     #[derive(Debug)]
1004     pub struct MaybeSizedValue<T: ?Sized + 'static>(PhantomData<T>);
1005
1006     impl<'a, T: ?Sized + 'static> MaybeSizedType<'a> for MaybeSizedValue<T> {
1007         type Reified = T;
1008     }
1009
1010     /// Type-based tag for reference types (`&'a T`, where T is represented by
1011     /// `<I as MaybeSizedType<'a>>::Reified`.
1012     #[derive(Debug)]
1013     pub struct Ref<I>(PhantomData<I>);
1014
1015     impl<'a, I: MaybeSizedType<'a>> Type<'a> for Ref<I> {
1016         type Reified = &'a I::Reified;
1017     }
1018 }
1019
1020 /// An `Option` with a type tag `I`.
1021 ///
1022 /// Since this struct implements `Erased`, the type can be erased to make a dynamically typed
1023 /// option. The type can be checked dynamically using `Erased::tag_id` and since this is statically
1024 /// checked for the concrete type, there is some degree of type safety.
1025 #[repr(transparent)]
1026 struct TaggedOption<'a, I: tags::Type<'a>>(Option<I::Reified>);
1027
1028 impl<'a, I: tags::Type<'a>> TaggedOption<'a, I> {
1029     fn as_demand(&mut self) -> &mut Demand<'a> {
1030         Demand::new(self as &mut (dyn Erased<'a> + 'a))
1031     }
1032 }
1033
1034 /// Represents a type-erased but identifiable object.
1035 ///
1036 /// This trait is exclusively implemented by the `TaggedOption` type.
1037 unsafe trait Erased<'a>: 'a {
1038     /// The `TypeId` of the erased type.
1039     fn tag_id(&self) -> TypeId;
1040 }
1041
1042 unsafe impl<'a, I: tags::Type<'a>> Erased<'a> for TaggedOption<'a, I> {
1043     fn tag_id(&self) -> TypeId {
1044         TypeId::of::<I>()
1045     }
1046 }
1047
1048 #[unstable(feature = "provide_any", issue = "96024")]
1049 impl<'a> dyn Erased<'a> + 'a {
1050     /// Returns some reference to the dynamic value if it is tagged with `I`,
1051     /// or `None` otherwise.
1052     #[inline]
1053     fn downcast_mut<I>(&mut self) -> Option<&mut TaggedOption<'a, I>>
1054     where
1055         I: tags::Type<'a>,
1056     {
1057         if self.tag_id() == TypeId::of::<I>() {
1058             // SAFETY: Just checked whether we're pointing to an I.
1059             Some(unsafe { &mut *(self as *mut Self).cast::<TaggedOption<'a, I>>() })
1060         } else {
1061             None
1062         }
1063     }
1064 }