-
Notifications
You must be signed in to change notification settings - Fork 5
/
bloom.go
52 lines (43 loc) · 1.01 KB
/
bloom.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
package bloom
import "math"
type Bloom struct {
Storage Storager
Config *Config
}
type Config struct {
ErrorRate float64
Elements uint
BitNumbers uint
HashNumbers uint
}
func (l *Bloom) New(config *Config) *Bloom {
if config.ErrorRate == 0 {
config.ErrorRate = 0.001
}
if config.Elements == 0 {
config.Elements = 1000
}
if config.BitNumbers == 0 || config.HashNumbers == 0 {
config.BitNumbers, config.HashNumbers = l.Estimate(config.Elements, config.ErrorRate)
}
return &Bloom{
Config: config,
}
}
func (l *Bloom) UseStorage(s Storager) *Bloom {
if s == nil {
panic("storage is nil.")
}
l.Storage = s
return l
}
func (l *Bloom) Exist(key string, value interface{}) (ex bool, err error) {
// get
return l.Storage.Exist(key, value)
}
// get need bit numbers and hash func numbers
func (l *Bloom) Estimate(n uint, p float64) (uint, uint) {
m := math.Ceil(float64(n) * math.Log(p) / math.Log(1.0/math.Pow(2.0, math.Ln2)))
k := math.Ln2*m/float64(n) + 0.5
return uint(m), uint(k)
}