-
Notifications
You must be signed in to change notification settings - Fork 669
/
filter_param.go
87 lines (68 loc) · 1.39 KB
/
filter_param.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// (c) 2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package pubsub
import (
"sync"
"github.com/ava-labs/avalanchego/utils/bloom"
)
type FilterParam struct {
lock sync.RWMutex
set map[string]struct{}
filter bloom.Filter
}
func NewFilterParam() *FilterParam {
return &FilterParam{
set: make(map[string]struct{}),
}
}
func (f *FilterParam) NewSet() {
f.lock.Lock()
defer f.lock.Unlock()
f.set = make(map[string]struct{})
f.filter = nil
}
func (f *FilterParam) Filter() bloom.Filter {
f.lock.RLock()
defer f.lock.RUnlock()
return f.filter
}
func (f *FilterParam) SetFilter(filter bloom.Filter) bloom.Filter {
f.lock.Lock()
defer f.lock.Unlock()
f.filter = filter
f.set = nil
return f.filter
}
func (f *FilterParam) Check(addr []byte) bool {
f.lock.RLock()
defer f.lock.RUnlock()
if f.filter != nil && f.filter.Check(addr) {
return true
}
_, ok := f.set[string(addr)]
return ok
}
func (f *FilterParam) Add(bl ...[]byte) error {
filter := f.Filter()
if filter != nil {
filter.Add(bl...)
return nil
}
f.lock.Lock()
defer f.lock.Unlock()
if f.set == nil {
return ErrFilterNotInitialized
}
if len(f.set)+len(bl) > MaxAddresses {
return ErrAddressLimit
}
for _, b := range bl {
f.set[string(b)] = struct{}{}
}
return nil
}
func (f *FilterParam) Len() int {
f.lock.RLock()
defer f.lock.RUnlock()
return len(f.set)
}