Advertisement
Guest User

bloom.c

a guest
Sep 17th, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.11 KB | None | 0 0
  1. int test_bit(char * buf, int pos){
  2. return buf[pos/8] & (1<<(pos%8));
  3. }
  4. void set_bit(char * buf, int pos){
  5. buf[pos/8] |= 1<<(pos%8);
  6. }
  7. int bloom_check(struct bloom * bloom, const void * buffer, int len) {
  8. int hits = 0;
  9. unsigned int a = murmurhash2(buffer, len, 0x9747b28c);
  10. unsigned int b = murmurhash2(buffer, len, a);
  11. for (int i = 0; i < bloom->hashes; i++)
  12. if(test_bit(bloom->bf, (a + i*b) % bloom->bits)) hits++;
  13. return hits == bloom->hashes;
  14. }
  15. int bloom_add(struct bloom * bloom, const void * buffer, int len) {
  16. unsigned int a = murmurhash2(buffer, len, 0x9747b28c);
  17. unsigned int b = murmurhash2(buffer, len, a);
  18. for (int i = 0; i < bloom->hashes; i++)
  19. set_bit(bloom->bf, (a + i*b) % bloom->bits);
  20. }
  21. int bloom_init(struct bloom * bloom, int entries, double error) {
  22. if (entries < 1000 || error == 0)
  23. return 1;
  24. double bpe = -(log(error) / 0.480453013918201);
  25. bloom->bits = (int)(entries * bpe);
  26. if (bloom->bits % 8)
  27. bloom->bf = (unsigned char *)calloc(bloom->bits/8+1, sizeof(unsigned char));
  28. else
  29. bloom->bf = (unsigned char *)calloc(bloom->bits/8, sizeof(unsigned char));
  30. if (bloom->bf == NULL)
  31. return 1;
  32. bloom->hashes = (int)ceil(0.693147180559945 * bpe); // ln(2)
  33. return 0;
  34. }
  35. void bloom_free(struct bloom * bloom) {
  36. free(bloom->bf);
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement