#[derive(Clone, Copy, Debug)]
pub(crate) struct HashChain {
h1: u64,
h2: u64,
}
impl HashChain {
#[inline(always)]
pub(crate) fn new(hash: u64) -> Self {
Self {
h1: hash,
h2: (hash >> 32).wrapping_mul(0x51_7c_c1_b7_27_22_0a_95),
}
}
#[inline(always)]
pub(crate) fn next(&mut self) -> u64 {
self.h1 = self.h1.wrapping_add(self.h2).rotate_left(5);
self.h1
}
}
#[inline(always)]
pub(crate) fn index(words: u64, hash: u64) -> u64 {
((hash >> 32) * words) >> 26
}
#[inline(always)]
pub(crate) fn set(words: &mut [u64], bit: u64) {
words[(bit >> 6) as usize] |= 1u64 << (bit & 63);
}
#[inline(always)]
pub(crate) fn test(words: &[u64], bit: u64) -> bool {
(words[(bit >> 6) as usize] >> (bit & 63)) & 1 == 1
}
#[cfg(test)]
mod tests {
use super::{HashChain, index};
const GOLDEN_RATIO_64: u64 = 0x9E37_79B9_7F4A_7C15;
#[test]
fn schedule_matches_fastbloom() {
for (words, hashes) in [(1usize, 1u32), (64, 3), (1_000, 7), (29_954, 13)] {
let mut ours = vec![0u64; words];
let mut theirs = fastbloom::BloomFilter::from_vec(vec![0u64; words])
.seed(&0)
.hashes(hashes);
for i in 0..5_000u64 {
let hash = i.wrapping_mul(GOLDEN_RATIO_64) ^ (i >> 7);
let mut chain = HashChain::new(hash);
for _ in 0..hashes {
super::set(&mut ours, index(words as u64, chain.next()));
}
theirs.insert_hash(hash);
}
assert_eq!(
ours.as_slice(),
theirs.as_slice(),
"schedule diverges from fastbloom at {words} words, {hashes} hashes"
);
}
}
#[test]
fn index_matches_fastbloom_below_its_wrap() {
for words in [1u64, 64, 1 << 14, 1 << 25, 1 << 26] {
let bits = words * 64;
for i in 0..200_000u64 {
let hash = i.wrapping_mul(GOLDEN_RATIO_64);
let original = ((hash >> 32).wrapping_mul(bits)) >> 32;
assert_eq!(index(words, hash), original, "diverged at {bits} bits");
}
}
}
#[test]
fn index_reaches_bits_fastbloom_cannot() {
let words = 1u64 << 28;
let bits = words * 64;
let reachable = (0..200_000u64)
.map(|i| {
let hash = i.wrapping_mul(GOLDEN_RATIO_64);
index(words, hash)
})
.max()
.unwrap();
assert!(
reachable > bits / 2,
"index only reached {reachable} of {bits} bits"
);
let original_reach = (0..200_000u64)
.map(|i| {
let hash = i.wrapping_mul(GOLDEN_RATIO_64);
((hash >> 32).wrapping_mul(bits)) >> 32
})
.max()
.unwrap();
assert!(
original_reach < bits / 2,
"the 64-bit form was expected to lose the upper half, reached {original_reach}"
);
}
}