-
Notifications
You must be signed in to change notification settings - Fork 10
/
filter.go
340 lines (293 loc) · 7.9 KB
/
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
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// Copyright (c) 2018 ContentBox Authors.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package bloom
import (
"bytes"
"errors"
"math"
"sync"
conv "github.com/BOXFoundation/boxd/p2p/convert"
"github.com/BOXFoundation/boxd/util"
"github.com/BOXFoundation/boxd/util/murmur3"
)
const ln2Squared = math.Ln2 * math.Ln2
const (
// MaxFilterHashFuncs is the maximum number of hash functions of bloom filter.
MaxFilterHashFuncs = 256
// MaxFilterSize is the maximum byte size in bytes a filter may be.
MaxFilterSize = 1024 * 1024
// DefaultConflictRate is the default conflict rate for any key.
DefaultConflictRate = 0.0001
)
// Filter defines bloom filter interface
type Filter interface {
Matches(data []byte) bool
Add(data []byte)
MatchesAndAdd(data []byte) bool
Merge(f Filter) error
Reset()
Copy(f Filter) error
Size() uint32
K() uint32
Tweak() uint32
FPRate() float64
GetByte(i uint32) byte
Indexes() []uint32
IsEmpty() bool
conv.Serializable
}
// filter implements the bloom-filter
type filter struct {
sm sync.Mutex
filter []byte
hashFuncs uint32
tweak uint32
}
// NewFilterWithMK returns a Filter.
// M is the cap of the bloom filter
// K is the number of hash functions
func NewFilterWithMK(m uint32, k uint32) Filter {
return newFilter(m, k, 0)
}
// NewFilterWithMKAndTweak returns a Filter with specific tweak for hash seed.
// M is the cap of the bloom filter
// K is the number of hash functions
func NewFilterWithMKAndTweak(m uint32, k uint32, tweak uint32) Filter {
return newFilter(m, k, tweak)
}
func newFilter(m uint32, k uint32, tweak uint32) Filter {
if m <= 0 {
m = 1
}
if k <= 0 {
k = 1
}
dataLen := uint32(math.Ceil(float64(m) / 8.))
if MaxFilterSize < dataLen {
dataLen = MaxFilterSize
}
hashFuncs := k
if MaxFilterHashFuncs < hashFuncs {
hashFuncs = MaxFilterHashFuncs
}
data := make([]byte, dataLen)
return &filter{
filter: data,
hashFuncs: hashFuncs,
tweak: tweak,
}
}
// NewFilter returns a Filter
func NewFilter(elements uint32, fprate float64) Filter {
return NewFilterWithTweak(elements, fprate, 0)
}
// NewFilterWithTweak returns a Filter with with specific tweak for hash seed
func NewFilterWithTweak(elements uint32, fprate float64, tweak uint32) Filter {
// Massage the false positive rate to sane values.
if fprate > 1.0 {
fprate = 1.0
} else if fprate < 1e-9 {
fprate = 1e-9
}
// Calculate the size of the filter in bits for the given number of
// elements and false positive rate.
m := uint32(math.Ceil(float64(-1 * float64(elements) * math.Log(fprate) / ln2Squared)))
// Calculate the number of hash functions based on the size of the
// filter calculated above and the number of elements.
k := uint32(math.Ceil(math.Ln2 * float64(m) / float64(elements)))
return newFilter(m, k, tweak)
}
// LoadFilter loads bloom filter from serialized data.
func LoadFilter(data []byte) (Filter, error) {
var f = &filter{}
if err := f.Unmarshal(data); err != nil {
return nil, err
}
return f, nil
}
// hash returns the bit offset in the bloom filter which corresponds to the
// passed data for the given indepedent hash function number.
func (bf *filter) hash(hashFuncNum uint32, data []byte) uint32 {
h32 := murmur3.MurmurHash3WithSeed(data, hashFuncNum*0xfba4c795+bf.tweak)
return h32 % (uint32(len(bf.filter)) << 3)
}
// matches returns true if the bloom filter might contain the passed data and
// false if it definitely does not.
func (bf *filter) matches(data []byte) bool {
// idx >> 3 = idx / 8 : byte index in the byte slice
// 1<<(idx&7) = idx % 8 : bit index in the byte
for i := uint32(0); i < bf.hashFuncs; i++ {
idx := bf.hash(i, data)
if bf.filter[idx>>3]&(1<<(idx&7)) == 0 {
return false
}
}
return true
}
// Matches returns true if the bloom filter might contain the passed data and
// false if it definitely does not.
func (bf *filter) Matches(data []byte) bool {
bf.sm.Lock()
match := bf.matches(data)
bf.sm.Unlock()
return match
}
// add adds the passed byte slice to the bloom filter.
func (bf *filter) add(data []byte) {
for i := uint32(0); i < bf.hashFuncs; i++ {
idx := bf.hash(i, data)
bf.filter[idx>>3] |= (1 << (7 & idx))
}
}
// Add adds the passed byte slice to the bloom filter.
func (bf *filter) Add(data []byte) {
bf.sm.Lock()
bf.add(data)
bf.sm.Unlock()
}
// matchesAndAdd adds the passed byte slice to the bloom filter.
func (bf *filter) matchesAndAdd(data []byte) (r bool) {
r = true
for i := uint32(0); i < bf.hashFuncs; i++ {
idx := bf.hash(i, data)
if bf.filter[idx>>3]&(1<<(idx&7)) == 0 {
bf.filter[idx>>3] |= (1 << (7 & idx))
r = false
}
}
return r
}
// MatchesAndAdd matchs the passed data, and add it to the bloom filter in case of false
func (bf *filter) MatchesAndAdd(data []byte) (r bool) {
bf.sm.Lock()
match := bf.matchesAndAdd(data)
bf.sm.Unlock()
return match
}
// merge merges the passed one with the bloom filter.
func (bf *filter) merge(f Filter) error {
var rf, ok = f.(*filter)
if !ok {
return errors.New("unknown bloom filter")
}
rf.sm.Lock()
defer rf.sm.Unlock()
if bf.hashFuncs != rf.hashFuncs {
return errors.New("HashFuncs doesn't match")
}
if len(bf.filter) != len(rf.filter) {
return errors.New("Size of filter bits doesn't match")
}
if bf.tweak != rf.tweak {
return errors.New("Seed of hash doesn't match")
}
for i := 0; i < len(bf.filter); i++ {
bf.filter[i] |= rf.filter[i]
}
return nil
}
// Merge merges the passed one with the bloom filter.
func (bf *filter) Merge(f Filter) error {
bf.sm.Lock()
err := bf.merge(f)
bf.sm.Unlock()
return err
}
// Reset reset all flag bits of the bloom filter.
func (bf *filter) Reset() {
bf.sm.Lock()
for i := 0; i < len(bf.filter); i++ {
bf.filter[i] = byte(0)
}
bf.sm.Unlock()
}
func (bf *filter) Copy(f Filter) error {
bf = NewFilterWithMK(f.Size(), f.K()).(*filter)
return bf.Merge(f)
}
// GetByte get the specified byte.
func (bf *filter) GetByte(i uint32) byte {
return bf.filter[i]
}
// Size returns the length of filter in bits.
func (bf *filter) Size() uint32 {
bf.sm.Lock()
s := uint32(len(bf.filter)) << 3
bf.sm.Unlock()
return s
}
// Size returns the number of hash functions.
func (bf *filter) K() uint32 {
return bf.hashFuncs
}
// Tweak returns the random value added to the hash seed.
func (bf *filter) Tweak() uint32 {
return bf.tweak
}
// FPRate returns the false positive probability
func (bf *filter) FPRate() float64 {
bf.sm.Lock()
var size = uint32(len(bf.filter)) << 3
var bits = bf.bitsFilled()
var frate = float64(bits) / float64(size)
var fprate = frate
for i := uint32(1); i < bf.hashFuncs; i++ {
fprate *= frate
}
bf.sm.Unlock()
return fprate
}
// bitsFilled returns how many bits were set
func (bf *filter) bitsFilled() uint32 {
var bits uint32
for i := 0; i < len(bf.filter); i++ {
b := bf.filter[i]
for idx := uint8(0); idx < 8; idx++ {
if b&(1<<idx) != 0 {
bits++
}
}
}
return bits
}
// Marshal marshals the bloom filter to a binary representation of it.
func (bf *filter) Marshal() (data []byte, err error) {
var w bytes.Buffer
if err := util.WriteUint32(&w, bf.hashFuncs); err != nil {
return nil, err
}
if err := util.WriteUint32(&w, bf.tweak); err != nil {
return nil, err
}
if err := util.WriteVarBytes(&w, bf.filter); err != nil {
return nil, err
}
return w.Bytes(), nil
}
// Unmarshal unmarshals a bloom filter from binary data.
func (bf *filter) Unmarshal(data []byte) error {
var err error
var r = bytes.NewBuffer(data)
if bf.hashFuncs, err = util.ReadUint32(r); err != nil {
return err
}
if bf.tweak, err = util.ReadUint32(r); err != nil {
return err
}
bf.filter, err = util.ReadVarBytes(r)
return err
}
// Indexes return marked indexes.
func (bf *filter) Indexes() []uint32 {
return util.BitIndexes(bf.filter)
}
// IsEmpty return whether it is empty.
func (bf *filter) IsEmpty() bool {
for _, b := range bf.filter {
if b != byte(0) {
return false
}
}
return true
}