-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbloom.c
More file actions
54 lines (47 loc) · 1.2 KB
/
bloom.c
File metadata and controls
54 lines (47 loc) · 1.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <assert.h>
#include "hash.h"
#include "hash_f.h"
#include "bloom.h"
void add_hash_functions(bloom_filter *bf) {
for (int i = 0; i < bf->k; i++) {
bf->hashfunc[i] = hashf[i];
}
}
bloom_filter *bloom_init(int size, int k) {
bloom_filter *bf = malloc(sizeof(bloom_filter));
assert(bf != NULL);
bf->size = size;
bf->bits = malloc(size * sizeof(int));
assert(bf->bits != NULL);
assert(k <= 12);
bf->hashfunc = malloc(k * sizeof(hash_func_t));
assert(bf->hashfunc != NULL);
bf->k = k;
add_hash_functions(bf);
return bf;
}
void bloom_add(bloom_filter *bf, const char *item) {
for (int i = 0; i < bf->k; i++) {
int hash_val = bf->hashfunc[i](item, bf->size);
bf->bits[hash_val] = 1;
}
}
bool bloom_check(bloom_filter *bf, const char *item) {
for (int i = 0; i < bf->k; i++) {
int hash_val = bf->hashfunc[i](item, bf->size);
if (bf->bits[hash_val] == 0) {
return false;
}
}
return true;
}
void bloom_free(bloom_filter *bf) {
free(bf->bits);
free(bf->hashfunc);
free(bf);
}