Debian Codegraph @

bloomring.go

raw symbols ◀ ▶ SCIP
2 Debian patches touch this file
•1 package bloomring
2
3 import (
•4 "github.com/v2fly/ss-bloomring/bloom"
5 "hash/fnv"
6 "sync"
7 )
8
9 // simply use Double FNV here as our Bloom Filter hash
10 func doubleFNV(b []byte) (uint64, uint64) {
11 hx := fnv.New64()
12 hx.Write(b)
13 x := hx.Sum64()
14 hy := fnv.New64a()
15 hy.Write(b)
16 y := hy.Sum64()
17 return x, y
18 }
19
20 type BloomRing struct {
21 slotCapacity int
22 slotPosition int
23 slotCount int
24 entryCounter int
25 slots []bloom.Filter
26 mutex sync.RWMutex
27 }
28
29 func NewBloomRing(slot, capacity int, falsePositiveRate float64) *BloomRing {
30 // Calculate entries for each slot
31 r := &BloomRing{
32 slotCapacity: capacity / slot,
33 slotCount: slot,
34 slots: make([]bloom.Filter, slot),
35 }
36 for i := 0; i < slot; i++ {
37 r.slots[i] = bloom.New(r.slotCapacity, falsePositiveRate, doubleFNV)
38 }
39 return r
40 }
41
42 func (r *BloomRing) Add(b []byte) {
43 if r == nil {
44 return
45 }
46 r.mutex.Lock()
47 defer r.mutex.Unlock()
48 slot := r.slots[r.slotPosition]
49 if r.entryCounter > r.slotCapacity {
50 // Move to next slot and reset
51 r.slotPosition = (r.slotPosition + 1) % r.slotCount
52 slot = r.slots[r.slotPosition]
53 slot.Reset()
54 r.entryCounter = 0
55 }
56 r.entryCounter++
57 slot.Add(b)
58 }
59
60 func (r *BloomRing) Test(b []byte) bool {
61 if r == nil {
62 return false
63 }
64 r.mutex.RLock()
65 defer r.mutex.RUnlock()
66 for _, s := range r.slots {
67 if s.Test(b) {
68 return true
69 }
70 }
71 return false
72 }