use crate::kernel::ExprId;
use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};
pub(crate) type IdMap<V> = HashMap<ExprId, V, BuildHasherDefault<IdHasher>>;
#[derive(Default, Clone, Copy)]
pub(crate) struct IdHasher(u64);
impl Hasher for IdHasher {
#[inline]
fn finish(&self) -> u64 {
self.0
}
#[inline]
fn write_u32(&mut self, n: u32) {
let h = (self.0 ^ u64::from(n)).wrapping_mul(0x9E37_79B9_7F4A_7C15);
self.0 = h ^ (h >> 32);
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
for &b in bytes {
self.write_u32(u32::from(b));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::kernel::{Domain, ExprPool};
#[test]
fn id_map_round_trips_many_ids() {
let pool = ExprPool::new();
let ids: Vec<ExprId> = (0..2000)
.map(|i| pool.symbol(format!("v{i}"), Domain::Real))
.collect();
let mut m: IdMap<usize> = IdMap::default();
for (i, &id) in ids.iter().enumerate() {
m.insert(id, i);
}
assert_eq!(m.len(), ids.len());
for (i, id) in ids.iter().enumerate() {
assert_eq!(m[id], i);
}
}
}