1use std::any::{Any, TypeId};
4use std::fmt::{self, Debug};
5use std::hash::{Hash, Hasher};
6use std::sync::atomic::{AtomicU64, Ordering};
7
8pub trait Key: Any + Debug {
28 fn eq_key(&self, other: &dyn Key) -> bool;
31
32 fn hash_key(&self, state: &mut dyn Hasher);
35}
36
37impl PartialEq for dyn Key {
38 fn eq(&self, other: &dyn Key) -> bool {
39 self.eq_key(other)
40 }
41}
42
43impl Eq for dyn Key {}
44
45impl Hash for dyn Key {
46 fn hash<H: Hasher>(&self, state: &mut H) {
47 self.hash_key(state);
48 }
49}
50
51impl dyn Key {
52 #[expect(
58 clippy::new_ret_no_self,
59 reason = "Dart's Key factory returns ValueKey<String>, not the trait object"
60 )]
61 pub fn new(value: impl Into<String>) -> ValueKey<String> {
62 ValueKey::new(value.into())
63 }
64}
65
66pub trait LocalKey: Key {}
71
72#[derive(Clone, Copy, PartialEq, Eq, Hash)]
77pub struct UniqueKey {
78 id: u64,
79}
80
81impl UniqueKey {
82 #[expect(
84 clippy::new_without_default,
85 reason = "each call creates a distinct key; Default would suggest a neutral value"
86 )]
87 pub fn new() -> UniqueKey {
88 static NEXT: AtomicU64 = AtomicU64::new(0);
89 UniqueKey {
90 id: NEXT.fetch_add(1, Ordering::Relaxed),
91 }
92 }
93}
94
95impl Key for UniqueKey {
96 fn eq_key(&self, other: &dyn Key) -> bool {
97 (other as &dyn Any)
98 .downcast_ref::<UniqueKey>()
99 .is_some_and(|other| other.id == self.id)
100 }
101
102 fn hash_key(&self, mut state: &mut dyn Hasher) {
103 TypeId::of::<UniqueKey>().hash(&mut state);
104 self.id.hash(&mut state);
105 }
106}
107
108impl LocalKey for UniqueKey {}
109
110impl Debug for UniqueKey {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 write!(f, "[#{:05x}]", self.id & 0xF_FFFF)
113 }
114}
115
116#[derive(Clone, PartialEq, Eq, Hash)]
144pub struct ValueKey<T> {
145 pub value: T,
147}
148
149impl<T> ValueKey<T> {
150 pub const fn new(value: T) -> ValueKey<T> {
152 ValueKey { value }
153 }
154}
155
156impl<T: PartialEq + Hash + Debug + 'static> Key for ValueKey<T> {
157 fn eq_key(&self, other: &dyn Key) -> bool {
158 (other as &dyn Any)
159 .downcast_ref::<ValueKey<T>>()
160 .is_some_and(|other| other.value == self.value)
161 }
162
163 fn hash_key(&self, mut state: &mut dyn Hasher) {
164 TypeId::of::<ValueKey<T>>().hash(&mut state);
165 self.value.hash(&mut state);
166 }
167}
168
169impl<T: PartialEq + Hash + Debug + 'static> LocalKey for ValueKey<T> {}
170
171impl<T: Debug + 'static> Debug for ValueKey<T> {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 let value = &self.value as &dyn Any;
175 if let Some(text) = value.downcast_ref::<String>() {
176 write!(f, "[<'{text}'>]")
177 } else if let Some(text) = value.downcast_ref::<&str>() {
178 write!(f, "[<'{text}'>]")
179 } else {
180 write!(f, "[<{:?}>]", self.value)
181 }
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use std::collections::HashMap;
188 use std::sync::Arc;
189
190 use super::*;
191
192 #[derive(Debug, PartialEq, Eq, Hash)]
193 struct SaltedKey(ValueKey<u32>);
194
195 impl Key for SaltedKey {
196 fn eq_key(&self, other: &dyn Key) -> bool {
197 (other as &dyn Any)
198 .downcast_ref::<SaltedKey>()
199 .is_some_and(|other| other.0 == self.0)
200 }
201
202 fn hash_key(&self, mut state: &mut dyn Hasher) {
203 TypeId::of::<SaltedKey>().hash(&mut state);
204 self.0.hash(&mut state);
205 }
206 }
207
208 impl LocalKey for SaltedKey {}
209
210 fn erase(key: impl Key) -> Arc<dyn Key> {
211 Arc::new(key)
212 }
213
214 #[test]
215 fn value_keys_are_equal_when_their_values_are() {
216 assert_eq!(&*erase(ValueKey::new(3)), &*erase(ValueKey::new(3)));
217 assert_ne!(&*erase(ValueKey::new(3)), &*erase(ValueKey::new(4)));
218 assert_eq!(
219 &*erase(ValueKey::new("a".to_owned())),
220 &*erase(ValueKey::new("a".to_owned()))
221 );
222 }
223
224 #[test]
225 fn value_keys_of_different_types_are_never_equal() {
226 assert_ne!(&*erase(ValueKey::new(3u32)), &*erase(ValueKey::new(3u64)));
227 assert_ne!(
228 &*erase(ValueKey::new(3u32)),
229 &*erase(SaltedKey(ValueKey::new(3)))
230 );
231 }
232
233 #[test]
234 fn unique_keys_are_equal_only_to_themselves() {
235 let key = UniqueKey::new();
236 assert_eq!(&*erase(key), &*erase(key));
237 assert_ne!(&*erase(UniqueKey::new()), &*erase(UniqueKey::new()));
238 }
239
240 #[test]
241 fn keys_of_different_types_share_one_map() {
242 let mut elements: HashMap<Arc<dyn Key>, &str> = HashMap::new();
243 elements.insert(erase(ValueKey::new(3u32)), "value");
244 elements.insert(erase(SaltedKey(ValueKey::new(3))), "salted");
245
246 assert_eq!(elements.len(), 2);
247 assert_eq!(elements.get(&erase(ValueKey::new(3u32))), Some(&"value"));
248 assert_eq!(
249 elements.get(&erase(SaltedKey(ValueKey::new(3)))),
250 Some(&"salted")
251 );
252 }
253
254 #[test]
255 fn debug_matches_flutter_to_string() {
256 assert_eq!(format!("{:?}", ValueKey::new(3)), "[<3>]");
257 assert_eq!(format!("{:?}", ValueKey::new("a")), "[<'a'>]");
258 assert_eq!(format!("{:?}", ValueKey::new("a".to_string())), "[<'a'>]");
259 assert_eq!(format!("{:?}", UniqueKey { id: 0x1_2345 }), "[#12345]");
260 assert_eq!(format!("{:?}", UniqueKey { id: 0x7 }), "[#00007]");
261 }
262
263 #[test]
264 fn dyn_key_new_is_a_string_value_key() {
265 assert_eq!(
266 &*erase(<dyn Key>::new("x")),
267 &*erase(ValueKey::new("x".to_owned()))
268 );
269 }
270}