1 //! Utilities for dynamic typing or type reflection.
3 //! # `Any` and `TypeId`
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.
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.
16 //! [`Box`]: ../../std/boxed/struct.Box.html
18 //! # Smart pointers and `dyn Any`
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:
28 //! use std::any::{Any, TypeId};
30 //! let boxed: Box<dyn Any> = Box::new(3_i32);
32 //! // You're more likely to want this:
33 //! let actual_id = (&*boxed).type_id();
35 //! let boxed_id = boxed.type_id();
37 //! assert_eq!(actual_id, TypeId::of::<i32>());
38 //! assert_eq!(boxed_id, TypeId::of::<Box<dyn Any>>());
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.
51 //! use std::fmt::Debug;
52 //! use std::any::Any;
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;
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);
66 //! println!("{value:?}");
71 //! // This function wants to log its parameter out prior to doing work with it.
72 //! fn do_work<T: Any + Debug>(value: &T) {
74 //! // ...do some other work
78 //! let my_string = "Hello World".to_string();
79 //! do_work(&my_string);
81 //! let my_i8: i8 = 100;
86 //! # `Provider` and `Demand`
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.
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.
102 //! * A user requests an object of a specific type, which is delegated to `request_value` or
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.
113 //! # #![feature(provide_any)]
114 //! use std::any::{Provider, Demand, request_ref};
116 //! // Definition of MyTrait, a data provider.
117 //! trait MyTrait: Provider {
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)
129 //! // Downstream implementation of `MyTrait` and `Provider`.
130 //! # struct SomeConcreteType { some_string: String }
131 //! impl MyTrait for SomeConcreteType {
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);
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();
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`.
153 #![stable(feature = "rust1", since = "1.0.0")]
156 use crate::intrinsics;
158 ///////////////////////////////////////////////////////////////////////////////
160 ///////////////////////////////////////////////////////////////////////////////
162 /// A trait to emulate dynamic typing.
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.
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`.
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`.
186 /// use std::any::{Any, TypeId};
188 /// fn is_string(s: &dyn Any) -> bool {
189 /// TypeId::of::<String>() == s.type_id()
192 /// assert_eq!(is_string(&0), false);
193 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
195 #[stable(feature = "get_type_id", since = "1.34.0")]
196 fn type_id(&self) -> TypeId;
199 #[stable(feature = "rust1", since = "1.0.0")]
200 impl<T: 'static + ?Sized> Any for T {
201 fn type_id(&self) -> TypeId {
206 ///////////////////////////////////////////////////////////////////////////////
207 // Extension methods for Any trait objects.
208 ///////////////////////////////////////////////////////////////////////////////
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()
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()
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()
235 /// Returns `true` if the inner type is the same as `T`.
240 /// use std::any::Any;
242 /// fn is_string(s: &dyn Any) {
243 /// if s.is::<String>() {
244 /// println!("It's a string!");
246 /// println!("Not a string...");
251 /// is_string(&"cookie monster".to_string());
253 #[stable(feature = "rust1", since = "1.0.0")]
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>();
259 // Get `TypeId` of the type in the trait object (`self`).
260 let concrete = self.type_id();
262 // Compare both `TypeId`s on equality.
266 /// Returns some reference to the inner value if it is of type `T`, or
267 /// `None` if it isn't.
272 /// use std::any::Any;
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);
278 /// println!("Not a string...");
282 /// print_if_string(&0);
283 /// print_if_string(&"cookie monster".to_string());
285 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn downcast_ref<T: Any>(&self) -> Option<&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()) }
298 /// Returns some mutable reference to the inner value if it is of type `T`, or
299 /// `None` if it isn't.
304 /// use std::any::Any;
306 /// fn modify_if_u32(s: &mut dyn Any) {
307 /// if let Some(num) = s.downcast_mut::<u32>() {
312 /// let mut x = 10u32;
313 /// let mut s = "starlord".to_string();
315 /// modify_if_u32(&mut x);
316 /// modify_if_u32(&mut s);
318 /// assert_eq!(x, 42);
319 /// assert_eq!(&s, "starlord");
321 #[stable(feature = "rust1", since = "1.0.0")]
323 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut 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()) }
334 /// Returns a reference to the inner value as type `dyn T`.
339 /// #![feature(downcast_unchecked)]
341 /// use std::any::Any;
343 /// let x: Box<dyn Any> = Box::new(1_usize);
346 /// assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
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")]
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) }
362 /// Returns a mutable reference to the inner value as type `dyn T`.
367 /// #![feature(downcast_unchecked)]
369 /// use std::any::Any;
371 /// let mut x: Box<dyn Any> = Box::new(1_usize);
374 /// *x.downcast_mut_unchecked::<usize>() += 1;
377 /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
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")]
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) }
393 impl dyn Any + Send {
394 /// Forwards to the method defined on the type `dyn Any`.
399 /// use std::any::Any;
401 /// fn is_string(s: &(dyn Any + Send)) {
402 /// if s.is::<String>() {
403 /// println!("It's a string!");
405 /// println!("Not a string...");
410 /// is_string(&"cookie monster".to_string());
412 #[stable(feature = "rust1", since = "1.0.0")]
414 pub fn is<T: Any>(&self) -> bool {
415 <dyn Any>::is::<T>(self)
418 /// Forwards to the method defined on the type `dyn Any`.
423 /// use std::any::Any;
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);
429 /// println!("Not a string...");
433 /// print_if_string(&0);
434 /// print_if_string(&"cookie monster".to_string());
436 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
439 <dyn Any>::downcast_ref::<T>(self)
442 /// Forwards to the method defined on the type `dyn Any`.
447 /// use std::any::Any;
449 /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
450 /// if let Some(num) = s.downcast_mut::<u32>() {
455 /// let mut x = 10u32;
456 /// let mut s = "starlord".to_string();
458 /// modify_if_u32(&mut x);
459 /// modify_if_u32(&mut s);
461 /// assert_eq!(x, 42);
462 /// assert_eq!(&s, "starlord");
464 #[stable(feature = "rust1", since = "1.0.0")]
466 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
467 <dyn Any>::downcast_mut::<T>(self)
470 /// Forwards to the method defined on the type `dyn Any`.
475 /// #![feature(downcast_unchecked)]
477 /// use std::any::Any;
479 /// let x: Box<dyn Any> = Box::new(1_usize);
482 /// assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
488 /// Same as the method on the type `dyn Any`.
489 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
496 /// Forwards to the method defined on the type `dyn Any`.
501 /// #![feature(downcast_unchecked)]
503 /// use std::any::Any;
505 /// let mut x: Box<dyn Any> = Box::new(1_usize);
508 /// *x.downcast_mut_unchecked::<usize>() += 1;
511 /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
516 /// Same as the method on the type `dyn Any`.
517 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
525 impl dyn Any + Send + Sync {
526 /// Forwards to the method defined on the type `Any`.
531 /// use std::any::Any;
533 /// fn is_string(s: &(dyn Any + Send + Sync)) {
534 /// if s.is::<String>() {
535 /// println!("It's a string!");
537 /// println!("Not a string...");
542 /// is_string(&"cookie monster".to_string());
544 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
546 pub fn is<T: Any>(&self) -> bool {
547 <dyn Any>::is::<T>(self)
550 /// Forwards to the method defined on the type `Any`.
555 /// use std::any::Any;
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);
561 /// println!("Not a string...");
565 /// print_if_string(&0);
566 /// print_if_string(&"cookie monster".to_string());
568 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
570 pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
571 <dyn Any>::downcast_ref::<T>(self)
574 /// Forwards to the method defined on the type `Any`.
579 /// use std::any::Any;
581 /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
582 /// if let Some(num) = s.downcast_mut::<u32>() {
587 /// let mut x = 10u32;
588 /// let mut s = "starlord".to_string();
590 /// modify_if_u32(&mut x);
591 /// modify_if_u32(&mut s);
593 /// assert_eq!(x, 42);
594 /// assert_eq!(&s, "starlord");
596 #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
598 pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
599 <dyn Any>::downcast_mut::<T>(self)
602 /// Forwards to the method defined on the type `Any`.
607 /// #![feature(downcast_unchecked)]
609 /// use std::any::Any;
611 /// let x: Box<dyn Any> = Box::new(1_usize);
614 /// assert_eq!(*x.downcast_ref_unchecked::<usize>(), 1);
617 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
624 /// Forwards to the method defined on the type `Any`.
629 /// #![feature(downcast_unchecked)]
631 /// use std::any::Any;
633 /// let mut x: Box<dyn Any> = Box::new(1_usize);
636 /// *x.downcast_mut_unchecked::<usize>() += 1;
639 /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
641 #[unstable(feature = "downcast_unchecked", issue = "90850")]
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) }
649 ///////////////////////////////////////////////////////////////////////////////
650 // TypeID and its methods
651 ///////////////////////////////////////////////////////////////////////////////
653 /// A `TypeId` represents a globally unique identifier for a type.
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.
659 /// A `TypeId` is currently only available for types which ascribe to `'static`,
660 /// but this limitation may be removed in the future.
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")]
672 /// Returns the `TypeId` of the type this generic function has been
673 /// instantiated with.
678 /// use std::any::{Any, TypeId};
680 /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
681 /// TypeId::of::<String>() == TypeId::of::<T>()
684 /// assert_eq!(is_string(&0), false);
685 /// assert_eq!(is_string(&"cookie monster".to_string()), true);
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>() }
695 /// Returns the name of a type as a string slice.
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>"`.
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.
711 /// The current implementation uses the same infrastructure as compiler
712 /// diagnostics and debuginfo, but this is not guaranteed.
718 /// std::any::type_name::<Option<String>>(),
719 /// "core::option::Option<alloc::string::String>",
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>()
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.
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
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"`.
746 /// The type name should not be considered a unique identifier of a type;
747 /// multiple types may share the same type name.
749 /// The current implementation uses the same infrastructure as compiler
750 /// diagnostics and debuginfo, but this is not guaranteed.
754 /// Prints the default integer and float types.
757 /// #![feature(type_name_of_val)]
758 /// use std::any::type_name_of_val;
761 /// println!("{}", type_name_of_val(&x));
763 /// println!("{}", type_name_of_val(&y));
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 {
772 ///////////////////////////////////////////////////////////////////////////////
774 ///////////////////////////////////////////////////////////////////////////////
776 /// Trait implemented by a type which can dynamically provide values based on type.
777 #[unstable(feature = "provide_any", issue = "96024")]
779 /// Data providers should implement this method to provide *all* values they are able to
780 /// provide by using `demand`.
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
788 /// Provides a reference to a field with type `String` as a `&str`, and a value of
792 /// # #![feature(provide_any)]
793 /// use std::any::{Provider, Demand};
794 /// # struct SomeConcreteType { field: String, num_field: i32 }
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);
803 #[unstable(feature = "provide_any", issue = "96024")]
804 fn provide<'a>(&'a self, demand: &mut Demand<'a>);
807 /// Request a value from the `Provider`.
811 /// Get a string value from a provider.
814 /// # #![feature(provide_any)]
815 /// use std::any::{Provider, request_value};
817 /// fn get_string(provider: &impl Provider) -> String {
818 /// request_value::<String>(provider).unwrap()
821 #[unstable(feature = "provide_any", issue = "96024")]
822 pub fn request_value<'a, T>(provider: &'a (impl Provider + ?Sized)) -> Option<T>
826 request_by_type_tag::<'a, tags::Value<T>>(provider)
829 /// Request a reference from the `Provider`.
833 /// Get a string reference from a provider.
836 /// # #![feature(provide_any)]
837 /// use std::any::{Provider, request_ref};
839 /// fn get_str(provider: &impl Provider) -> &str {
840 /// request_ref::<str>(provider).unwrap()
843 #[unstable(feature = "provide_any", issue = "96024")]
844 pub fn request_ref<'a, T>(provider: &'a (impl Provider + ?Sized)) -> Option<&'a T>
848 request_by_type_tag::<'a, tags::Ref<tags::MaybeSizedValue<T>>>(provider)
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>
856 let mut tagged = TaggedOption::<'a, I>(None);
857 provider.provide(tagged.as_demand());
861 ///////////////////////////////////////////////////////////////////////////////
862 // Demand and its methods
863 ///////////////////////////////////////////////////////////////////////////////
865 /// A helper object for providing data by type.
867 /// A data provider provides values by calling this type's provide methods.
868 #[unstable(feature = "provide_any", issue = "96024")]
870 pub struct Demand<'a>(dyn Erased<'a> + 'a);
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>) }
880 /// Provide a value or other type with only static lifetimes.
884 /// Provides a `String` by cloning.
887 /// # #![feature(provide_any)]
888 /// use std::any::{Provider, Demand};
889 /// # struct SomeConcreteType { field: String }
891 /// impl Provider for SomeConcreteType {
892 /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
893 /// demand.provide_value::<String>(|| self.field.clone());
897 #[unstable(feature = "provide_any", issue = "96024")]
898 pub fn provide_value<T>(&mut self, fulfil: impl FnOnce() -> T) -> &mut Self
902 self.provide_with::<tags::Value<T>>(fulfil)
905 /// Provide a reference, note that the referee type must be bounded by `'static`,
906 /// but may be unsized.
910 /// Provides a reference to a field as a `&str`.
913 /// # #![feature(provide_any)]
914 /// use std::any::{Provider, Demand};
915 /// # struct SomeConcreteType { field: String }
917 /// impl Provider for SomeConcreteType {
918 /// fn provide<'a>(&'a self, demand: &mut Demand<'a>) {
919 /// demand.provide_ref::<str>(&self.field);
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)
928 /// Provide a value with the given `Type` tag.
929 fn provide<I>(&mut self, value: I::Reified) -> &mut Self
933 if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
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
944 if let Some(res @ TaggedOption(None)) = self.0.downcast_mut::<I>() {
945 res.0 = Some(fulfil());
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()
958 ///////////////////////////////////////////////////////////////////////////////
960 ///////////////////////////////////////////////////////////////////////////////
963 //! Type tags are used to identify a type using a separate value. This module includes type tags
964 //! for some very common types.
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.
970 use crate::marker::PhantomData;
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`.
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
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;
990 impl<'a, T: Type<'a>> MaybeSizedType<'a> for T {
991 type Reified = T::Reified;
994 /// Type-based tag for types bounded by `'static`, i.e., with no borrowed elements.
996 pub struct Value<T: 'static>(PhantomData<T>);
998 impl<'a, T: 'static> Type<'a> for Value<T> {
1002 /// Type-based tag similar to [`Value`] but which may be unsized (i.e., has a `?Sized` bound).
1004 pub struct MaybeSizedValue<T: ?Sized + 'static>(PhantomData<T>);
1006 impl<'a, T: ?Sized + 'static> MaybeSizedType<'a> for MaybeSizedValue<T> {
1010 /// Type-based tag for reference types (`&'a T`, where T is represented by
1011 /// `<I as MaybeSizedType<'a>>::Reified`.
1013 pub struct Ref<I>(PhantomData<I>);
1015 impl<'a, I: MaybeSizedType<'a>> Type<'a> for Ref<I> {
1016 type Reified = &'a I::Reified;
1020 /// An `Option` with a type tag `I`.
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>);
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))
1034 /// Represents a type-erased but identifiable object.
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;
1042 unsafe impl<'a, I: tags::Type<'a>> Erased<'a> for TaggedOption<'a, I> {
1043 fn tag_id(&self) -> TypeId {
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.
1053 fn downcast_mut<I>(&mut self) -> Option<&mut TaggedOption<'a, I>>
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>>() })