├── README.md ├── bloom_test.go ├── storage └── redis_bit │ └── redis_bit.go ├── storage.go └── bloom.go /README.md: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bloom_test.go: -------------------------------------------------------------------------------- 1 | package bloom 2 | 3 | 4 | -------------------------------------------------------------------------------- /storage/redis_bit/redis_bit.go: -------------------------------------------------------------------------------- 1 | package redis_bit 2 | 3 | 4 | -------------------------------------------------------------------------------- /storage.go: -------------------------------------------------------------------------------- 1 | package bloom 2 | 3 | type Storager interface { 4 | Init(errRate float64, elements uint) error 5 | Add(key string, value interface{}) error 6 | Exist(key string, value interface{}) (bool, error) 7 | } 8 | -------------------------------------------------------------------------------- /bloom.go: -------------------------------------------------------------------------------- 1 | package bloom 2 | 3 | import "math" 4 | 5 | type Bloom struct { 6 | Storage Storager 7 | Config *Config 8 | } 9 | 10 | type Config struct { 11 | ErrorRate float64 12 | Elements uint 13 | BitNumbers uint 14 | HashNumbers uint 15 | } 16 | 17 | func (l *Bloom) New(config *Config) *Bloom { 18 | if config.ErrorRate == 0 { 19 | config.ErrorRate = 0.001 20 | } 21 | if config.Elements == 0 { 22 | config.Elements = 1000 23 | } 24 | 25 | if config.BitNumbers == 0 || config.HashNumbers == 0 { 26 | config.BitNumbers, config.HashNumbers = l.Estimate(config.Elements, config.ErrorRate) 27 | } 28 | 29 | return &Bloom{ 30 | Config: config, 31 | } 32 | } 33 | 34 | func (l *Bloom) UseStorage(s Storager) *Bloom { 35 | if s == nil { 36 | panic("storage is nil.") 37 | } 38 | l.Storage = s 39 | return l 40 | } 41 | 42 | func (l *Bloom) Exist(key string, value interface{}) (ex bool, err error) { 43 | // get 44 | return l.Storage.Exist(key, value) 45 | } 46 | 47 | // get need bit numbers and hash func numbers 48 | func (l *Bloom) Estimate(n uint, p float64) (uint, uint) { 49 | m := math.Ceil(float64(n) * math.Log(p) / math.Log(1.0/math.Pow(2.0, math.Ln2))) 50 | k := math.Ln2*m/float64(n) + 0.5 51 | return uint(m), uint(k) 52 | } --------------------------------------------------------------------------------