Debian Codegraph @

gopls/internal/bloom/filter_test.go

raw symbols SCIP
1 // Copyright 2024 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
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 // First, sanity check that the filter contains all the given elements.
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 // Measure the false positives rate.
27 //
28 // Of course, we can't assert on the results, since they are probabilistic,
29 // but this can be useful for interactive use.
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 // In practice, all positives below will be false, but be precise anyway.
35 truePositive := make(map[string]bool)
36 for _, e := range elems {
37 truePositive[e] = true
38 }
39
40 // Generate a large number of random strings to measure the false positive
41 // rate.
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 // falsePositiveRate estimates the expected false positive rate for a filter
59 // with the given number of blocks, seeds, and elements.
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) // length
75 var runes []rune
76 for range l {
77 runes = append(runes, rune(' '+rand.IntN('~'-' ')))
78 }
79 return string(runes)
80 }
81
82 // TestDegenerateFilter checks that the degenerate filter with no elements
83 // results in no false positives.
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 }