| 1 |
use crate::{math::*, AtomicBloomFilter, BloomFilter, BuildHasher, DefaultHasher}; |
| 2 |
use alloc::vec::Vec; |
| 3 |
use core::{cmp::max, f64::consts::LN_2, hash::Hash}; |
| 4 |
|
| 5 |
macro_rules! builder_with_bits { |
| 6 |
($name:ident, $($m:ident)?, $bloom:ident) => { |
| 7 |
/// A Bloom filter builder with an immutable number of bits. |
| 8 |
/// |
| 9 |
#[doc = concat!("This type can be used to construct an instance of [`", stringify!($bloom), "`] via the builder pattern.")] |
| 10 |
/// |
| 11 |
/// # Examples |
| 12 |
/// ``` |
| 13 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 14 |
/// |
| 15 |
#[doc = concat!("let builder = ", stringify!($bloom), "::with_num_bits(1024);")] |
| 16 |
#[doc = concat!("let builder = ", stringify!($bloom), "::from_vec(vec![0; 8]);")] |
| 17 |
/// ``` |
| 18 |
#[derive(Debug, Clone)] |
| 19 |
pub struct $name<S = DefaultHasher> { |
| 20 |
pub(crate) data: Vec<u64>, |
| 21 |
pub(crate) hasher: S, |
| 22 |
} |
| 23 |
|
| 24 |
impl<S: BuildHasher> PartialEq for $name<S> { |
| 25 |
fn eq(&self, other: &Self) -> bool { |
| 26 |
self.data == other.data |
| 27 |
} |
| 28 |
} |
| 29 |
impl<S: BuildHasher> Eq for $name<S> {} |
| 30 |
|
| 31 |
impl $name { |
| 32 |
/// Sets the seed for this builder. The later constructed Bloom filter |
| 33 |
/// will use this seed when hashing items. |
| 34 |
/// |
| 35 |
/// # Examples |
| 36 |
/// |
| 37 |
/// ``` |
| 38 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 39 |
/// |
| 40 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_num_bits(1024).seed(&1).hashes(4);")] |
| 41 |
/// ``` |
| 42 |
pub fn seed(mut self, seed: &u128) -> Self { |
| 43 |
self.hasher = DefaultHasher::seeded(&seed.to_be_bytes()); |
| 44 |
self |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
impl<S: BuildHasher> $name<S> { |
| 49 |
/// Sets the hasher for this builder. The later constructed Bloom filter will use |
| 50 |
/// this hasher when inserting and checking items. |
| 51 |
/// |
| 52 |
/// # Examples |
| 53 |
/// |
| 54 |
/// ``` |
| 55 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 56 |
/// use foldhash::fast::RandomState; |
| 57 |
/// |
| 58 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_num_bits(1024).hasher(RandomState::default()).hashes(4);")] |
| 59 |
/// ``` |
| 60 |
pub fn hasher<H: BuildHasher>(self, hasher: H) -> $name<H> { |
| 61 |
$name::<H> { |
| 62 |
data: self.data, |
| 63 |
hasher, |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
/// "Consumes" this builder, using the provided `num_hashes` to return an |
| 68 |
#[doc = concat!("empty [`", stringify!($bloom), "`].")] |
| 69 |
/// |
| 70 |
/// Note: if `num_hashes` is 0, it is treated as 1. Bloom filters with 0 |
| 71 |
/// hashes per item are practically useless, and disallowing this case |
| 72 |
/// enables further optimizations. |
| 73 |
/// |
| 74 |
/// # Examples |
| 75 |
/// ``` |
| 76 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 77 |
/// |
| 78 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_num_bits(1024).hashes(4);")] |
| 79 |
/// ``` |
| 80 |
pub fn hashes(self, num_hashes: u32) -> $bloom<S> { |
| 81 |
$bloom { |
| 82 |
bits: self.data.into_iter().collect(), |
| 83 |
num_hashes_minus_one: max(1, num_hashes) - 1, |
| 84 |
hasher: self.hasher, |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
/// "Consumes" this builder, using the provided `expected_items` to return an |
| 89 |
#[doc = concat!("empty [`", stringify!($bloom), "`]. The number of hashes is optimized based on `expected_items`")] |
| 90 |
#[doc = concat!("to maximize Bloom filter accuracy (minimize false positives chance on [`", stringify!($bloom), "::contains`]).")] |
| 91 |
/// More or less than `expected_items` may be inserted into Bloom filter. |
| 92 |
/// |
| 93 |
/// Note: `expected_items` will internally be set to 1 if 0 is specified. |
| 94 |
/// |
| 95 |
/// # Examples |
| 96 |
/// |
| 97 |
/// ``` |
| 98 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 99 |
/// |
| 100 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_num_bits(1024).expected_items(500);")] |
| 101 |
/// ``` |
| 102 |
pub fn expected_items(self, expected_items: usize) -> $bloom<S> { |
| 103 |
let expected_items = max(1, expected_items); |
| 104 |
let hashes = optimal_hashes(self.data.len() * 64, expected_items); |
| 105 |
self.hashes(hashes) |
| 106 |
} |
| 107 |
|
| 108 |
#[doc = concat!("\"Consumes\" this builder and constructs a [`", stringify!($bloom), "`] containing")] |
| 109 |
/// all values in `items`. The number of hashes per item |
| 110 |
/// is optimized based on `items.len()` to maximize Bloom filter accuracy |
| 111 |
#[doc = concat!("(minimize false positives chance on [`", stringify!($bloom), "::contains`]).")] |
| 112 |
/// |
| 113 |
/// # Examples |
| 114 |
/// |
| 115 |
/// ``` |
| 116 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 117 |
/// |
| 118 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_num_bits(1024).items([1, 2, 3].iter());")] |
| 119 |
/// ``` |
| 120 |
pub fn items<'a, H: Hash + 'a, I: IntoIterator<IntoIter = impl ExactSizeIterator<Item = &'a H>>>( |
| 121 |
self, |
| 122 |
items: I, |
| 123 |
) -> $bloom<S> { |
| 124 |
let into_iter = items.into_iter(); |
| 125 |
let $($m)? filter = self.expected_items(into_iter.len()); |
| 126 |
filter.insert_all(into_iter); |
| 127 |
filter |
| 128 |
} |
| 129 |
} |
| 130 |
}; |
| 131 |
} |
| 132 |
|
| 133 |
builder_with_bits!(BuilderWithBits, mut, BloomFilter); |
| 134 |
builder_with_bits!(AtomicBuilderWithBits, , AtomicBloomFilter); |
| 135 |
|
| 136 |
macro_rules! builder_with_fp { |
| 137 |
($name:ident, $($m:ident)?, $bloom:ident) => { |
| 138 |
/// A Bloom filter builder with an immutable false positive rate. |
| 139 |
/// |
| 140 |
/// This type can be used to construct an instance of [`BloomFilter`] via the builder pattern. |
| 141 |
/// |
| 142 |
/// # Examples |
| 143 |
/// |
| 144 |
/// ``` |
| 145 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 146 |
/// |
| 147 |
#[doc = concat!("let builder = ", stringify!($bloom), "::with_false_pos(0.01);")] |
| 148 |
/// ``` |
| 149 |
#[derive(Debug, Clone)] |
| 150 |
pub struct $name<S = DefaultHasher> { |
| 151 |
pub(crate) desired_fp_rate: f64, |
| 152 |
pub(crate) hasher: S, |
| 153 |
} |
| 154 |
|
| 155 |
impl<S: BuildHasher> PartialEq for $name<S> { |
| 156 |
fn eq(&self, other: &Self) -> bool { |
| 157 |
self.desired_fp_rate == other.desired_fp_rate |
| 158 |
} |
| 159 |
} |
| 160 |
impl<S: BuildHasher> Eq for $name<S> {} |
| 161 |
|
| 162 |
impl $name { |
| 163 |
/// Sets the seed for this builder. The later constructed Bloom filter |
| 164 |
/// will use this seed when hashing items. |
| 165 |
/// |
| 166 |
/// # Examples |
| 167 |
/// |
| 168 |
/// ``` |
| 169 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 170 |
/// |
| 171 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_false_pos(0.001).seed(&1).expected_items(100);")] |
| 172 |
/// ``` |
| 173 |
pub fn seed(mut self, seed: &u128) -> Self { |
| 174 |
self.hasher = DefaultHasher::seeded(&seed.to_be_bytes()); |
| 175 |
self |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
impl<S: BuildHasher> $name<S> { |
| 180 |
#[doc = concat!("Sets the hasher for this builder. The later constructed [`", stringify!($bloom), "`] will use")] |
| 181 |
/// this hasher when inserting and checking items. |
| 182 |
/// |
| 183 |
/// # Examples |
| 184 |
/// |
| 185 |
/// ``` |
| 186 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 187 |
/// use foldhash::fast::RandomState; |
| 188 |
/// |
| 189 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_false_pos(0.001).hasher(RandomState::default()).expected_items(100);")] |
| 190 |
/// ``` |
| 191 |
pub fn hasher<H: BuildHasher>(self, hasher: H) -> $name<H> { |
| 192 |
$name::<H> { |
| 193 |
desired_fp_rate: self.desired_fp_rate, |
| 194 |
hasher, |
| 195 |
} |
| 196 |
} |
| 197 |
|
| 198 |
/// "Consumes" this builder, using the provided `expected_items` to return an |
| 199 |
#[doc = concat!("empty [`", stringify!($bloom), "`]. The number of hashes is optimized based on `expected_items`")] |
| 200 |
#[doc = concat!("to maximize Bloom filter accuracy (minimize false positives chance on [`", stringify!($bloom), "::contains`]).")] |
| 201 |
/// More or less than `expected_items` may be inserted into Bloom filter. |
| 202 |
/// |
| 203 |
/// Note: `expected_items` will internally be set to 1 if 0 is specified. |
| 204 |
/// |
| 205 |
/// # Examples |
| 206 |
/// |
| 207 |
/// ``` |
| 208 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 209 |
/// |
| 210 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_false_pos(0.001).expected_items(500);")] |
| 211 |
/// ``` |
| 212 |
pub fn expected_items(self, expected_items: usize) -> $bloom<S> { |
| 213 |
let expected_items = max(1, expected_items); |
| 214 |
let num_bits = optimal_size(expected_items, self.desired_fp_rate); |
| 215 |
$bloom::new_builder(num_bits) |
| 216 |
.hasher(self.hasher) |
| 217 |
.expected_items(expected_items) |
| 218 |
} |
| 219 |
|
| 220 |
#[doc = concat!("\"Consumes\" this builder and constructs a [`", stringify!($bloom), "`] containing")] |
| 221 |
/// all values in `items`. The number of hashes per item and underlying memory |
| 222 |
/// is optimized based on `items.len()` to meet the desired false positive rate. |
| 223 |
/// |
| 224 |
/// # Examples |
| 225 |
/// |
| 226 |
/// ``` |
| 227 |
#[doc = concat!("use fastbloom::", stringify!($bloom), ";")] |
| 228 |
/// |
| 229 |
#[doc = concat!("let bloom = ", stringify!($bloom), "::with_false_pos(0.001).items([1, 2, 3].iter());")] |
| 230 |
/// ``` |
| 231 |
pub fn items<'a, H: Hash + 'a, I: IntoIterator<IntoIter = impl ExactSizeIterator<Item = &'a H>>>( |
| 232 |
self, |
| 233 |
items: I, |
| 234 |
) -> $bloom<S> { |
| 235 |
let into_iter = items.into_iter(); |
| 236 |
let $($m)? filter = self.expected_items(into_iter.len()); |
| 237 |
filter.insert_all(into_iter); |
| 238 |
filter |
| 239 |
} |
| 240 |
} |
| 241 |
}; |
| 242 |
} |
| 243 |
|
| 244 |
builder_with_fp!(BuilderWithFalsePositiveRate, mut, BloomFilter); |
| 245 |
builder_with_fp!(AtomicBuilderWithFalsePositiveRate, , AtomicBloomFilter); |
| 246 |
|
| 247 |
/// Returns the optimal (for false positive rate) number of hashes to perform for an item given the expected number of items in the bloom filter. |
| 248 |
pub fn optimal_hashes(num_bits: usize, num_items: usize) -> u32 { |
| 249 |
// Proof: <https://gopiandcode.uk/logs/log-bloomfilters-debunked.html>. |
| 250 |
let num_bits = num_bits as f64; |
| 251 |
let hashes = LN_2 * num_bits / num_items as f64; |
| 252 |
max(round(hashes) as u32, 1) |
| 253 |
} |
| 254 |
|
| 255 |
/// Returns the smallest size in bits of a Bloom filter containing `num_items` items to achieve the target false positive rate. |
| 256 |
pub fn optimal_size(num_items: usize, fp: f64) -> usize { |
| 257 |
let num_items = num_items as f64; |
| 258 |
let log2_2 = LN_2 * LN_2; |
| 259 |
let result = 8 * ceil(num_items * ln(fp) / (-8.0 * log2_2)) as usize; |
| 260 |
max(result, 64) |
| 261 |
} |
| 262 |
|
| 263 |
/// Returns the probability of a "1" bit in the Bloom filter. |
| 264 |
pub fn expected_density(hashes: u32, bits: usize, items: usize) -> f64 { |
| 265 |
let total_sets = (items * hashes as usize) as f64; |
| 266 |
let bits = bits as f64; |
| 267 |
let prob_set = 1.0 / bits; |
| 268 |
let prob_not_set = 1.0 - prob_set; |
| 269 |
let prob_all_not_set = crate::math::pow(prob_not_set, total_sets); |
| 270 |
1.0 - prob_all_not_set |
| 271 |
} |
| 272 |
|
| 273 |
/// Returns the expected false positive rate of a Bloom filter. |
| 274 |
pub fn expected_false_pos(hashes: u32, density: f64) -> f64 { |
| 275 |
crate::math::pow(density, hashes as f64) |
| 276 |
} |
| 277 |
|
| 278 |
#[cfg(test)] |
| 279 |
mod tests { |
| 280 |
use super::*; |
| 281 |
|
| 282 |
// optimal size should produce a FP the same. |
| 283 |
|
| •284 |
//#[test] ignored due to numeric overflow on 32-bit |
| 285 |
fn test_expected_false_pos() { |
| 286 |
for items_mag in 1..=32 { |
| 287 |
let items = 2usize.pow(items_mag); |
| 288 |
for fp_mag in 1..=16 { |
| 289 |
let target_fp = 1.0f64 / 10u64.pow(fp_mag) as f64; |
| 290 |
let size = optimal_size(items, target_fp); |
| 291 |
|
| 292 |
let thresh = if size < 256 { |
| 293 |
0.1 // If size is tool small results too sensitive |
| 294 |
} else { |
| 295 |
0.01 |
| 296 |
}; |
| 297 |
|
| 298 |
let h = optimal_hashes(size, items); |
| 299 |
let density = expected_density(h, size, items); |
| 300 |
let expected_fp = expected_false_pos(h, density); |
| 301 |
let err = (expected_fp - target_fp) / target_fp; |
| 302 |
assert!(err < thresh); |
| 303 |
} |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
fn density_err(d: f64) -> f64 { |
| 308 |
(0.5 - d).abs() |
| 309 |
} |
| 310 |
|
| 311 |
#[test] |
| 312 |
fn test_optimal_hashes() { |
| 313 |
for bits_mag in 6..=16 { |
| 314 |
let bits = 2usize.pow(bits_mag); |
| 315 |
for items_mag in 1..=16 { |
| 316 |
let items = 2usize.pow(items_mag); |
| 317 |
|
| 318 |
let h = optimal_hashes(bits, items); |
| 319 |
|
| 320 |
// Too sensitive to rounding errors |
| 321 |
if h > 1000 { |
| 322 |
continue; |
| 323 |
} |
| 324 |
let density = expected_density(h, bits, items); |
| 325 |
assert!(density_err(density) <= density_err(expected_density(h + 1, bits, items))); |
| 326 |
assert!(density_err(density) <= density_err(expected_density(h - 1, bits, items))); |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
#[cfg(test)] |
| 333 |
mod for_accuracy_tests { |
| 334 |
use crate::BloomFilter; |
| 335 |
|
| 336 |
#[test] |
| 337 |
fn data_size() { |
| 338 |
let size_bits = 512 * 1000; |
| 339 |
let bloom = BloomFilter::with_num_bits(size_bits).hashes(4); |
| 340 |
assert_eq!(bloom.num_bits(), size_bits); |
| 341 |
} |
| 342 |
|
| 343 |
#[test] |
| 344 |
fn specified_hashes() { |
| 345 |
for num_hashes in 1..1000 { |
| 346 |
assert_eq!( |
| 347 |
num_hashes, |
| 348 |
BloomFilter::with_num_bits(1) |
| 349 |
.hashes(num_hashes) |
| 350 |
.num_hashes() |
| 351 |
); |
| 352 |
assert_eq!( |
| 353 |
num_hashes, |
| 354 |
BloomFilter::with_num_bits(1) |
| 355 |
.hashes(num_hashes) |
| 356 |
.num_hashes() |
| 357 |
); |
| 358 |
} |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
#[cfg(test)] |
| 363 |
mod for_size_tests { |
| 364 |
use crate::{AtomicBloomFilter, BloomFilter}; |
| 365 |
|
| 366 |
#[test] |
| 367 |
fn test_size() { |
| 368 |
let _: BloomFilter = BloomFilter::new_with_false_pos(0.0001).expected_items(10000); |
| 369 |
} |
| 370 |
|
| 371 |
#[test] |
| 372 |
fn test_zero_hashes() { |
| 373 |
let bloom = BloomFilter::with_num_bits(512).hashes(0); |
| 374 |
assert_eq!(bloom.num_hashes(), 1); |
| 375 |
let bloom = AtomicBloomFilter::with_num_bits(512).hashes(0); |
| 376 |
assert_eq!(bloom.num_hashes(), 1); |
| 377 |
} |
| 378 |
} |