use std::collections::HashSet;
use std::hash::{BuildHasherDefault, Hasher};
pub(crate) const HASH_THRESHOLD: usize = 32;
const FNV_SEED: u64 = 0x51_7c_c1_b7_27_22_0a_95;
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct FxHasher {
hash: u64,
}
impl FxHasher {
#[inline]
fn add(&mut self, word: u64) {
self.hash = (self.hash.rotate_left(5) ^ word).wrapping_mul(FNV_SEED);
}
}
impl Hasher for FxHasher {
#[inline]
fn finish(&self) -> u64 {
self.hash
}
#[inline]
fn write(&mut self, bytes: &[u8]) {
let mut chunks = bytes.chunks_exact(8);
for chunk in &mut chunks {
let mut buf = [0u8; 8];
buf.copy_from_slice(chunk);
self.add(u64::from_le_bytes(buf));
}
let rest = chunks.remainder();
if !rest.is_empty() {
let mut buf = [0u8; 8];
buf[..rest.len()].copy_from_slice(rest);
self.add(u64::from_le_bytes(buf));
}
}
#[inline]
fn write_u32(&mut self, n: u32) {
self.add(u64::from(n));
}
#[inline]
fn write_u64(&mut self, n: u64) {
self.add(n);
}
#[inline]
fn write_usize(&mut self, n: usize) {
self.add(n as u64);
}
}
type FxBuild = BuildHasherDefault<FxHasher>;
#[derive(Debug)]
pub(crate) enum ConstSet {
StrSorted(Box<[Box<str>]>),
StrHash(HashSet<Box<str>, FxBuild>),
IntSorted(Box<[i64]>),
IntHash(HashSet<i64, FxBuild>),
NumSorted(Box<[f64]>),
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum Probe<'a> {
Str(&'a str),
Num(f64),
Other,
}
impl ConstSet {
pub(crate) fn from_strs(mut items: Vec<Box<str>>) -> Self {
items.sort_unstable();
if items.len() >= HASH_THRESHOLD {
ConstSet::StrHash(items.into_iter().collect())
} else {
ConstSet::StrSorted(items.into_boxed_slice())
}
}
pub(crate) fn from_ints(mut items: Vec<i64>) -> Self {
items.sort_unstable();
if items.len() >= HASH_THRESHOLD {
ConstSet::IntHash(items.into_iter().collect())
} else {
ConstSet::IntSorted(items.into_boxed_slice())
}
}
pub(crate) fn from_nums(mut items: Vec<f64>) -> Self {
items.sort_unstable_by(f64::total_cmp);
ConstSet::NumSorted(items.into_boxed_slice())
}
pub(crate) fn contains(&self, probe: Probe<'_>) -> bool {
match (self, probe) {
(ConstSet::StrSorted(set), Probe::Str(s)) => {
set.binary_search_by(|item| (**item).cmp(s)).is_ok()
}
(ConstSet::StrHash(set), Probe::Str(s)) => set.contains(s),
(ConstSet::IntSorted(set), Probe::Num(n)) => {
int_of(n).is_some_and(|i| set.binary_search(&i).is_ok())
}
(ConstSet::IntHash(set), Probe::Num(n)) => int_of(n).is_some_and(|i| set.contains(&i)),
(ConstSet::NumSorted(set), Probe::Num(n)) => {
let hit = |k: f64| set.binary_search_by(|item| item.total_cmp(&k)).is_ok();
hit(n) || (n == 0.0 && (hit(0.0) || hit(-0.0)))
}
_ => false,
}
}
}
fn int_of(n: f64) -> Option<i64> {
if n.is_finite() && n.fract() == 0.0 && n >= -2f64.powi(63) && n < 2f64.powi(63) {
Some(n as i64)
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn str_sorted_hits_misses() {
let set = ConstSet::from_strs(vec!["b".into(), "a".into(), "c".into()]);
assert!(set.contains(Probe::Str("a")));
assert!(set.contains(Probe::Str("c")));
assert!(!set.contains(Probe::Str("d")));
assert!(!set.contains(Probe::Num(1.0)));
assert!(!set.contains(Probe::Other));
}
#[test]
fn int_sorted_hits_misses() {
let set = ConstSet::from_ints(vec![30, 22, 26, 28]);
assert!(set.contains(Probe::Num(22.0)));
assert!(set.contains(Probe::Num(30.0)));
assert!(!set.contains(Probe::Num(23.0)));
assert!(!set.contains(Probe::Num(22.5)));
assert!(!set.contains(Probe::Str("22")));
}
#[test]
fn large_sets_switch_to_hash() {
let strs: Vec<Box<str>> = (0..40).map(|i| format!("k{i}").into()).collect();
let set = ConstSet::from_strs(strs);
assert!(matches!(set, ConstSet::StrHash(_)));
assert!(set.contains(Probe::Str("k39")));
assert!(!set.contains(Probe::Str("k40")));
let ints: Vec<i64> = (0..64).collect();
let set = ConstSet::from_ints(ints);
assert!(matches!(set, ConstSet::IntHash(_)));
assert!(set.contains(Probe::Num(63.0)));
assert!(!set.contains(Probe::Num(64.0)));
}
#[test]
fn float_set_compares_by_total_order() {
let set = ConstSet::from_nums(vec![1.5, -0.25]);
assert!(set.contains(Probe::Num(1.5)));
assert!(set.contains(Probe::Num(-0.25)));
assert!(!set.contains(Probe::Num(0.25)));
}
#[test]
fn large_int_beyond_f64_precision() {
let set = ConstSet::from_ints(vec![9_007_199_254_740_993]);
assert!(!set.contains(Probe::Num(9_007_199_254_740_993.0)));
}
#[test]
fn signed_zero_is_same_value() {
let pos = ConstSet::from_nums(vec![1.5, 0.0]);
assert!(pos.contains(Probe::Num(-0.0)));
assert!(pos.contains(Probe::Num(0.0)));
let neg = ConstSet::from_nums(vec![1.5, -0.0]);
assert!(neg.contains(Probe::Num(0.0)));
assert!(neg.contains(Probe::Num(-0.0)));
}
}