13 #define BITS_PER_INDEX (sizeof(uint32_t) * 8)
14 #define BITS_INDEX_MASK (BITS_PER_INDEX - 1)
16 static unsigned int jhash_init[] = { 0, 0x12db635, 0x2a4a53 };
19 struct bloom *bloom_new(uint64_t entries)
24 b = malloc(sizeof(*b));
25 b->nentries = entries;
26 no_uints = (entries + BITS_PER_INDEX - 1) / BITS_PER_INDEX;
27 b->map = calloc(no_uints, sizeof(uint32_t));
36 void bloom_free(struct bloom *b)
42 static int __bloom_check(struct bloom *b, uint32_t *data, unsigned int nwords,
45 uint32_t hashes[N_HASHES];
48 for (i = 0; i < N_HASHES; i++)
49 hashes[i] = jhash(data, nwords, jhash_init[i]) % b->nentries;
52 for (i = 0; i < N_HASHES; i++) {
53 const unsigned int index = hashes[i] / BITS_PER_INDEX;
54 const unsigned int bit = hashes[i] & BITS_INDEX_MASK;
56 if (b->map[index] & (1U << bit))
59 b->map[index] |= 1U << bit;
62 return was_set == N_HASHES;
65 int bloom_check(struct bloom *b, uint32_t *data, unsigned int nwords)
67 return __bloom_check(b, data, nwords, 0);
70 int bloom_set(struct bloom *b, uint32_t *data, unsigned int nwords)
72 return __bloom_check(b, data, nwords, 1);