| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package bloom |
| 6 |
|
| 7 |
import ( |
| 8 |
"math" |
| 9 |
"math/rand/v2" |
| 10 |
"testing" |
| 11 |
) |
| 12 |
|
| 13 |
func TestFilter(t *testing.T) { |
| 14 |
elems := []string{ |
| 15 |
"a", "apple", "b", "banana", "an arbitrarily long string", "", "世界", |
| 16 |
} |
| 17 |
|
| 18 |
|
| 19 |
f := NewFilter(elems) |
| 20 |
for _, elem := range elems { |
| 21 |
if got := f.MayContain(elem); !got { |
| 22 |
t.Errorf("MayContain(%q) = %t, want true", elem, got) |
| 23 |
} |
| 24 |
} |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
fpRate := falsePositiveRate(len(f.blocks), len(f.seeds), len(elems)) |
| 32 |
t.Logf("%d blocks, %d seeds, %.2g%% expected false positives", len(f.blocks), len(f.seeds), 100*fpRate) |
| 33 |
|
| 34 |
|
| 35 |
truePositive := make(map[string]bool) |
| 36 |
for _, e := range elems { |
| 37 |
truePositive[e] = true |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
g := newStringGenerator() |
| 43 |
const samples = 1000 |
| 44 |
falsePositives := 0 |
| 45 |
for range samples { |
| 46 |
s := g.next() |
| 47 |
got := f.MayContain(s) |
| 48 |
if false { |
| 49 |
t.Logf("MayContain(%q) = %t", s, got) |
| 50 |
} |
| 51 |
if got && !truePositive[s] { |
| 52 |
falsePositives++ |
| 53 |
} |
| 54 |
} |
| 55 |
t.Logf("false positives: %.1f%% (%d/%d)", 100*float64(falsePositives)/float64(samples), falsePositives, samples) |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
func falsePositiveRate(block, seeds, elems int) float64 { |
| 61 |
k, m, n := float64(seeds), float64(block*blockBits), float64(elems) |
| 62 |
return math.Pow(1-math.Exp(-k*n/m), k) |
| 63 |
} |
| 64 |
|
| 65 |
type stringGenerator struct { |
| 66 |
r *rand.Rand |
| 67 |
} |
| 68 |
|
| 69 |
func newStringGenerator() *stringGenerator { |
| 70 |
return &stringGenerator{rand.New(rand.NewPCG(1, 2))} |
| 71 |
} |
| 72 |
|
| 73 |
func (g *stringGenerator) next() string { |
| 74 |
l := g.r.IntN(50) |
| 75 |
var runes []rune |
| 76 |
for range l { |
| 77 |
runes = append(runes, rune(' '+rand.IntN('~'-' '))) |
| 78 |
} |
| 79 |
return string(runes) |
| 80 |
} |
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
func TestDegenerateFilter(t *testing.T) { |
| 85 |
f := NewFilter(nil) |
| 86 |
g := newStringGenerator() |
| 87 |
for range 100 { |
| 88 |
s := g.next() |
| 89 |
if f.MayContain(s) { |
| 90 |
t.Errorf("MayContain(%q) = true, want false", s) |
| 91 |
} |
| 92 |
} |
| 93 |
} |