-
Notifications
You must be signed in to change notification settings - Fork 664
/
filter.go
51 lines (39 loc) · 994 Bytes
/
filter.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package bloom
import (
"errors"
"github.com/ava-labs/avalanchego/utils/bloom"
)
const bytesPerHash = 8
var (
_ Filter = (*filter)(nil)
errMaxBytes = errors.New("too large")
)
type Filter interface {
// Add adds to filter, assumed thread safe
Add(...[]byte)
// Check checks filter, assumed thread safe
Check([]byte) bool
}
func New(maxN int, p float64, maxBytes int) (Filter, error) {
numHashes, numEntries := bloom.OptimalParameters(maxN, p)
if neededBytes := 1 + numHashes*bytesPerHash + numEntries; neededBytes > maxBytes {
return nil, errMaxBytes
}
f, err := bloom.New(numHashes, numEntries)
return &filter{
filter: f,
}, err
}
type filter struct {
filter *bloom.Filter
}
func (f *filter) Add(bl ...[]byte) {
for _, b := range bl {
bloom.Add(f.filter, b, nil)
}
}
func (f *filter) Check(b []byte) bool {
return bloom.Contains(f.filter, b, nil)
}