1 #include "git-compat-util.h"
4 static uint32_t rotate_left(uint32_t value, int32_t count)
6 uint32_t mask = 8 * sizeof(uint32_t) - 1;
8 return ((value << count) | (value >> ((-count) & mask)));
11 static inline unsigned char get_bitmask(uint32_t pos)
13 return ((unsigned char)1) << (pos & (BITS_PER_WORD - 1));
17 * Calculate the murmur3 32-bit hash value for the given data
18 * using the given seed.
19 * Produces a uniformly distributed hash value.
20 * Not considered to be cryptographically secure.
21 * Implemented as described in https://en.wikipedia.org/wiki/MurmurHash#Algorithm
23 uint32_t murmur3_seeded(uint32_t seed, const char *data, size_t len)
25 const uint32_t c1 = 0xcc9e2d51;
26 const uint32_t c2 = 0x1b873593;
27 const uint32_t r1 = 15;
28 const uint32_t r2 = 13;
30 const uint32_t n = 0xe6546b64;
35 int len4 = len / sizeof(uint32_t);
38 for (i = 0; i < len4; i++) {
39 uint32_t byte1 = (uint32_t)data[4*i];
40 uint32_t byte2 = ((uint32_t)data[4*i + 1]) << 8;
41 uint32_t byte3 = ((uint32_t)data[4*i + 2]) << 16;
42 uint32_t byte4 = ((uint32_t)data[4*i + 3]) << 24;
43 k = byte1 | byte2 | byte3 | byte4;
45 k = rotate_left(k, r1);
49 seed = rotate_left(seed, r2) * m + n;
52 tail = (data + len4 * sizeof(uint32_t));
54 switch (len & (sizeof(uint32_t) - 1)) {
56 k1 ^= ((uint32_t)tail[2]) << 16;
59 k1 ^= ((uint32_t)tail[1]) << 8;
62 k1 ^= ((uint32_t)tail[0]) << 0;
64 k1 = rotate_left(k1, r1);
70 seed ^= (uint32_t)len;
80 void fill_bloom_key(const char *data,
82 struct bloom_key *key,
83 const struct bloom_filter_settings *settings)
86 const uint32_t seed0 = 0x293ae76f;
87 const uint32_t seed1 = 0x7e646e2c;
88 const uint32_t hash0 = murmur3_seeded(seed0, data, len);
89 const uint32_t hash1 = murmur3_seeded(seed1, data, len);
91 key->hashes = (uint32_t *)xcalloc(settings->num_hashes, sizeof(uint32_t));
92 for (i = 0; i < settings->num_hashes; i++)
93 key->hashes[i] = hash0 + i * hash1;
96 void add_key_to_filter(const struct bloom_key *key,
97 struct bloom_filter *filter,
98 const struct bloom_filter_settings *settings)
101 uint64_t mod = filter->len * BITS_PER_WORD;
103 for (i = 0; i < settings->num_hashes; i++) {
104 uint64_t hash_mod = key->hashes[i] % mod;
105 uint64_t block_pos = hash_mod / BITS_PER_WORD;
107 filter->data[block_pos] |= get_bitmask(hash_mod);