Skip to content

About

A space-efficient probabilistic Bloom filter and counting Bloom filter with real double-hashing and deletion support. Zero-dependency Rust.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rs-bloomfilter

A space-efficient probabilistic Bloom filter and counting Bloom filter for Rust, with zero external dependencies — everything is built on the standard library.

Why this is useful

A Bloom filter answers "have I possibly seen this before?" using a small, fixed-size bit array instead of storing the actual items. That trade-off is genuinely useful whenever you need to cheaply rule out the vast majority of lookups before paying for an expensive one — for example:

  • Checking "might this key exist in a database/disk file?" before doing a real disk read (this is exactly how LevelDB/RocksDB and Cassandra avoid unnecessary disk seeks).
  • Deduplicating a huge stream of events/URLs without keeping every item in memory.
  • Spell-checkers and "have we already sent this notification?" caches, where an occasional false positive is cheap and a false negative would be a real bug.

The core guarantee is asymmetric and is the entire point of the data structure: a Bloom filter never produces a false negative (if it says "no", the item was definitely never inserted), but it can produce a false positive (if it says "maybe", it's usually right, at a rate you control up front). In exchange, it uses a tiny, constant amount of memory per expected item regardless of how large or complex the items themselves are, and it never stores the items at all.

This crate also includes a counting Bloom filter, which trades a bit more memory (small integer counters instead of single bits) for the ability to actually delete items — something a plain bit-array Bloom filter fundamentally cannot support safely, because clearing a shared bit would silently break every other item relying on it.

Usage

use rs_bloomfilter::{BloomFilter, CountingBloomFilter};

// Size the filter for ~10,000 items at a 1% target false-positive rate.
// m (bit-array size) and k (hash count) are computed automatically.
let mut filter = BloomFilter::new(10_000, 0.01).unwrap();

filter.insert(&"[email protected]");
filter.insert(&"[email protected]");

assert!(filter.contains(&"[email protected]"));   // definitely inserted -> always true
assert!(!filter.contains(&"[email protected]"));  // never inserted -> true with probability >= 99%

// The counting variant supports real deletion.
let mut deletable = CountingBloomFilter::new(1_000, 0.01).unwrap();
deletable.insert(&"session-42");
assert!(deletable.contains(&"session-42"));

deletable.remove(&"session-42");
assert!(!deletable.contains(&"session-42"));

Both types also expose with_dimensions(m, k) if you want to bypass the sizing formula and set the bit/counter array size and hash count directly.

How it works

Sizing: choosing m and k

Given an expected item count n and a target false-positive rate p, the filter needs a bit array of size

m = ceil(-n * ln(p) / (ln 2)^2)

and a number of hash functions

k = round((m / n) * ln 2)

(clamped to at least 1). These are the standard closed-form results that minimize the false-positive rate for a bit array of size m holding n items. For example, n = 1000, p = 0.01 works out to m ~= 9586 bits (~1.2 KB) and k = 7 hashes — about 9.6 bits per item, independent of how large the items themselves are.

Deriving k hash functions from just two real hashes

A naive implementation would need k genuinely different hash algorithms. Instead, this crate uses the Kirsch-Mitzenmacher double-hashing technique (Kirsch & Mitzenmacher, 2006, "Less Hashing, Same Performance: Building a Better Bloom Filter"): compute two real, independent hashes h1(x) and h2(x) of the item, then derive all k indices as

g_i(x) = (h1(x) + i * h2(x)) mod m,   for i in 0..k

This is provably as effective as using k independent hash functions for the purposes of a Bloom filter's false-positive analysis, while only ever computing two real hashes per item. h1 and h2 here are both produced by the standard library's std::collections::hash_map::DefaultHasher (SipHash-1-3), seeded differently by hashing the item together with two distinct fixed constants.

Note on hash quality: DefaultHasher is a general-purpose, non-cryptographic hash designed to resist accidental collisions and basic hash-flooding, not a cryptographically secure hash. That's the right trade-off for this crate's target use cases (caching, deduplication, membership pre-checks). If you need this for anything security-sensitive — e.g. where an adversary can choose inputs specifically to force excessive collisions or false positives against you — swap in a hash function appropriate for that threat model instead.

The counting variant and deletion semantics

CountingBloomFilter replaces each single bit with a small saturating u8 counter (range 0..=255). Inserting an item increments its k derived counters; removing it decrements them. Because a slot only returns to zero once every item that touched it has been removed, deleting one item can never collaterally break a lookup for a different, still-present item that happened to share a slot with it — which is exactly the failure mode that makes deletion unsafe on a plain bit-array Bloom filter. Overflow is handled by saturating rather than wrapping: a counter stays pinned at 255 instead of wrapping back to a misleadingly low value, and decrementing an already-zero counter is a safe no-op rather than an underflow panic.

Testing

cargo test

The test suite proves three correctness properties directly, not just "it compiles":

  1. Zero false negatives — every item that was actually inserted always reports "possibly present."
  2. Empirical false-positive rate — a filter configured for n = 2000, p = 0.02 is tested against 20,000 distinct, never-inserted probe items; the measured false-positive rate is asserted to stay within a factor of 3 of the configured target in either direction (a real run measured 1.84% against a 2% target).
  3. Counting filter deletion is collateral-damage-free — two items are found (by brute-force search, reproducibly, over a small explicit m/k) that share at least one hash slot but are not identical. After deleting one, it correctly reports absent while the other, never deleted, still reports present — including verifying the shared counter directly, proving the counting scheme (not just luck) is what keeps the second item alive.

License

MIT

About

A space-efficient probabilistic Bloom filter and counting Bloom filter with real double-hashing and deletion support. Zero-dependency Rust.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages