intuicio_data/
type_hash.rs

1use rustc_hash::FxHasher;
2use std::{
3    cmp::Ordering,
4    hash::{Hash, Hasher},
5};
6
7#[derive(Debug, Copy, Clone)]
8pub struct TypeHash {
9    hash: u64,
10    #[cfg(feature = "typehash_debug_name")]
11    name: Option<&'static str>,
12}
13
14impl Default for TypeHash {
15    fn default() -> Self {
16        Self::INVALID
17    }
18}
19
20impl TypeHash {
21    pub const INVALID: Self = Self {
22        hash: 0,
23        #[cfg(feature = "typehash_debug_name")]
24        name: None,
25    };
26
27    /// # Safety
28    pub unsafe fn raw(name: &str) -> Self {
29        let mut hasher = FxHasher::default();
30        name.hash(&mut hasher);
31        Self {
32            hash: hasher.finish(),
33            #[cfg(feature = "typehash_debug_name")]
34            name: None,
35        }
36    }
37
38    /// # Safety
39    pub unsafe fn raw_static(name: &'static str) -> Self {
40        let mut hasher = FxHasher::default();
41        name.hash(&mut hasher);
42        Self {
43            hash: hasher.finish(),
44            #[cfg(feature = "typehash_debug_name")]
45            name: Some(name),
46        }
47    }
48
49    pub fn of<T: ?Sized>() -> Self {
50        let name = std::any::type_name::<T>();
51        let mut hasher = FxHasher::default();
52        name.hash(&mut hasher);
53        Self {
54            hash: hasher.finish(),
55            #[cfg(feature = "typehash_debug_name")]
56            name: Some(name),
57        }
58    }
59
60    pub fn is_valid(&self) -> bool {
61        self.hash != Self::INVALID.hash
62    }
63
64    pub fn hash(&self) -> u64 {
65        self.hash
66    }
67
68    #[cfg(feature = "typehash_debug_name")]
69    pub fn name(&self) -> Option<&'static str> {
70        self.name
71    }
72}
73
74impl PartialEq for TypeHash {
75    fn eq(&self, other: &Self) -> bool {
76        self.hash == other.hash
77    }
78}
79
80impl Eq for TypeHash {}
81
82impl PartialOrd for TypeHash {
83    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
84        Some(self.cmp(other))
85    }
86}
87
88impl Ord for TypeHash {
89    fn cmp(&self, other: &Self) -> Ordering {
90        self.hash.cmp(&other.hash)
91    }
92}
93
94impl Hash for TypeHash {
95    fn hash<H: Hasher>(&self, state: &mut H) {
96        self.hash.hash(state);
97    }
98}
99
100impl std::fmt::Display for TypeHash {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        #[cfg(feature = "typehash_debug_name")]
103        {
104            if let Some(name) = self.name {
105                return write!(f, "#{:X}: {}", self.hash, name);
106            }
107        }
108        write!(f, "#{:X}", self.hash)
109    }
110}