Skip to main content

core/
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 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
87#![stable(feature = "rust1", since = "1.0.0")]
88
89use crate::intrinsics::reflection::{type_id, type_id_vtable};
90use crate::intrinsics::{self};
91use crate::mem::transmute;
92use crate::mem::type_info::{TraitImpl, TypeKind};
93use crate::{fmt, hash, ptr};
94
95///////////////////////////////////////////////////////////////////////////////
96// Any trait
97///////////////////////////////////////////////////////////////////////////////
98
99/// A trait to emulate dynamic typing.
100///
101/// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
102/// See the [module-level documentation][mod] for more details.
103///
104/// [mod]: crate::any
105// This trait is not unsafe, though we rely on the specifics of it's sole impl's
106// `type_id` function in unsafe code (e.g., `downcast`). Normally, that would be
107// a problem, but because the only impl of `Any` is a blanket implementation, no
108// other code can implement `Any`.
109//
110// We could plausibly make this trait unsafe -- it would not cause breakage,
111// since we control all the implementations -- but we choose not to as that's
112// both not really necessary and may confuse users about the distinction of
113// unsafe traits and unsafe methods (i.e., `type_id` would still be safe to call,
114// but we would likely want to indicate as such in documentation).
115#[stable(feature = "rust1", since = "1.0.0")]
116#[rustc_diagnostic_item = "Any"]
117pub trait Any: 'static {
118    /// Gets the `TypeId` of `self`.
119    ///
120    /// If called on a `dyn Any` trait object
121    /// (or a trait object of a subtrait of `Any`),
122    /// this returns the `TypeId` of the underlying
123    /// concrete type, not that of `dyn Any` itself.
124    ///
125    /// # Examples
126    ///
127    /// ```
128    /// use std::any::{Any, TypeId};
129    ///
130    /// fn is_string(s: &dyn Any) -> bool {
131    ///     TypeId::of::<String>() == s.type_id()
132    /// }
133    ///
134    /// assert_eq!(is_string(&0), false);
135    /// assert_eq!(is_string(&"cookie monster".to_string()), true);
136    /// ```
137    #[stable(feature = "get_type_id", since = "1.34.0")]
138    fn type_id(&self) -> TypeId;
139}
140
141#[stable(feature = "rust1", since = "1.0.0")]
142impl<T: 'static + ?Sized> Any for T {
143    fn type_id(&self) -> TypeId {
144        TypeId::of::<T>()
145    }
146}
147
148///////////////////////////////////////////////////////////////////////////////
149// Extension methods for Any trait objects.
150///////////////////////////////////////////////////////////////////////////////
151
152#[stable(feature = "rust1", since = "1.0.0")]
153impl fmt::Debug for dyn Any {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        f.debug_struct("Any").finish_non_exhaustive()
156    }
157}
158
159// Ensure that the result of e.g., joining a thread can be printed and
160// hence used with `unwrap`. May eventually no longer be needed if
161// dispatch works with upcasting.
162#[stable(feature = "rust1", since = "1.0.0")]
163impl fmt::Debug for dyn Any + Send {
164    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
165        f.debug_struct("Any").finish_non_exhaustive()
166    }
167}
168
169#[stable(feature = "any_send_sync_methods", since = "1.28.0")]
170impl fmt::Debug for dyn Any + Send + Sync {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        f.debug_struct("Any").finish_non_exhaustive()
173    }
174}
175
176impl dyn Any {
177    /// Returns `true` if the inner type is the same as `T`.
178    ///
179    /// # Examples
180    ///
181    /// ```
182    /// use std::any::Any;
183    ///
184    /// fn is_string(s: &dyn Any) {
185    ///     if s.is::<String>() {
186    ///         println!("It's a string!");
187    ///     } else {
188    ///         println!("Not a string...");
189    ///     }
190    /// }
191    ///
192    /// is_string(&0);
193    /// is_string(&"cookie monster".to_string());
194    /// ```
195    #[stable(feature = "rust1", since = "1.0.0")]
196    #[inline]
197    pub fn is<T: Any>(&self) -> bool {
198        // Get `TypeId` of the type this function is instantiated with.
199        let t = TypeId::of::<T>();
200
201        // Get `TypeId` of the type in the trait object (`self`).
202        let concrete = self.type_id();
203
204        // Compare both `TypeId`s on equality.
205        t == concrete
206    }
207
208    /// Returns some reference to the inner value if it is of type `T`, or
209    /// `None` if it isn't.
210    ///
211    /// # Examples
212    ///
213    /// ```
214    /// use std::any::Any;
215    ///
216    /// fn print_if_string(s: &dyn Any) {
217    ///     if let Some(string) = s.downcast_ref::<String>() {
218    ///         println!("It's a string({}): '{}'", string.len(), string);
219    ///     } else {
220    ///         println!("Not a string...");
221    ///     }
222    /// }
223    ///
224    /// print_if_string(&0);
225    /// print_if_string(&"cookie monster".to_string());
226    /// ```
227    #[stable(feature = "rust1", since = "1.0.0")]
228    #[inline]
229    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
230        if self.is::<T>() {
231            // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
232            // that check for memory safety because we have implemented Any for all types; no other
233            // impls can exist as they would conflict with our impl.
234            unsafe { Some(self.downcast_unchecked_ref()) }
235        } else {
236            None
237        }
238    }
239
240    /// Returns some mutable reference to the inner value if it is of type `T`, or
241    /// `None` if it isn't.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// use std::any::Any;
247    ///
248    /// fn modify_if_u32(s: &mut dyn Any) {
249    ///     if let Some(num) = s.downcast_mut::<u32>() {
250    ///         *num = 42;
251    ///     }
252    /// }
253    ///
254    /// let mut x = 10u32;
255    /// let mut s = "starlord".to_string();
256    ///
257    /// modify_if_u32(&mut x);
258    /// modify_if_u32(&mut s);
259    ///
260    /// assert_eq!(x, 42);
261    /// assert_eq!(&s, "starlord");
262    /// ```
263    #[stable(feature = "rust1", since = "1.0.0")]
264    #[inline]
265    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
266        if self.is::<T>() {
267            // SAFETY: just checked whether we are pointing to the correct type, and we can rely on
268            // that check for memory safety because we have implemented Any for all types; no other
269            // impls can exist as they would conflict with our impl.
270            unsafe { Some(self.downcast_unchecked_mut()) }
271        } else {
272            None
273        }
274    }
275
276    /// Returns a reference to the inner value as type `dyn T`.
277    ///
278    /// # Examples
279    ///
280    /// ```
281    /// #![feature(downcast_unchecked)]
282    ///
283    /// use std::any::Any;
284    ///
285    /// let x: Box<dyn Any> = Box::new(1_usize);
286    ///
287    /// unsafe {
288    ///     assert_eq!(*x.downcast_unchecked_ref::<usize>(), 1);
289    /// }
290    /// ```
291    ///
292    /// # Safety
293    ///
294    /// The contained value must be of type `T`. Calling this method
295    /// with the incorrect type is *undefined behavior*.
296    #[unstable(feature = "downcast_unchecked", issue = "90850")]
297    #[inline]
298    pub unsafe fn downcast_unchecked_ref<T: Any>(&self) -> &T {
299        debug_assert!(self.is::<T>());
300        // SAFETY: caller guarantees that T is the correct type
301        unsafe { &*(self as *const dyn Any as *const T) }
302    }
303
304    /// Returns a mutable reference to the inner value as type `dyn T`.
305    ///
306    /// # Examples
307    ///
308    /// ```
309    /// #![feature(downcast_unchecked)]
310    ///
311    /// use std::any::Any;
312    ///
313    /// let mut x: Box<dyn Any> = Box::new(1_usize);
314    ///
315    /// unsafe {
316    ///     *x.downcast_unchecked_mut::<usize>() += 1;
317    /// }
318    ///
319    /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
320    /// ```
321    ///
322    /// # Safety
323    ///
324    /// The contained value must be of type `T`. Calling this method
325    /// with the incorrect type is *undefined behavior*.
326    #[unstable(feature = "downcast_unchecked", issue = "90850")]
327    #[inline]
328    pub unsafe fn downcast_unchecked_mut<T: Any>(&mut self) -> &mut T {
329        debug_assert!(self.is::<T>());
330        // SAFETY: caller guarantees that T is the correct type
331        unsafe { &mut *(self as *mut dyn Any as *mut T) }
332    }
333}
334
335impl dyn Any + Send {
336    /// Forwards to the method defined on the type `dyn Any`.
337    ///
338    /// # Examples
339    ///
340    /// ```
341    /// use std::any::Any;
342    ///
343    /// fn is_string(s: &(dyn Any + Send)) {
344    ///     if s.is::<String>() {
345    ///         println!("It's a string!");
346    ///     } else {
347    ///         println!("Not a string...");
348    ///     }
349    /// }
350    ///
351    /// is_string(&0);
352    /// is_string(&"cookie monster".to_string());
353    /// ```
354    #[stable(feature = "rust1", since = "1.0.0")]
355    #[inline]
356    pub fn is<T: Any>(&self) -> bool {
357        <dyn Any>::is::<T>(self)
358    }
359
360    /// Forwards to the method defined on the type `dyn Any`.
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// use std::any::Any;
366    ///
367    /// fn print_if_string(s: &(dyn Any + Send)) {
368    ///     if let Some(string) = s.downcast_ref::<String>() {
369    ///         println!("It's a string({}): '{}'", string.len(), string);
370    ///     } else {
371    ///         println!("Not a string...");
372    ///     }
373    /// }
374    ///
375    /// print_if_string(&0);
376    /// print_if_string(&"cookie monster".to_string());
377    /// ```
378    #[stable(feature = "rust1", since = "1.0.0")]
379    #[inline]
380    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
381        <dyn Any>::downcast_ref::<T>(self)
382    }
383
384    /// Forwards to the method defined on the type `dyn Any`.
385    ///
386    /// # Examples
387    ///
388    /// ```
389    /// use std::any::Any;
390    ///
391    /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
392    ///     if let Some(num) = s.downcast_mut::<u32>() {
393    ///         *num = 42;
394    ///     }
395    /// }
396    ///
397    /// let mut x = 10u32;
398    /// let mut s = "starlord".to_string();
399    ///
400    /// modify_if_u32(&mut x);
401    /// modify_if_u32(&mut s);
402    ///
403    /// assert_eq!(x, 42);
404    /// assert_eq!(&s, "starlord");
405    /// ```
406    #[stable(feature = "rust1", since = "1.0.0")]
407    #[inline]
408    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
409        <dyn Any>::downcast_mut::<T>(self)
410    }
411
412    /// Forwards to the method defined on the type `dyn Any`.
413    ///
414    /// # Examples
415    ///
416    /// ```
417    /// #![feature(downcast_unchecked)]
418    ///
419    /// use std::any::Any;
420    ///
421    /// let x: Box<dyn Any> = Box::new(1_usize);
422    ///
423    /// unsafe {
424    ///     assert_eq!(*x.downcast_unchecked_ref::<usize>(), 1);
425    /// }
426    /// ```
427    ///
428    /// # Safety
429    ///
430    /// The contained value must be of type `T`. Calling this method
431    /// with the incorrect type is *undefined behavior*.
432    #[unstable(feature = "downcast_unchecked", issue = "90850")]
433    #[inline]
434    pub unsafe fn downcast_unchecked_ref<T: Any>(&self) -> &T {
435        // SAFETY: guaranteed by caller
436        unsafe { <dyn Any>::downcast_unchecked_ref::<T>(self) }
437    }
438
439    /// Forwards to the method defined on the type `dyn Any`.
440    ///
441    /// # Examples
442    ///
443    /// ```
444    /// #![feature(downcast_unchecked)]
445    ///
446    /// use std::any::Any;
447    ///
448    /// let mut x: Box<dyn Any> = Box::new(1_usize);
449    ///
450    /// unsafe {
451    ///     *x.downcast_unchecked_mut::<usize>() += 1;
452    /// }
453    ///
454    /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
455    /// ```
456    ///
457    /// # Safety
458    ///
459    /// The contained value must be of type `T`. Calling this method
460    /// with the incorrect type is *undefined behavior*.
461    #[unstable(feature = "downcast_unchecked", issue = "90850")]
462    #[inline]
463    pub unsafe fn downcast_unchecked_mut<T: Any>(&mut self) -> &mut T {
464        // SAFETY: guaranteed by caller
465        unsafe { <dyn Any>::downcast_unchecked_mut::<T>(self) }
466    }
467}
468
469impl dyn Any + Send + Sync {
470    /// Forwards to the method defined on the type `Any`.
471    ///
472    /// # Examples
473    ///
474    /// ```
475    /// use std::any::Any;
476    ///
477    /// fn is_string(s: &(dyn Any + Send + Sync)) {
478    ///     if s.is::<String>() {
479    ///         println!("It's a string!");
480    ///     } else {
481    ///         println!("Not a string...");
482    ///     }
483    /// }
484    ///
485    /// is_string(&0);
486    /// is_string(&"cookie monster".to_string());
487    /// ```
488    #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
489    #[inline]
490    pub fn is<T: Any>(&self) -> bool {
491        <dyn Any>::is::<T>(self)
492    }
493
494    /// Forwards to the method defined on the type `Any`.
495    ///
496    /// # Examples
497    ///
498    /// ```
499    /// use std::any::Any;
500    ///
501    /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
502    ///     if let Some(string) = s.downcast_ref::<String>() {
503    ///         println!("It's a string({}): '{}'", string.len(), string);
504    ///     } else {
505    ///         println!("Not a string...");
506    ///     }
507    /// }
508    ///
509    /// print_if_string(&0);
510    /// print_if_string(&"cookie monster".to_string());
511    /// ```
512    #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
513    #[inline]
514    pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
515        <dyn Any>::downcast_ref::<T>(self)
516    }
517
518    /// Forwards to the method defined on the type `Any`.
519    ///
520    /// # Examples
521    ///
522    /// ```
523    /// use std::any::Any;
524    ///
525    /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
526    ///     if let Some(num) = s.downcast_mut::<u32>() {
527    ///         *num = 42;
528    ///     }
529    /// }
530    ///
531    /// let mut x = 10u32;
532    /// let mut s = "starlord".to_string();
533    ///
534    /// modify_if_u32(&mut x);
535    /// modify_if_u32(&mut s);
536    ///
537    /// assert_eq!(x, 42);
538    /// assert_eq!(&s, "starlord");
539    /// ```
540    #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
541    #[inline]
542    pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
543        <dyn Any>::downcast_mut::<T>(self)
544    }
545
546    /// Forwards to the method defined on the type `Any`.
547    ///
548    /// # Examples
549    ///
550    /// ```
551    /// #![feature(downcast_unchecked)]
552    ///
553    /// use std::any::Any;
554    ///
555    /// let x: Box<dyn Any> = Box::new(1_usize);
556    ///
557    /// unsafe {
558    ///     assert_eq!(*x.downcast_unchecked_ref::<usize>(), 1);
559    /// }
560    /// ```
561    /// # Safety
562    ///
563    /// The contained value must be of type `T`. Calling this method
564    /// with the incorrect type is *undefined behavior*.
565    #[unstable(feature = "downcast_unchecked", issue = "90850")]
566    #[inline]
567    pub unsafe fn downcast_unchecked_ref<T: Any>(&self) -> &T {
568        // SAFETY: guaranteed by caller
569        unsafe { <dyn Any>::downcast_unchecked_ref::<T>(self) }
570    }
571
572    /// Forwards to the method defined on the type `Any`.
573    ///
574    /// # Examples
575    ///
576    /// ```
577    /// #![feature(downcast_unchecked)]
578    ///
579    /// use std::any::Any;
580    ///
581    /// let mut x: Box<dyn Any> = Box::new(1_usize);
582    ///
583    /// unsafe {
584    ///     *x.downcast_unchecked_mut::<usize>() += 1;
585    /// }
586    ///
587    /// assert_eq!(*x.downcast_ref::<usize>().unwrap(), 2);
588    /// ```
589    /// # Safety
590    ///
591    /// The contained value must be of type `T`. Calling this method
592    /// with the incorrect type is *undefined behavior*.
593    #[unstable(feature = "downcast_unchecked", issue = "90850")]
594    #[inline]
595    pub unsafe fn downcast_unchecked_mut<T: Any>(&mut self) -> &mut T {
596        // SAFETY: guaranteed by caller
597        unsafe { <dyn Any>::downcast_unchecked_mut::<T>(self) }
598    }
599}
600
601///////////////////////////////////////////////////////////////////////////////
602// TypeID and its methods
603///////////////////////////////////////////////////////////////////////////////
604
605/// A `TypeId` represents a globally unique identifier for a type.
606///
607/// Each `TypeId` is an opaque object which does not allow inspection of what's
608/// inside but does allow basic operations such as cloning, comparison,
609/// printing, and showing.
610///
611/// A `TypeId` is currently only available for types which ascribe to `'static`,
612/// but this limitation may be removed in the future.
613///
614/// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
615/// noting that the hashes and ordering will vary between Rust releases. Beware
616/// of relying on them inside of your code!
617///
618/// # Layout
619///
620/// Like other [`Rust`-representation][repr-rust] types, `TypeId`'s size and layout are unstable.
621/// In particular, this means that you cannot rely on the size and layout of `TypeId` remaining the
622/// same between Rust releases; they are subject to change without prior notice between Rust
623/// releases.
624///
625/// [repr-rust]: https://doc.rust-lang.org/reference/type-layout.html#r-layout.repr.rust.unspecified
626///
627/// # Danger of Improper Variance
628///
629/// You might think that subtyping is impossible between two static types,
630/// but this is false; there exists a static type with a static subtype.
631/// To wit, `fn(&str)`, which is short for `for<'any> fn(&'any str)`, and
632/// `fn(&'static str)`, are two distinct, static types, and yet,
633/// `fn(&str)` is a subtype of `fn(&'static str)`, since any value of type
634/// `fn(&str)` can be used where a value of type `fn(&'static str)` is needed.
635///
636/// This means that abstractions around `TypeId`, despite its
637/// `'static` bound on arguments, still need to worry about unnecessary
638/// and improper variance: it is advisable to strive for invariance
639/// first. The usability impact will be negligible, while the reduction
640/// in the risk of unsoundness will be most welcome.
641///
642/// ## Examples
643///
644/// Suppose `SubType` is a subtype of `SuperType`, that is,
645/// a value of type `SubType` can be used wherever
646/// a value of type `SuperType` is expected.
647/// Suppose also that `CoVar<T>` is a generic type, which is covariant over `T`
648/// (like many other types, including `PhantomData<T>` and `Vec<T>`).
649///
650/// Then, by covariance, `CoVar<SubType>` is a subtype of `CoVar<SuperType>`,
651/// that is, a value of type `CoVar<SubType>` can be used wherever
652/// a value of type `CoVar<SuperType>` is expected.
653///
654/// Then if `CoVar<SuperType>` relies on `TypeId::of::<SuperType>()` to uphold any invariants,
655/// those invariants may be broken because a value of type `CoVar<SuperType>` can be created
656/// without going through any of its methods, like so:
657/// ```
658/// type SubType = fn(&());
659/// type SuperType = fn(&'static ());
660/// type CoVar<T> = Vec<T>; // imagine something more complicated
661///
662/// let sub: CoVar<SubType> = CoVar::new();
663/// // we have a `CoVar<SuperType>` instance without
664/// // *ever* having called `CoVar::<SuperType>::new()`!
665/// let fake_super: CoVar<SuperType> = sub;
666/// ```
667///
668/// The following is an example program that tries to use `TypeId::of` to
669/// implement a generic type `Unique<T>` that guarantees unique instances for each `Unique<T>`,
670/// that is, for each type `T` there can be at most one value of type `Unique<T>` at any time.
671///
672/// ```
673/// mod unique {
674///     use std::any::TypeId;
675///     use std::collections::BTreeSet;
676///     use std::marker::PhantomData;
677///     use std::sync::Mutex;
678///
679///     static ID_SET: Mutex<BTreeSet<TypeId>> = Mutex::new(BTreeSet::new());
680///
681///     // TypeId has only covariant uses, which makes Unique covariant over TypeAsId 🚨
682///     #[derive(Debug, PartialEq)]
683///     pub struct Unique<TypeAsId: 'static>(
684///         // private field prevents creation without `new` outside this module
685///         PhantomData<TypeAsId>,
686///     );
687///
688///     impl<TypeAsId: 'static> Unique<TypeAsId> {
689///         pub fn new() -> Option<Self> {
690///             let mut set = ID_SET.lock().unwrap();
691///             (set.insert(TypeId::of::<TypeAsId>())).then(|| Self(PhantomData))
692///         }
693///     }
694///
695///     impl<TypeAsId: 'static> Drop for Unique<TypeAsId> {
696///         fn drop(&mut self) {
697///             let mut set = ID_SET.lock().unwrap();
698///             (!set.remove(&TypeId::of::<TypeAsId>())).then(|| panic!("duplicity detected"));
699///         }
700///     }
701/// }
702///
703/// use unique::Unique;
704///
705/// // `OtherRing` is a subtype of `TheOneRing`. Both are 'static, and thus have a TypeId.
706/// type TheOneRing = fn(&'static ());
707/// type OtherRing = fn(&());
708///
709/// fn main() {
710///     let the_one_ring: Unique<TheOneRing> = Unique::new().unwrap();
711///     assert_eq!(Unique::<TheOneRing>::new(), None);
712///
713///     let other_ring: Unique<OtherRing> = Unique::new().unwrap();
714///     // Use that `Unique<OtherRing>` is a subtype of `Unique<TheOneRing>` 🚨
715///     let fake_one_ring: Unique<TheOneRing> = other_ring;
716///     assert_eq!(fake_one_ring, the_one_ring);
717///
718///     std::mem::forget(fake_one_ring);
719/// }
720/// ```
721#[derive(Copy, PartialOrd, Ord)]
722#[derive_const(Clone, Eq)]
723#[stable(feature = "rust1", since = "1.0.0")]
724#[lang = "type_id"]
725pub struct TypeId {
726    /// This needs to be an array of pointers, since there is provenance
727    /// in the first array field. This provenance knows exactly which type
728    /// the TypeId actually is, allowing CTFE and miri to operate based off it.
729    /// At runtime all the pointers in the array contain bits of the hash, making
730    /// the entire `TypeId` actually just be a `u128` hash of the type.
731    pub(crate) data: [*const (); 16 / size_of::<*const ()>()],
732}
733
734// SAFETY: the raw pointer is always an integer
735#[stable(feature = "rust1", since = "1.0.0")]
736unsafe impl Send for TypeId {}
737// SAFETY: the raw pointer is always an integer
738#[stable(feature = "rust1", since = "1.0.0")]
739unsafe impl Sync for TypeId {}
740
741#[stable(feature = "rust1", since = "1.0.0")]
742#[rustc_const_unstable(feature = "const_cmp", issue = "143800")]
743const impl PartialEq for TypeId {
744    #[inline]
745    fn eq(&self, other: &Self) -> bool {
746        crate::intrinsics::reflection::type_id_eq(*self, *other)
747    }
748}
749
750impl TypeId {
751    /// Returns the `TypeId` of the generic type parameter.
752    ///
753    /// # Examples
754    ///
755    /// ```
756    /// use std::any::{Any, TypeId};
757    ///
758    /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
759    ///     TypeId::of::<String>() == TypeId::of::<T>()
760    /// }
761    ///
762    /// assert_eq!(is_string(&0), false);
763    /// assert_eq!(is_string(&"cookie monster".to_string()), true);
764    /// ```
765    #[must_use]
766    #[stable(feature = "rust1", since = "1.0.0")]
767    #[rustc_const_stable(feature = "const_type_id", since = "1.91.0")]
768    pub const fn of<T: ?Sized + 'static>() -> TypeId {
769        const { intrinsics::reflection::type_id::<T>() }
770    }
771
772    /// Checks if the [TypeId] implements the trait. If it does it returns [TraitImpl] which can be used to build a fat pointer.
773    /// It can only be called at compile time. `self` must be the [TypeId] of a sized type or None will be returned.
774    ///
775    /// # Examples
776    ///
777    /// ```
778    /// #![feature(type_info)]
779    /// use std::any::{TypeId};
780    ///
781    /// pub trait Blah {}
782    /// impl Blah for u8 {}
783    ///
784    /// assert!(const { TypeId::of::<u8>().trait_info_of::<dyn Blah>() }.is_some());
785    /// assert!(const { TypeId::of::<u16>().trait_info_of::<dyn Blah>() }.is_none());
786    /// ```
787    #[unstable(feature = "type_info", issue = "146922")]
788    #[rustc_const_unstable(feature = "type_info", issue = "146922")]
789    #[rustc_comptime]
790    pub fn trait_info_of<'a, T: TryAsDynCompatible<'a> + ?Sized>(self) -> Option<TraitImpl<T>> {
791        // SAFETY: The vtable was obtained for `T`, so it is guaranteed to be `DynMetadata<T>`.
792        // The intrinsic can't infer this because it is designed to work with arbitrary TypeIds.
793        unsafe { transmute(self.trait_info_of_trait_type_id(const { type_id::<T>() })) }
794    }
795
796    /// Checks if the [TypeId] implements the trait of `trait_represented_by_type_id`. If it does it returns [TraitImpl] which can be used to build a fat pointer.
797    /// It can only be called at compile time. `self` must be the [TypeId] of a sized type or None will be returned.
798    ///
799    /// # Examples
800    ///
801    /// ```
802    /// #![feature(type_info)]
803    /// use std::any::{TypeId};
804    ///
805    /// pub trait Blah {}
806    /// impl Blah for u8 {}
807    ///
808    /// assert!(const { TypeId::of::<u8>().trait_info_of_trait_type_id(TypeId::of::<dyn Blah>()) }.is_some());
809    /// assert!(const { TypeId::of::<u16>().trait_info_of_trait_type_id(TypeId::of::<dyn Blah>()) }.is_none());
810    /// ```
811    #[unstable(feature = "type_info", issue = "146922")]
812    #[rustc_const_unstable(feature = "type_info", issue = "146922")]
813    #[rustc_comptime]
814    pub fn trait_info_of_trait_type_id(
815        self,
816        trait_represented_by_type_id: TypeId,
817    ) -> Option<TraitImpl<*const ()>> {
818        if self.size().is_none() {
819            return None;
820        }
821
822        if matches!(trait_represented_by_type_id.info().kind, TypeKind::DynTrait(_))
823            && let Some(vtable) = type_id_vtable(self, trait_represented_by_type_id)
824        {
825            Some(TraitImpl { vtable })
826        } else {
827            None
828        }
829    }
830
831    pub(crate) fn as_u128(self) -> u128 {
832        let mut bytes = [0; 16];
833
834        // This is a provenance-stripping memcpy.
835        for (i, chunk) in self.data.iter().copied().enumerate() {
836            let chunk = chunk.addr().to_ne_bytes();
837            let start = i * chunk.len();
838            bytes[start..(start + chunk.len())].copy_from_slice(&chunk);
839        }
840        u128::from_ne_bytes(bytes)
841    }
842}
843
844#[stable(feature = "rust1", since = "1.0.0")]
845impl hash::Hash for TypeId {
846    #[inline]
847    fn hash<H: hash::Hasher>(&self, state: &mut H) {
848        // We only hash the lower 64 bits of our (128 bit) internal numeric ID,
849        // because:
850        // - The hashing algorithm which backs `TypeId` is expected to be
851        //   unbiased and high quality, meaning further mixing would be somewhat
852        //   redundant compared to choosing (the lower) 64 bits arbitrarily.
853        // - `Hasher::finish` returns a u64 anyway, so the extra entropy we'd
854        //   get from hashing the full value would probably not be useful
855        //   (especially given the previous point about the lower 64 bits being
856        //   high quality on their own).
857        // - It is correct to do so -- only hashing a subset of `self` is still
858        //   compatible with an `Eq` implementation that considers the entire
859        //   value, as ours does.
860        let data =
861        // SAFETY: The `offset` stays in-bounds, it just moves the pointer to the 2nd half of the `TypeId`.
862        // Only the first ptr-sized chunk ever has provenance, so that second half is always
863        // fine to read at integer type.
864            unsafe { crate::ptr::read_unaligned(self.data.as_ptr().cast::<u64>().offset(1)) };
865        data.hash(state);
866    }
867}
868
869#[stable(feature = "rust1", since = "1.0.0")]
870impl fmt::Debug for TypeId {
871    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
872        write!(f, "TypeId({:#034x})", self.as_u128())
873    }
874}
875
876/// Returns the name of a type as a string slice.
877///
878/// # Note
879///
880/// This is intended for diagnostic use. The exact contents and format of the
881/// string returned are not specified, other than being a best-effort
882/// description of the type. For example, amongst the strings
883/// that `type_name::<Option<String>>()` might return are `"Option<String>"` and
884/// `"std::option::Option<std::string::String>"`.
885///
886/// The returned string must not be considered to be a unique identifier of a
887/// type as multiple types may map to the same type name. Similarly, there is no
888/// guarantee that all parts of a type will appear in the returned string. In
889/// addition, the output may change between versions of the compiler. For
890/// example, lifetime specifiers were omitted in some earlier versions.
891///
892/// The current implementation uses the same infrastructure as compiler
893/// diagnostics and debuginfo, but this is not guaranteed.
894///
895/// # Examples
896///
897/// ```rust
898/// assert_eq!(
899///     std::any::type_name::<Option<String>>(),
900///     "core::option::Option<alloc::string::String>",
901/// );
902/// ```
903#[must_use]
904#[stable(feature = "type_name", since = "1.38.0")]
905#[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
906pub const fn type_name<T: ?Sized>() -> &'static str {
907    const { intrinsics::reflection::type_name::<T>() }
908}
909
910/// Returns the type name of the pointed-to value as a string slice.
911///
912/// This is the same as `type_name::<T>()`, but can be used where the type of a
913/// variable is not easily available.
914///
915/// # Note
916///
917/// Like [`type_name`], this is intended for diagnostic use and the exact output is not
918/// guaranteed. It provides a best-effort description, but the output may change between
919/// versions of the compiler.
920///
921/// In short: use this for debugging, avoid using the output to affect program behavior. More
922/// information is available at [`type_name`].
923///
924/// Additionally, this function does not resolve trait objects. This means that
925/// `type_name_of_val(&7u32 as &dyn Debug)` may return `"dyn Debug"`, but will not return `"u32"`
926/// at this time.
927///
928/// # Examples
929///
930/// Prints the default integer and float types.
931///
932/// ```rust
933/// use std::any::type_name_of_val;
934///
935/// let s = "foo";
936/// let x: i32 = 1;
937/// let y: f32 = 1.0;
938///
939/// assert!(type_name_of_val(&s).contains("str"));
940/// assert!(type_name_of_val(&x).contains("i32"));
941/// assert!(type_name_of_val(&y).contains("f32"));
942/// ```
943#[must_use]
944#[stable(feature = "type_name_of_val", since = "1.76.0")]
945#[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
946pub const fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
947    type_name::<T>()
948}
949
950/// Trait that is automatically implemented for all `dyn Trait<'b, C> + 'a` without assoc type bounds.
951/// The lifetime parameter should be the same that is used to constrain generic type parameters
952/// that are turned into the dyn trait constrained by `TryAsDynCompatible`.
953///
954/// This is required for `try_as_dyn` to be able to soundly convert non-static
955/// types to `dyn Trait`.
956///
957/// Note: these requirements are sufficient for soundness, but it is unclear
958/// if they are all necessary. We may be able to lift some requirements in favor
959/// of more precise ones.
960///
961#[unstable(feature = "try_as_dyn", issue = "144361")]
962#[lang = "try_as_dyn"]
963#[rustc_deny_explicit_impl]
964pub trait TryAsDynCompatible<'a>: ptr::Pointee<Metadata = ptr::DynMetadata<Self>> {}
965
966/// Returns `Some(&U)` if `T` can be coerced to the dyn trait type `U`. Otherwise, it returns `None`.
967///
968/// <div class="warning">
969///
970/// This function is implemented on a best-effort basis. It is not always possible to determine
971/// whether a generic type implements a trait; thus, this function may produce false negatives,
972/// returning `None` even when `T` implements the requested trait.
973///
974/// `try_as_dyn` is guaranteed to return `None` if `T` does *not* implement the requested trait, but
975/// it is never guaranteed to return `Some`. It is intended  to be used for performance
976/// optimizations and debugging, and `try_as_dyn` succeeding for a particular type should never be
977/// relied upon for correctness (i.e. callers must behave correctly even if `try_as_dyn` spuriously
978/// returns `None`).
979///
980/// </div>
981///
982/// # Examples of false negatives
983///
984/// Some examples of situations where `try_as_dyn::<T, dyn Trait>` returns `None` in practice even
985/// when `T` implements `Trait`:
986/// * `T`'s impl for `Trait` is lifetime-dependent
987/// * `T`'s impl for `Trait` is a builtin impl (e.g. `dyn Debug` implements `Debug`)
988/// * `T`'s impl for `Trait` has a trait bound which requires transitively reasoning about
989/// lifetime-dependent or builtin impls
990///
991/// This list is not exhaustive. There is some detailed documentation about these limitations at
992/// <https://doc.rust-lang.org/unstable-book/library-features/try-as-dyn.html> But the gist is
993/// summarized below:
994///
995/// ## Lifetime-dependent impls
996///
997/// `try_as_dyn` does not have access to lifetime information, thus it cannot differentiate between
998/// `'static` and other lifetimes and cannot reason about outlives bounds on impls. Thus it cannot
999/// reason about impls that have `'static` lifetimes or outlives bounds of any kind.
1000///
1001/// The following impls are lifetime-dependent and produce false negatives when used with
1002/// `try_as_dyn`:
1003///
1004/// ```rust
1005/// # trait Trait<'a, T> {}
1006/// # struct Type<'b, U>(&'b U);
1007/// # use std::fmt::{Debug, Display};
1008/// // impl mentions a 'static lifetime
1009/// impl<'a, T: Debug, U: Display> Trait<'a, T> for Type<'static, U> {}
1010/// ```
1011///
1012/// ```
1013/// # trait Trait<'a, T> {}
1014/// # struct Type<'b, U>(&'b U);
1015/// # use std::fmt::{Debug, Display};
1016/// // impl contains an outlives bound
1017/// impl<'a, 'b, T: Debug, U: Display> Trait<'a, T> for Type<'b, U>
1018///     where 'b: 'a {}
1019/// ```
1020///
1021/// Impls that mention a generic parameter more than once are lifetime-dependent and produce false
1022/// negatives, even if they don't expressly mention any lifetimes:
1023///
1024/// ```rust
1025/// # trait Trait<T> {}
1026/// // impl mentions T more than once, creating an implied lifetime dependence
1027/// impl<T> Trait<T> for T {}
1028/// ```
1029///
1030/// The following impl is lifetime-**independent**, because even though it *mentions* lifetimes,
1031/// implementation of the trait is not *conditional* over the lifetimes:
1032/// ```rust
1033/// # trait Trait<'a, T> {}
1034/// # struct Type<'b, U>(&'b U);
1035/// # use std::fmt::{Debug, Display};
1036/// impl<'a, 'b, T: Debug, U: Display> Trait<'a, T> for Type<'b, U> {}
1037/// ```
1038///
1039/// Impls without generic parameters at all are also lifetime-independent, as long as they contain
1040/// no `'static` lifetimes.
1041///
1042/// ## Builtin impls
1043///
1044/// Builtin impls (like `impl Debug for dyn Debug`, or automatic implementations of `Send` and
1045/// `Sync`) have various obscure rules and often are not fully generic. To simplify reasoning about
1046/// what is allowed and what not, all builtin impls are rejected and will neither directly nor
1047/// indirectly contribute to a `Some` result.
1048///
1049/// # Compile-time failures
1050/// Determining whether `T` can be coerced to the dyn trait type `U` requires compiler trait resolution.
1051/// In some cases, that resolution can exceed the recursion limit,
1052/// and compilation will fail instead of this function returning `None`.
1053///
1054/// The input type `T` must outlive the lifetime `'a` on the `dyn Trait + 'a`.
1055/// This is basically the same rule that forbids `let x: &dyn Trait + 'static = &&some_local_variable;`
1056/// So if you see borrow check errors around `try_as_dyn`, think about whether a normal unsizing
1057/// coercion would be possible at all if you were using concrete types or had bounds on the input type.
1058///
1059/// # Examples
1060///
1061/// Using `try_as_dyn` to use bytewise comparison instead of PartialEq for certain types, similar to
1062/// the standard library's optimization for slices:
1063///
1064/// ```rust
1065/// #![feature(try_as_dyn)]
1066///
1067/// use core::any::try_as_dyn;
1068///
1069/// /// Compares two objects for equality,
1070/// fn eq<T: PartialEq + ?Sized>(x: &T, y: &T) -> bool {
1071///     if try_as_dyn::<T, dyn BytewiseEq>(&x).is_some() {
1072///         // T implements BytewiseEq, so we cast the slices to u8 and compare their bytes
1073///         // instead of calling PartialEq on each individual element.
1074///         unsafe {
1075///             // SAFETY: x and y are valid for reads of size_of::<T>() bytes
1076///             // BytewiseEq trait guarantees we can interperet these bytes as u8's
1077///             // and compare them for equality
1078///             let x = &*core::ptr::slice_from_raw_parts(
1079///                 (&raw const *x).cast::<u8>(),
1080///                 core::mem::size_of_val(x),
1081///             );
1082///             let y = &*core::ptr::slice_from_raw_parts(
1083///                 (&raw const *y).cast::<u8>(),
1084///                 core::mem::size_of_val(y),
1085///             );
1086///
1087///             x == y
1088///         }
1089///     } else {
1090///         // T does not implement BytewiseEq, or try_as_dyn returned a false negative.
1091///         // Fallback to PartialEq.
1092///         //
1093///         // BytewiseEq guarantees bytewise comparison and PartialEq will produce the same
1094///         // results, so our code behaves correctly if try_as_dyn produces false negatives.
1095///         x == y
1096///     }
1097/// }
1098///
1099/// /// Marker trait for types that can be compared for equality
1100/// /// using a bytewise comparison (i.e. memcmp).
1101/// ///
1102/// /// Implementations must ensure the type contains no uninitialized bytes,
1103/// /// and that a bytewise comparison will produce the same result as PartialEq.
1104/// unsafe trait BytewiseEq {}
1105///
1106/// unsafe impl BytewiseEq for u8 {}
1107/// unsafe impl BytewiseEq for u16 {}
1108/// unsafe impl BytewiseEq for u32 {}
1109///
1110/// // u16 implements BytewiseEq, so eq::<u16> will use bytewise comparison
1111/// // (unless try_as_dyn returns a false negative)
1112/// assert!(eq(&5u16, &5u16));
1113///
1114/// // f32 does not implement BytewiseEq, so eq::<f32> will use element-wise comparison
1115/// assert!(eq(&5f32, &5f32));
1116/// ```
1117///
1118/// Using `try_as_dyn` for debugging:
1119///
1120/// ```rust
1121/// #![feature(try_as_dyn)]
1122///
1123/// use core::any::{try_as_dyn, type_name};
1124/// use core::fmt::Debug;
1125///
1126/// /// Prints a value of type T, attempting to use its Debug implementation with try_as_dyn.
1127/// fn debug_println<T: ?Sized>(x: &T) {
1128///     if let Some(debug) = try_as_dyn::<T, dyn Debug>(x) {
1129///         println!("{:?}", debug);
1130///     } else {
1131///         // T does not implement Debug, or try_as_dyn returned a false negative.
1132///         // Print the name of the type instead.
1133///         //
1134///         // We're not relying on this for correctness; it's just for debugging,
1135///         // so we can tolerate false negatives.
1136///         println!("<{}>", type_name::<T>());
1137///     }
1138/// }
1139///
1140/// /// This type does not implement Debug.
1141/// struct NoDebug;
1142///
1143/// // Prints "Hello, world!" unless try_as_dyn returns a false negative.
1144/// debug_println(&"Hello, world!");
1145///
1146/// // Prints the name of the type, since it does not have a Debug implementation.
1147/// debug_println(&NoDebug);
1148///
1149/// // The current implementation of try_as_dyn gives a false positive in this case!
1150/// debug_println(&"Hello, world!" as &dyn Debug);
1151/// ```
1152#[must_use]
1153#[unstable(feature = "try_as_dyn", issue = "144361")]
1154pub const fn try_as_dyn<'a, T: ?Sized + 'a, U: TryAsDynCompatible<'a> + ?Sized>(
1155    t: &T,
1156) -> Option<&U> {
1157    // For unsized `T`, `trait_info_of` always returns `None` (vtable lookup is
1158    // only supported for sized types). The function therefore unconditionally
1159    // returns `None` in that case.
1160    let vtable: Option<ptr::DynMetadata<U>> =
1161        const { type_id::<T>().trait_info_of::<U>().as_ref().map(TraitImpl::get_vtable) };
1162    match vtable {
1163        Some(dyn_metadata) => {
1164            let pointer = ptr::from_raw_parts(t as *const T as *const (), dyn_metadata);
1165            // SAFETY: `t` is a reference to a type, so we know it is valid.
1166            // `dyn_metadata` is a vtable for T, implementing the trait of `U`.
1167            // `T` is sized here because `trait_info_of` only returns `Some` for sized types,
1168            // so the thin data pointer fully describes the value.
1169            Some(unsafe { &*pointer })
1170        }
1171        None => None,
1172    }
1173}
1174
1175/// Returns `Some(&mut U)` if `T` can be coerced to the dyn trait type `U`. Otherwise, it returns `None`.
1176///
1177/// See documentation of [try_as_dyn] for details about the behaviour and limitations.
1178#[must_use]
1179#[unstable(feature = "try_as_dyn", issue = "144361")]
1180pub const fn try_as_dyn_mut<'a, T: ?Sized + 'a, U: TryAsDynCompatible<'a> + ?Sized>(
1181    t: &mut T,
1182) -> Option<&mut U> {
1183    // For unsized `T`, `trait_info_of` always returns `None` (vtable lookup is
1184    // only supported for sized types). The function therefore unconditionally
1185    // returns `None` in that case.
1186    let vtable: Option<ptr::DynMetadata<U>> =
1187        const { type_id::<T>().trait_info_of::<U>().as_ref().map(TraitImpl::get_vtable) };
1188    match vtable {
1189        Some(dyn_metadata) => {
1190            let pointer = ptr::from_raw_parts_mut(t as *mut T as *mut (), dyn_metadata);
1191            // SAFETY: `t` is a reference to a type, so we know it is valid.
1192            // `dyn_metadata` is a vtable for T, implementing the trait of `U`.
1193            // `T` is sized here because `trait_info_of` only returns `Some` for sized types,
1194            // so the thin data pointer fully describes the value.
1195            Some(unsafe { &mut *pointer })
1196        }
1197        None => None,
1198    }
1199}