Debian Codegraph @

debian/bloom/filter_test.go

raw symbols SCIP
1 package bloom
2
3 import (
4 "encoding/binary"
5 "fmt"
6 "hash/fnv"
7 "testing"
8 )
9
10 func doubleFNV(b []byte) (uint64, uint64) {
11 hx := fnv.New64()
12 hx.Write(b)
13 x := hx.Sum64()
14 hy := fnv.New64a()
15 hy.Write(b)
16 y := hy.Sum64()
17 return x, y
18 }
19
20 func TestClassicFilter_Test(t *testing.T) {
21 bf := New(1e6, 1e-4, doubleFNV)
22 buf := []byte("testing")
23 bf.Add(buf)
24 if !bf.Test(buf) {
25 t.Fatal("Should exist in filter but got false")
26 }
27 if bf.Test([]byte("not-exists")) {
28 t.Fatal("Should missing in filter but got true")
29 }
30 }
31
32 func TestFalsePositive(t *testing.T) {
33 const (
34 n = 1e6
35 expectFPR = 1e-4
36 )
37 bf := New(n, expectFPR, doubleFNV)
38 samples := make([][]byte, n)
39 fp := 0 // false positive count
40
41 for i := 0; i < n; i++ {
42 x := []byte(fmt.Sprint(i))
43 samples[i] = x
44 bf.Add(x)
45 }
46
47 for _, x := range samples {
48 if !bf.Test(x) {
49 fp++
50 }
51 }
52 fpr := float64(fp) / n
53 t.Logf("Samples = %d, FP = %d, FPR = %.4f%%", int(n), fp, fpr*100)
54 }
55
56 func BenchmarkAdd(b *testing.B) {
57 b.StopTimer()
58 b.ReportAllocs()
59 bf := New(1e6, 1e-4, doubleFNV)
60 buf := make([]byte, 20)
61 b.StartTimer()
62 for i := 0; i < b.N; i++ {
63 binary.PutUvarint(buf, uint64(i))
64 bf.Add(buf)
65 }
66 }
67
68 func BenchmarkTest(b *testing.B) {
69 b.StopTimer()
70 b.ReportAllocs()
71 bf := New(1e6, 1e-4, doubleFNV)
72 buf := make([]byte, 20)
73 b.StartTimer()
74 for i := 0; i < b.N; i++ {
75 binary.PutUvarint(buf, uint64(i))
76 bf.Test(buf)
77 }
78 }