use std::any::TypeId;
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
#[derive(Clone, Copy, Eq)]
pub struct Key {
type_id: TypeId,
hash: u64,
label: &'static str,
}
impl Key {
pub fn of<T: Hash + 'static>(value: &T) -> Self {
Self::new(TypeId::of::<T>(), value, std::any::type_name::<T>())
}
fn new<T: Hash + ?Sized>(type_id: TypeId, value: &T, label: &'static str) -> Self {
let mut hasher = DefaultHasher::new();
value.hash(&mut hasher);
Self {
type_id,
hash: hasher.finish(),
label,
}
}
}
impl From<&'static str> for Key {
fn from(name: &'static str) -> Self {
Self::new(TypeId::of::<&'static str>(), &name, name)
}
}
impl PartialEq for Key {
fn eq(&self, other: &Self) -> bool {
self.type_id == other.type_id && self.hash == other.hash
}
}
impl Hash for Key {
fn hash<H: Hasher>(&self, hasher: &mut H) {
self.type_id.hash(hasher);
self.hash.hash(hasher);
}
}
impl fmt::Debug for Key {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "Key({})", self.label)
}
}