bloom - Bloom filter (probabilistic set)
Import with import "bloom.j" as bloom;. A compact, probabilistic set: add records a string and mightContain tests membership with no false negatives (a member always reports present) but possible false positives (a non-member may report present, with a probability that grows as the filter fills). It trades a little accuracy for a lot of space in "have I seen this before?" checks over large sets. Pure .j over hash + math + binary; runs on both binaries.
import "bloom.j" as bloom;
def f as bloom.Filter init bloom.new(1024, 4);
$f = bloom.add($f, "alice");
$f = bloom.add($f, "bob");
bloom.mightContain($f, "alice"); # true
bloom.mightContain($f, "carol"); # almost always falseRunnable: examples/modules/bloom_demo.j.
Surface
bloom.Filter { bits as bytes, size as int, hashes as int }| Call | Returns | |
|---|---|---|
bloom.new(size, hashes) | Filter | an empty filter of size bits (1 to 2^29) and hashes hash functions (1 to 255) |
bloom.optimal(n, fpr) | Filter | an empty filter sized for n expected items at target false-positive rate fpr (n >= 1, 0 < fpr < 1) |
bloom.add(f, item) | Filter | the filter with item recorded |
bloom.addAll(f, items) | Filter | the filter with every item of a list of string recorded |
bloom.mightContain(f, item) | bool | true if the item might be present, false if it is definitely absent |
bloom.serialize(f) | bytes | encode a filter to bytes (4-byte size, 4-byte hashes, then the bit array) |
bloom.deserialize(b) | Filter | reconstruct a filter from serialize output (identical filter, membership preserved) |
bloom.union(a, b) | Filter | a with the members of b added (same size and hashes required) |
bloom.merge(a, b) | Filter | alias for bloom.union |
$f = bloom.add($f, x) on a local updates the bit array in place; any other use copies the filter first, as value semantics require.
The hashes bit positions per item come from double-hashing one SHA-256 digest: pos_i = (h1 + i*h2) mod size, where h1 / h2 are the first two 32-bit words of the digest (h2 reduced mod size, and 1 when that is 0), so one hash yields all k positions.
Choosing size and hashes
Bigger size and a well-chosen hashes lower the false-positive rate. Rules of thumb for n expected items at a target false-positive probability p:
- bits
m ~= -n * ln(p) / (ln 2)^2(about9.6 * nbits forp = 1%,14.4 * nforp = 0.1%). - hashes
k ~= (m / n) * ln 2(about 7 forp = 1%).
So for 10000 items at 1%: size ~= 96000, hashes = 7.
bloom.optimal(n, fpr) does this arithmetic: it computes m = ceil(-(n * ln fpr) / (ln 2)^2) and k = round((m / n) * ln 2) (clamped to 1..255, the range new accepts, so a tiny fpr such as 1e-100 gets 255 hashes) and returns an empty filter of that shape. bloom.optimal(1000, 0.01) yields a size = 9586, hashes = 7 filter.
Serialization and union
bloom.serialize encodes a filter to a self-describing bytes blob (a 4-byte big-endian size, a 4-byte big-endian hashes, then the raw bit array), and bloom.deserialize reverses it to a byte-identical filter, so a filter can be written to disk (fs) or sent over the wire and rebuilt later. A blob whose header is out of range (size 0, a hash count outside 1-255) or whose length does not match its size is an error.
bloom.union (alias bloom.merge) bitwise-ORs two filters of the same size and hashes: an item present in either input is present in the union. Filters that disagree on size or hashes cannot be combined and throw an Error{kind: "bloom"}.
use io;
import "bloom.j" as bloom;
def a as bloom.Filter init bloom.addAll(bloom.new(2048, 5), ["alice", "bob"]);
def b as bloom.Filter init bloom.addAll(bloom.new(2048, 5), ["carol"]);
def both as bloom.Filter init bloom.union($a, $b); # holds alice, bob, carol
def blob as bytes init bloom.serialize($both);
def restored as bloom.Filter init bloom.deserialize($blob); # identical filter
io.printf("%t\n", bloom.mightContain($restored, "carol")); # trueScope
- Add and test only. A standard Bloom filter cannot remove an item or count occurrences (removal needs a counting Bloom filter).
- Value-semantic
add.addreturns the updated filter, so assign it back ($f = bloom.add($f, x)); written that way on a local it updates the bit array in place. Any other use (keeping the old filter, a struct field) copies the whole array per add.addAllrecords a list in one call. - Strings only. Hash other values through
convert.toStringor ajson/encodingrepresentation first. - Non-crypto use. The filter is a set membership structure, not a security primitive.
See also
- hash.md - the SHA-256 the positions derive from.
- ringbuffer.md - the sibling data-structure module.
- modules/index.md - the module catalog and import rules.
Academy talks
| Talk | What it shows |
|---|---|
| Using the Jennifer profiler | a Bloom filter profiled and sped up from 1.2 s to 0.33 s |
API reference
Every exported function, struct and constant of bloom, with its signature, generated from the module's doc comments: the bloom API reference.