-
Notifications
You must be signed in to change notification settings - Fork 0
/
bloom_test.go
80 lines (72 loc) · 1.97 KB
/
bloom_test.go
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package bloom
import (
"fmt"
"testing"
"github.com/dchest/siphash"
"github.com/stretchr/testify/assert"
)
const (
// Number of elements
n = 65000
// False positive probability
p = 0.1
)
func TestNbits(t *testing.T) {
//Optimal number of bits, m = -(n log(p) / pow(log(2), 2))
// p = 0.1 ; n = 65000
// m ~= 311514 > 311552 (multiple of 64 - 4868 64bit-words)
// Given a filter with n = 65000 and p = 0.1
filter := New(n, p)
// Then, the number of bits must be equal to 311552
assert.Equal(t, uint64(311552), filter.nbits)
}
func TestNHashes(t *testing.T) {
// uint64(-int(math.Ceil(math.Log(p) / math.Ln2)))
// Given a filter with n = 65000 and p = 0.1
filter := New(n, p)
// Then, the number of bits must be equal to 3 (math.Ceil(-3.321928094887362) == 3)
assert.Equal(t, filter.nhashes, uint64(3))
}
func TestAdd(t *testing.T) {
// Given an empty filter
value := "random"
filter := New(n, p)
// If we add a value
filter.Add(value)
// Then, the value must exist in the filter
a, b := siphash.Hash128(k0, k1, []byte(value))
for h := uint64(0); h <= filter.nhashes; h++ {
i := (a + h*b) % filter.nbits
mask := uint64(1) << (i & mod)
assert.NotZero(t, filter.bits[i>>div]&mask)
}
}
func TestHas(t *testing.T) {
// Given a filter that has a value x
value := "random"
filter := New(n, p)
a, b := siphash.Hash128(k0, k1, []byte(value))
for h := uint64(0); h <= filter.nhashes; h++ {
i := (a + h*b) % filter.nbits
mask := uint64(1) << (i & mod)
if filter.bits[i>>div]&mask == 0 {
filter.bits[i>>div] |= mask
}
}
// If the has operation is executed to verify x presence
result := filter.Has(value)
fmt.Println(result)
// Then, the result must be true
assert.True(t, result)
}
func TestClear(t *testing.T) {
// Given a filter with values
filter := New(n, p)
filter.bits = []uint64{300, 55}
// If the clear option is executed
filter.Clear()
// Then, all the words must be equal to 0
for i := range filter.bits {
assert.Zero(t, filter.bits[i])
}
}