use std::sync::OnceLock;
pub fn fnv1a64_hex(data: &[u8]) -> String {
const OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
const PRIME: u64 = 0x0000_0100_0000_01b3;
let mut h = OFFSET;
for &b in data {
h ^= b as u64;
h = h.wrapping_mul(PRIME);
}
format!("{h:016x}")
}
pub fn crc16(data: &[u8]) -> u16 {
let mut crc: u16 = 0;
for &b in data {
crc ^= (b as u16) << 8;
for _ in 0..8 {
crc = if crc & 0x8000 != 0 {
(crc << 1) ^ 0x1021
} else {
crc << 1
};
}
}
crc
}
pub fn effective_tag(key: &[u8]) -> Option<&[u8]> {
let start = key.iter().position(|&b| b == b'{')?;
let end_rel = key[start + 1..].iter().position(|&b| b == b'}')?;
if end_rel == 0 {
return None;
}
Some(&key[start + 1..start + 1 + end_rel])
}
pub fn redis_slot(key: &[u8]) -> u16 {
let hashed = effective_tag(key).unwrap_or(key);
crc16(hashed) % 16384
}
fn synthetic_table() -> &'static Vec<String> {
static TABLE: OnceLock<Vec<String>> = OnceLock::new();
TABLE.get_or_init(|| {
let mut table: Vec<Option<String>> = vec![None; 16384];
let mut remaining = 16384usize;
let mut counter: u64 = 0;
while remaining > 0 {
let tag = format!("t{counter:x}");
let slot = (crc16(tag.as_bytes()) % 16384) as usize;
if table[slot].is_none() {
table[slot] = Some(tag);
remaining -= 1;
}
counter += 1;
}
table
.into_iter()
.map(|t| t.expect("synthetic 表全覆盖"))
.collect()
})
}
pub fn synthetic_tag(slot: u16) -> &'static str {
&synthetic_table()[(slot % 16384) as usize]
}
pub fn derive_same_slot_key(source: &[u8], suffix: &str) -> Vec<u8> {
let tag: &[u8] = match effective_tag(source) {
Some(t) => t,
None => synthetic_tag(redis_slot(source)).as_bytes(),
};
let mut out = Vec::with_capacity(tag.len() + suffix.len() + 3);
out.push(b'{');
out.extend_from_slice(tag);
out.push(b'}');
out.push(b':');
out.extend_from_slice(suffix.as_bytes());
out
}