use super::Kind;
#[derive(Clone, Copy)]
struct Entry {
prefix: u64,
suffix_and_len: u32,
kind: Kind,
}
const HASH_SEED: u64 = 17_825_894_737_173_976_417;
const fn slot(prefix: u64, suffix_and_len: u32) -> usize {
((prefix ^ ((suffix_and_len as u64) << 21)).wrapping_mul(HASH_SEED) >> 55) as usize
}
static TABLE: [Entry; 512] = {
let mut table = [Entry { prefix: 0, suffix_and_len: 0, kind: Kind::Ident }; 512];
let mut index = 0;
while index < Kind::VARIANTS.len() {
let kind = Kind::VARIANTS[index];
index += 1;
if !kind.is_any_keyword() {
continue;
}
let bytes = kind.to_str().as_bytes();
assert!(bytes.len() >= 2 && bytes.len() <= 11);
let mut prefix = [0; 8];
let mut suffix_and_len = [0; 4];
#[expect(clippy::cast_possible_truncation)]
let len = bytes.len() as u8;
suffix_and_len[3] = len;
let mut byte_index = 0;
while byte_index < bytes.len() {
if byte_index < 8 {
prefix[byte_index] = bytes[byte_index];
} else {
suffix_and_len[byte_index - 8] = bytes[byte_index];
}
byte_index += 1;
}
let prefix = u64::from_le_bytes(prefix);
let suffix_and_len = u32::from_le_bytes(suffix_and_len);
let slot = slot(prefix, suffix_and_len);
assert!(matches!(table[slot].kind, Kind::Ident), "keyword hash collision");
table[slot] = Entry { prefix, suffix_and_len, kind };
}
table
};
#[expect(clippy::inline_always)]
#[inline(always)]
pub(super) fn match_keyword(bytes: &[u8]) -> Kind {
let len = bytes.len();
if !(2..12).contains(&len) {
return Kind::Ident;
}
let (prefix, suffix) = unsafe {
let ptr = bytes.as_ptr();
if len <= 4 {
let first = u64::from(u16::from_le(ptr.cast::<u16>().read_unaligned()));
let last = u64::from(u16::from_le(ptr.add(len - 2).cast::<u16>().read_unaligned()));
(first | (last << ((len - 2) * 8)), 0)
} else if len <= 8 {
let first = u64::from(u32::from_le(ptr.cast::<u32>().read_unaligned()));
let last = u64::from(u32::from_le(ptr.add(len - 4).cast::<u32>().read_unaligned()));
(first | (last << ((len - 4) * 8)), 0)
} else {
let first = u64::from_le(ptr.cast::<u64>().read_unaligned());
let last = u32::from_le(ptr.add(len - 4).cast::<u32>().read_unaligned());
(first, last >> ((12 - len) * 8))
}
};
#[expect(clippy::cast_possible_truncation)]
let suffix_and_len = suffix | ((len as u32) << 24);
let entry = TABLE[slot(prefix, suffix_and_len)];
if entry.prefix == prefix && entry.suffix_and_len == suffix_and_len {
entry.kind
} else {
Kind::Ident
}
}