-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilter.go
More file actions
76 lines (62 loc) · 1.71 KB
/
filter.go
File metadata and controls
76 lines (62 loc) · 1.71 KB
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
package dblchk
import (
"hash"
"hash/fnv"
"sync"
"sync/atomic"
)
const DEFAULT_CAPACITY uint = 1 << 16 /* 256 KiB / sizeof(uint32) */
var hashPool *sync.Pool = &sync.Pool{
New: func() any { return fnv.New32() },
}
func hashElement(element []byte) hashKey {
h := hashPool.Get().(hash.Hash32)
defer hashPool.Put(h)
h.Reset()
h.Write(element)
return hashKey(h.Sum32())
}
// Key into the filter, with a composite internal structure.
//
// The 32-bit (4-byte) layout of the key is as follows:
// Upper 16 bits (two bytes): idx
// Low 5 bits of middle byte: posA
// Low 5 bits of lower byte: posB
type hashKey uint32
func (key hashKey) index() uint16 {
return uint16(key >> 16)
}
func (key hashKey) mask() uint32 {
posA := byte((key & 0x0000_1f00) >> 8)
posB := byte(key & 0x0000_001f)
return uint32((1 << posA) | (1 << posB))
}
type Filter []uint32
// Create a new filter with the given number of 32-bit blocks.
//
// If capacity is set to 0, the default capacity of 64k (=256 KiB) is used.
func NewFilter(capacity uint) Filter {
if capacity == 0 {
capacity = DEFAULT_CAPACITY
}
return make(Filter, capacity)
}
// Add the given element to the filter.
func (filter Filter) Add(element []byte) {
hash := hashElement(element)
atomic.OrUint32(&filter[hash.index()], hash.mask())
}
// Check the filter for an element.
//
// If the method returns `true`, the element may be present in the filter.
// Otherwise, it is guaranteed not to be in the filter.
func (filter Filter) MayContain(element []byte) bool {
hash := hashElement(element)
mask := hash.mask()
block := filter[hash.index()]
return (block & mask) == mask
}
// Clear the filter, resetting it back to an empty state.
func (filter Filter) Reset() {
clear(filter)
}