| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package bloom |
| 6 |
|
| 7 |
import ( |
| 8 |
"hash/maphash" |
| 9 |
"math" |
| 10 |
) |
| 11 |
|
| 12 |
|
| 13 |
type block = uint8 |
| 14 |
|
| 15 |
const blockBits = 8 |
| 16 |
|
| 17 |
|
| 18 |
type Filter struct { |
| 19 |
seeds []maphash.Seed |
| 20 |
blocks []block |
| 21 |
} |
| 22 |
|
| 23 |
|
| 24 |
func NewFilter(elems []string) *Filter { |
| 25 |
|
| 26 |
nblocks, nseeds := calibrate(0.05, len(elems)) |
| 27 |
f := &Filter{ |
| 28 |
blocks: make([]block, nblocks), |
| 29 |
seeds: make([]maphash.Seed, nseeds), |
| 30 |
} |
| 31 |
for i := range nseeds { |
| 32 |
f.seeds[i] = maphash.MakeSeed() |
| 33 |
} |
| 34 |
for _, elem := range elems { |
| 35 |
for _, seed := range f.seeds { |
| 36 |
index, bit := f.locate(seed, elem) |
| 37 |
f.blocks[index] |= bit |
| 38 |
} |
| 39 |
} |
| 40 |
return f |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
func (f *Filter) locate(seed maphash.Seed, s string) (index int, bit block) { |
| 46 |
h := uint(maphash.String(seed, s)) |
| 47 |
blk := h / blockBits % uint(len(f.blocks)) |
| 48 |
bit = block(1 << (h % blockBits)) |
| 49 |
return int(blk), bit |
| 50 |
} |
| 51 |
|
| 52 |
func assert(cond bool, msg string) { |
| 53 |
if !cond { |
| 54 |
panic(msg) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
func calibrate(fpRate float64, n int) (blocks, seeds int) { |
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
assert(0 < fpRate && fpRate < 1, "invalid false positive rate") |
| 67 |
assert(n >= 0, "invalid set size") |
| 68 |
|
| 69 |
if n == 0 { |
| 70 |
|
| 71 |
return 1, 1 |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
logFpRate := math.Log(fpRate) |
| 78 |
m := -(float64(n) * logFpRate) / (math.Ln2 * math.Ln2) |
| 79 |
blocks = int(m) / blockBits |
| 80 |
if float64(blocks*blockBits) < m { |
| 81 |
blocks += 1 |
| 82 |
} |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
k := -logFpRate / math.Ln2 |
| 91 |
seeds = max(int(math.Round(k)), 1) |
| 92 |
|
| 93 |
return blocks, seeds |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
func (f *Filter) MayContain(s string) bool { |
| 98 |
for _, seed := range f.seeds { |
| 99 |
index, bit := f.locate(seed, s) |
| 100 |
if f.blocks[index]&bit == 0 { |
| 101 |
return false |
| 102 |
} |
| 103 |
} |
| 104 |
return true |
| 105 |
} |