MCPcopy Create free account
hub / github.com/CDSecLab/MJXT / Bloom

Class Bloom

src/main/java/utils/Bloom.java:7–68  ·  view source on GitHub ↗

A standard Bloom filter.

Source from the content-addressed store, hash-verified

5 *
6 */
7public class Bloom {
8
9 public static Bloom construct(long[] keys, double bitsPerKey) {
10 long n = keys.length;
11 int k = getBestK(bitsPerKey);
12 Bloom f = new Bloom((int) n, bitsPerKey, k);
13 for(long x : keys) {
14 f.add(x);
15 }
16 return f;
17 }
18
19 private static int getBestK(double bitsPerKey) {
20 return Math.max(1, (int) Math.round(bitsPerKey * Math.log(2)));
21 }
22
23 private final int k;
24 private final long bits;
25 private final long seed;
26 private final int arraySize;
27 private final long[] data;
28
29 Bloom(int entryCount, double bitsPerKey, int k) {
30 entryCount = Math.max(1, entryCount);
31 this.k = k;
32 this.seed = Hash.randomSeed();
33 this.bits = (long) (entryCount * bitsPerKey);
34 arraySize = (int) ((bits + 63) / 64);
35 data = new long[arraySize];
36 }
37
38 public void add(long key) {
39 long hash = Hash.hash64(key, seed);
40 long a = (hash >>> 32) | (hash << 32);
41 long b = hash;
42 for (int i = 0; i < k; i++) {
43 data[Hash.reduce((int) (a >>> 32), arraySize)] |= 1L << a;
44 a += b;
45 }
46 }
47
48 public boolean mayContain(long key) {
49 long hash = Hash.hash64(key, seed);
50 long a = (hash >>> 32) | (hash << 32);
51 long b = hash;
52 for (int i = 0; i < k; i++) {
53 if ((data[Hash.reduce((int) (a >>> 32), arraySize)] & 1L << a) == 0) {
54 return false;
55 }
56 a += b;
57 }
58 return true;
59 }
60
61 public byte[][] getData() {
62 byte[][] d = new byte[data.length][];
63 for (int i = 0; i < data.length; i++) {
64 d[i] = tool.longToBytes(data[i]);

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected