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