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