logo

drewdevault.com

[mirror] blog and personal website of Drew DeVault git clone https://hacktivis.me/git/mirror/drewdevault.com.git

How-to-write-a-better-bloom-filter-in-C.md (5681B)


  1. ---
  2. date: 2016-04-12
  3. # vim tw=80
  4. title: How to write a better bloom filter in C
  5. layout: post
  6. tags: [C, instructive]
  7. ---
  8. This is in response to
  9. [How to write a bloom filter in C++](http://blog.michaelschmatz.com/2016/04/11/how-to-write-a-bloom-filter-cpp/),
  10. which has good intentions, but is ultimately a less than ideal bloom filter
  11. implementation. I put together a better one in C in a few minutes, and I'll
  12. explain the advantages of it.
  13. The important differences are:
  14. * You bring your own hashing functions
  15. * You can add arbitrary data types, not just bytes
  16. * It uses bits directly instead of relying on the `std::vector<bool>`
  17. being space effecient
  18. I chose C because (1) I prefer it over C++ and (2) I just think it's a better
  19. choice for implementing low level data types, and C++ is better used in high
  20. level code.
  21. I'm not going to explain the mechanics of a bloom filter or most of the details
  22. of why the code looks this way, since I think the original post did a fine job
  23. of that. I'll just present my alternate implementation:
  24. ## Header
  25. ```c
  26. #ifndef _BLOOM_H
  27. #define _BLOOM_H
  28. #include <stddef.h>
  29. #include <stdbool.h>
  30. typedef unsigned int (*hash_function)(const void *data);
  31. typedef struct bloom_filter * bloom_t;
  32. /* Creates a new bloom filter with no hash functions and size * 8 bits. */
  33. bloom_t bloom_create(size_t size);
  34. /* Frees a bloom filter. */
  35. void bloom_free(bloom_t filter);
  36. /* Adds a hashing function to the bloom filter. You should add all of the
  37. * functions you intend to use before you add any items. */
  38. void bloom_add_hash(bloom_t filter, hash_function func);
  39. /* Adds an item to the bloom filter. */
  40. void bloom_add(bloom_t filter, const void *item);
  41. /* Tests if an item is in the bloom filter.
  42. *
  43. * Returns false if the item has definitely not been added before. Returns true
  44. * if the item was probably added before. */
  45. bool bloom_test(bloom_t filter, const void *item);
  46. #endif
  47. ```
  48. ## Implementation
  49. The implementation of this is pretty straightfoward. First, here's the actual
  50. structs behind the opaque bloom_t type:
  51. ```c
  52. struct bloom_hash {
  53. hash_function func;
  54. struct bloom_hash *next;
  55. };
  56. struct bloom_filter {
  57. struct bloom_hash *func;
  58. void *bits;
  59. size_t size;
  60. };
  61. ```
  62. The hash functions are a linked list, but this isn't important. You can make
  63. that anything you want. Otherwise we have a bit of memory called "bits" and the
  64. size of it. Now, for the easy functions:
  65. ```c
  66. bloom_t bloom_create(size_t size) {
  67. bloom_t res = calloc(1, sizeof(struct bloom_filter));
  68. res->size = size;
  69. res->bits = malloc(size);
  70. return res;
  71. }
  72. void bloom_free(bloom_t filter) {
  73. if (filter) {
  74. while (filter->func) {
  75. struct bloom_hash *h;
  76. filter->func = h->next;
  77. free(h);
  78. }
  79. free(filter->bits);
  80. free(filter);
  81. }
  82. }
  83. ```
  84. These should be fairly self explanatory. The first interesting function is here:
  85. ```c
  86. void bloom_add_hash(bloom_t filter, hash_function func) {
  87. struct bloom_hash *h = calloc(1, sizeof(struct bloom_hash));
  88. h->func = func;
  89. struct bloom_hash *last = filter->func;
  90. while (last && last->next) {
  91. last = last->next;
  92. }
  93. if (last) {
  94. last->next = h;
  95. } else {
  96. filter->func = h;
  97. }
  98. }
  99. ```
  100. Given a hashing function from the user, this just adds it to our linked list of
  101. hash functions. There's a slightly different code path if we're adding the first
  102. function. The functions so far don't really do anything specific to bloom
  103. filters. The first one that does is this:
  104. ```c
  105. void bloom_add(bloom_t filter, const void *item) {
  106. struct bloom_hash *h = filter->func;
  107. uint8_t *bits = filter->bits;
  108. while (h) {
  109. unsigned int hash = h->func(item);
  110. hash %= filter->size * 8;
  111. bits[hash / 8] |= 1 << hash % 8;
  112. h = h->next;
  113. }
  114. }
  115. ```
  116. This iterates over each of the hash functions the user has provided and computes
  117. the hash of the data for that function (modulo the size of our bloom filter),
  118. then it adds this to the bloom filter with this line:
  119. ```c
  120. bits[hash / 8] |= 1 << hash % 8;
  121. ```
  122. This just sets the nth bit of the filter where n is the hash. Finally, we have
  123. the test function:
  124. ```c
  125. bool bloom_test(bloom_t filter, const void *item) {
  126. struct bloom_hash *h = filter->func;
  127. uint8_t *bits = filter->bits;
  128. while (h) {
  129. unsigned int hash = h->func(item);
  130. hash %= filter->size * 8;
  131. if (!(bits[hash / 8] & 1 << hash % 8)) {
  132. return false;
  133. }
  134. h = h->next;
  135. }
  136. return true;
  137. }
  138. ```
  139. This function is extremely similar, but instead of setting the nth bit, it
  140. checks the nth bit and returns if it's 0:
  141. ```c
  142. if (!(bits[hash / 8] & 1 << hash % 8)) {
  143. ```
  144. That's it! You have a bloom filter with arbitrary data types for insert and
  145. user-supplied hash functions. I wrote up some simple test code to demonstrate
  146. this, after googling for a couple of random hash functions:
  147. ```c
  148. #include "bloom.h"
  149. #include <stdio.h>
  150. unsigned int djb2(const void *_str) {
  151. const char *str = _str;
  152. unsigned int hash = 5381;
  153. char c;
  154. while ((c = *str++)) {
  155. hash = ((hash << 5) + hash) + c;
  156. }
  157. return hash;
  158. }
  159. unsigned int jenkins(const void *_str) {
  160. const char *key = _str;
  161. unsigned int hash, i;
  162. while (*key) {
  163. hash += *key;
  164. hash += (hash << 10);
  165. hash ^= (hash >> 6);
  166. key++;
  167. }
  168. hash += (hash << 3);
  169. hash ^= (hash >> 11);
  170. hash += (hash << 15);
  171. return hash;
  172. }
  173. int main() {
  174. bloom_t bloom = bloom_create(8);
  175. bloom_add_hash(bloom, djb2);
  176. bloom_add_hash(bloom, jenkins);
  177. printf("Should be 0: %d\n", bloom_test(bloom, "hello world"));
  178. bloom_add(bloom, "hello world");
  179. printf("Should be 1: %d\n", bloom_test(bloom, "hello world"));
  180. printf("Should (probably) be 0: %d\n", bloom_test(bloom, "world hello"));
  181. return 0;
  182. }
  183. ```
  184. The full code is available [here](https://git.sr.ht/~sircmpwn/bloom/).