use std::collections::{BTreeMap, HashMap};
use std::hash::{BuildHasherDefault, Hasher};
#[derive(Default)]
pub(crate) struct NameHasher(u64);
impl Hasher for NameHasher {
fn write(&mut self, bytes: &[u8]) {
let mut h = if self.0 == 0 { 0xcbf2_9ce4_8422_2325 } else { self.0 };
for &b in bytes {
h = (h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3);
}
self.0 = h;
}
fn finish(&self) -> u64 {
self.0
}
}
pub(crate) struct Interner<T> {
index: HashMap<String, usize, BuildHasherDefault<NameHasher>>,
names: Vec<String>,
slots: Vec<T>,
}
impl<T: Default> Interner<T> {
pub(crate) fn new() -> Self {
Self {
index: HashMap::default(),
names: Vec::new(),
slots: Vec::new(),
}
}
pub(crate) fn slot(&mut self, name: &str) -> &mut T {
let at = match self.index.get(name) {
Some(&at) => at,
None => {
let at = self.slots.len();
self.index.insert(name.to_string(), at);
self.names.push(name.to_string());
self.slots.push(T::default());
at
}
};
&mut self.slots[at]
}
pub(crate) fn into_map(self) -> BTreeMap<String, T> {
self.names.into_iter().zip(self.slots).collect()
}
}