forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 4
/
filter_param.go
87 lines (68 loc) · 1.42 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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package pubsub
import (
"sync"
"github.com/MetalBlockchain/metalgo/utils/bloom"
"github.com/MetalBlockchain/metalgo/utils/set"
)
type FilterParam struct {
lock sync.RWMutex
set set.Set[string]
filter bloom.Filter
}
func NewFilterParam() *FilterParam {
return &FilterParam{
set: set.Set[string]{},
}
}
func (f *FilterParam) NewSet() {
f.lock.Lock()
defer f.lock.Unlock()
f.set = set.Set[string]{}
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
}
return f.set.Contains(string(addr))
}
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.Add(string(b))
}
return nil
}
func (f *FilterParam) Len() int {
f.lock.RLock()
defer f.lock.RUnlock()
return len(f.set)
}