Debian Codegraph @

debian/bloom/filter.go

raw symbols SCIP
1 // Package bloom implements Bloom Filter using double hashing
2 package bloom
3
4 import (
5 "math"
6 )
7
8 // Filter is a generic Bloom Filter
9 type Filter interface {
10 Add([]byte) // add an entry to the filter
11 Test([]byte) bool // test if an entry is in the filter
12 Size() int // size of the filter in bytes
13 Reset() // reset the filter to initial state
14 }
15
16 // Classic Bloom Filter
17 type classicFilter struct {
18 b []byte
19 k int
20 h func([]byte) (uint64, uint64)
21 }
22
23 // New creates a classic Bloom Filter that is optimal for n entries and false positive rate of p.
24 // h is a double hash that takes an entry and returns two different hashes.
25 func New(n int, p float64, h func([]byte) (uint64, uint64)) Filter {
26 k := -math.Log(p) * math.Log2E // number of hashes
27 m := float64(n) * k * math.Log2E // number of bits
28 return &classicFilter{b: make([]byte, int(m/8)), k: int(k), h: h}
29 }
30
31 func (f *classicFilter) getOffset(x, y uint64, i int) uint64 {
32 return (x + uint64(i)*y) % (8 * uint64(len(f.b)))
33 }
34
35 func (f *classicFilter) Add(b []byte) {
36 x, y := f.h(b)
37 for i := 0; i < f.k; i++ {
38 offset := f.getOffset(x, y, i)
39 f.b[offset/8] |= 1 << (offset % 8)
40 }
41 }
42
43 func (f *classicFilter) Test(b []byte) bool {
44 x, y := f.h(b)
45 for i := 0; i < f.k; i++ {
46 offset := f.getOffset(x, y, i)
47 if f.b[offset/8]&(1<<(offset%8)) == 0 {
48 return false
49 }
50 }
51 return true
52 }
53
54 func (f *classicFilter) Size() int { return len(f.b) }
55
56 func (f *classicFilter) Reset() {
57 for i := range f.b {
58 f.b[i] = 0
59 }
60 }