forked from gxed/bbloom
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbbloom_test.go
More file actions
571 lines (487 loc) · 12.6 KB
/
bbloom_test.go
File metadata and controls
571 lines (487 loc) · 12.6 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
package bbloom
import (
"encoding/json"
"fmt"
"math"
"os"
"strconv"
"strings"
"testing"
)
var (
wordlist1 [][]byte
n = 1 << 16
bf Bloom
)
func TestMain(m *testing.M) {
wordlist1 = make([][]byte, n)
for i := range wordlist1 {
wordlist1[i] = []byte("word-" + strconv.Itoa(i))
}
fmt.Println("\n###############\nbbloom_test.go")
fmt.Print("Benchmarks relate to 2**16 OP. --> output/65536 op/ns\n###############\n\n")
os.Exit(m.Run())
}
func TestM_NumberOfWrongs(t *testing.T) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
cnt := 0
for i := range wordlist1 {
if !bf.AddIfNotHas(wordlist1[i]) {
cnt++
}
}
pct := float64(cnt) / float64(n) * 100
t.Logf("false positives: %d/%d (%.2f%%)", cnt, n, pct)
if pct > 1.0 {
t.Errorf("false positive rate too high: %.2f%% (expected <1%%)", pct)
}
}
func TestM_JSON(t *testing.T) {
const shallBe = int(1 << 16)
bf, err := New(float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
cnt := 0
for i := range wordlist1 {
if !bf.AddIfNotHas(wordlist1[i]) {
cnt++
}
}
json := bf.JSONMarshal()
if err != nil {
t.Fatal(err)
}
// create new bloomfilter from bloomfilter's JSON representation
bf2, err := JSONUnmarshal(json)
if err != nil {
t.Fatal(err)
}
cnt2 := 0
for i := range wordlist1 {
if !bf2.AddIfNotHas(wordlist1[i]) {
cnt2++
}
}
if cnt2 != shallBe {
t.Errorf("FAILED !AddIfNotHas = %v; want %v", cnt2, shallBe)
}
}
func TestSipHashLowAlwaysOdd(t *testing.T) {
bf, err := New(float64(1<<20), float64(7))
if err != nil {
t.Fatal(err)
}
for i := range 10000 {
entry := []byte("entry-" + strconv.Itoa(i))
l, _ := bf.sipHash(entry)
if l%2 == 0 {
t.Fatalf("l is even for entry %q: l=%d", entry, l)
}
}
}
func TestJSON_ElementsRoundTrip(t *testing.T) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
for i := range wordlist1 {
bf.Add(wordlist1[i])
}
if bf.ElementsAdded() != uint64(n) {
t.Fatalf("ElementsAdded = %d, want %d", bf.ElementsAdded(), n)
}
data := bf.JSONMarshal()
bf2, err := JSONUnmarshal(data)
if err != nil {
t.Fatal(err)
}
if bf2.ElementsAdded() != uint64(n) {
t.Fatalf("ElementsAdded after round-trip = %d, want %d", bf2.ElementsAdded(), n)
}
}
func TestJSON_ElementsBackwardCompat(t *testing.T) {
// simulate old-format JSON by marshaling a filter and stripping Elements
bf, err := New(float64(512), float64(3))
if err != nil {
t.Fatal(err)
}
bf.Add([]byte("hello"))
bf.Add([]byte("world"))
// marshal, strip Elements field, unmarshal
data := bf.JSONMarshal()
var m map[string]any
if err := json.Unmarshal(data, &m); err != nil {
t.Fatal(err)
}
delete(m, "Elements")
oldJSON, err := json.Marshal(m)
if err != nil {
t.Fatal(err)
}
bf2, err := JSONUnmarshal(oldJSON)
if err != nil {
t.Fatal(err)
}
// old format has no Elements field, so ElementsAdded should be 0
if bf2.ElementsAdded() != 0 {
t.Fatalf("ElementsAdded from old JSON = %d, want 0", bf2.ElementsAdded())
}
// but the bitset should still work
if !bf2.Has([]byte("hello")) || !bf2.Has([]byte("world")) {
t.Fatal("filter lost entries after old-format round-trip")
}
}
func TestNewWithKeys(t *testing.T) {
k0 := uint64(0x0123456789abcdef)
k1 := uint64(0xfedcba9876543210)
bf1, err := NewWithKeys(k0, k1, float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
bf2, err := New(float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
// same entry should hash to different positions with different keys
entry := []byte("test-entry")
l1, h1 := bf1.sipHash(entry)
l2, h2 := bf2.sipHash(entry)
if l1 == l2 && h1 == h2 {
t.Fatal("custom keys produced same hash as default keys")
}
// filter should still work correctly with custom keys
for i := range wordlist1 {
bf1.Add(wordlist1[i])
}
for i := range wordlist1 {
if !bf1.Has(wordlist1[i]) {
t.Fatalf("Has(%q) = false after Add", wordlist1[i])
}
}
}
func TestJSONBackwardCompatV0(t *testing.T) {
// simulate a filter created with the legacy hash (version 0)
bf, err := New(float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
bf.hashVersion = 0 // legacy
entries := wordlist1[:1000]
for _, e := range entries {
bf.Add(e)
}
// serialize (will have Version:0 which is omitted from JSON)
data := bf.JSONMarshal()
// deserialize -- should restore version 0 and use legacy hash
bf2, err := JSONUnmarshal(data)
if err != nil {
t.Fatal(err)
}
if bf2.hashVersion != 0 {
t.Fatalf("expected hashVersion 0, got %d", bf2.hashVersion)
}
for _, e := range entries {
if !bf2.Has(e) {
t.Fatalf("v0 filter lost entry %q after JSON round-trip", e)
}
}
}
func TestNewWithKeysJSON(t *testing.T) {
k0 := uint64(0x0123456789abcdef)
k1 := uint64(0xfedcba9876543210)
bf, err := NewWithKeys(k0, k1, float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
entries := wordlist1[:1000]
for _, e := range entries {
bf.Add(e)
}
data := bf.JSONMarshal()
bf2, err := JSONUnmarshal(data)
if err != nil {
t.Fatal(err)
}
// keys should be preserved
if bf2.k0 != k0 || bf2.k1 != k1 {
t.Fatalf("keys not preserved: got k0=%x k1=%x, want k0=%x k1=%x", bf2.k0, bf2.k1, k0, k1)
}
for _, e := range entries {
if !bf2.Has(e) {
t.Fatalf("custom-key filter lost entry %q after JSON round-trip", e)
}
}
}
func TestJSONRoundTripV1(t *testing.T) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
entries := wordlist1[:1000]
for _, e := range entries {
bf.Add(e)
}
data := bf.JSONMarshal()
bf2, err := JSONUnmarshal(data)
if err != nil {
t.Fatal(err)
}
if bf2.hashVersion != 1 {
t.Fatalf("expected hashVersion 1, got %d", bf2.hashVersion)
}
for _, e := range entries {
if !bf2.Has(e) {
t.Fatalf("v1 filter lost entry %q after JSON round-trip", e)
}
}
}
func TestJSONUnmarshalPartialKeys(t *testing.T) {
// Only K0 present, K1 absent -- should error, not silently fall back.
jsonK0Only := []byte(`{"FilterSet":"AAAAAAAAAA==","SetLocs":3,"K0":42}`)
if _, err := JSONUnmarshal(jsonK0Only); err == nil {
t.Fatal("expected error for JSON with K0 but no K1")
}
// Only K1 present, K0 absent.
jsonK1Only := []byte(`{"FilterSet":"AAAAAAAAAA==","SetLocs":3,"K1":99}`)
if _, err := JSONUnmarshal(jsonK1Only); err == nil {
t.Fatal("expected error for JSON with K1 but no K0")
}
}
func TestDefaultKeysOmittedFromJSON(t *testing.T) {
bf, err := New(float64(512), float64(3))
if err != nil {
t.Fatal(err)
}
bf.Add([]byte("test"))
data := bf.JSONMarshal()
s := string(data)
if strings.Contains(s, "K0") || strings.Contains(s, "K1") {
t.Fatalf("default keys should not appear in JSON: %s", s)
}
// custom keys should appear
bf2, err := NewWithKeys(42, 99, float64(512), float64(3))
if err != nil {
t.Fatal(err)
}
bf2.Add([]byte("test"))
data2 := bf2.JSONMarshal()
s2 := string(data2)
if !strings.Contains(s2, "K0") || !strings.Contains(s2, "K1") {
t.Fatalf("custom keys should appear in JSON: %s", s2)
}
}
func TestNewWithBoolsetAndKeys(t *testing.T) {
k0 := uint64(0x0123456789abcdef)
k1 := uint64(0xfedcba9876543210)
entries := wordlist1[:1000]
// Build a reference filter with custom keys and populate it.
ref, err := NewWithKeys(k0, k1, float64(n*10), float64(7))
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
ref.Add(e)
}
// Export the raw bitset so we can reconstruct with NewWithBoolsetAndKeys.
rawBitset := ref.JSONMarshal()
refImport, err := JSONUnmarshal(rawBitset)
if err != nil {
t.Fatal(err)
}
t.Run("keys are stored", func(t *testing.T) {
// NewWithBoolsetAndKeys must propagate k0/k1 into the Bloom struct,
// otherwise all lookups will use the wrong hash positions.
got := NewWithBoolsetAndKeys(make([]byte, 64), 7, k0, k1)
if got.k0 != k0 || got.k1 != k1 {
t.Fatalf("keys not set: got k0=%x k1=%x, want k0=%x k1=%x",
got.k0, got.k1, k0, k1)
}
})
t.Run("entries survive bitset round-trip", func(t *testing.T) {
// A filter rebuilt from the same bitset and keys must recognize
// every entry that was added to the original.
for _, e := range entries {
if !refImport.Has(e) {
t.Fatalf("entry %q lost after round-trip", e)
}
}
})
t.Run("wrong keys miss entries", func(t *testing.T) {
// Unmarshal the custom-key filter, then force default keys.
// Lookups must fail, proving the keys actually affect hashing.
wrong, err := JSONUnmarshal(ref.JSONMarshal())
if err != nil {
t.Fatal(err)
}
wrong.k0 = defaultK0
wrong.k1 = defaultK1
misses := 0
for _, e := range entries {
if !wrong.Has(e) {
misses++
}
}
if misses == 0 {
t.Fatal("default keys matched every entry; custom keys had no effect")
}
})
}
func TestFillRatio(t *testing.T) {
bf, err := New(float64(512), float64(7))
if err != nil {
t.Fatal(err)
}
bf.Add([]byte("test"))
r := bf.FillRatio()
if math.Abs(r-float64(7)/float64(512)) > 0.001 {
t.Error("ratio doesn't work")
}
}
func ExampleBloom_AddIfNotHas() {
bf, err := New(float64(512), float64(1))
if err != nil {
panic(err)
}
fmt.Printf("%v %v %v %v\n", bf.sizeExp, bf.size, bf.setLocs, bf.shift)
bf.Add([]byte("Manfred"))
fmt.Println("bf.Add([]byte(\"Manfred\"))")
fmt.Printf("bf.Has([]byte(\"Manfred\")) -> %v - should be true\n", bf.Has([]byte("Manfred")))
fmt.Printf("bf.Add([]byte(\"manfred\")) -> %v - should be false\n", bf.Has([]byte("manfred")))
fmt.Printf("bf.AddIfNotHas([]byte(\"Manfred\")) -> %v - should be false\n", bf.AddIfNotHas([]byte("Manfred")))
fmt.Printf("bf.AddIfNotHas([]byte(\"manfred\")) -> %v - should be true\n", bf.AddIfNotHas([]byte("manfred")))
bf.AddTS([]byte("Hans"))
fmt.Println("bf.AddTS([]byte(\"Hans\")")
fmt.Printf("bf.HasTS([]byte(\"Hans\")) -> %v - should be true\n", bf.HasTS([]byte("Hans")))
fmt.Printf("bf.AddTS([]byte(\"hans\")) -> %v - should be false\n", bf.HasTS([]byte("hans")))
fmt.Printf("bf.AddIfNotHasTS([]byte(\"Hans\")) -> %v - should be false\n", bf.AddIfNotHasTS([]byte("Hans")))
fmt.Printf("bf.AddIfNotHasTS([]byte(\"hans\")) -> %v - should be true\n", bf.AddIfNotHasTS([]byte("hans")))
// Output: 9 511 1 55
// bf.Add([]byte("Manfred"))
// bf.Has([]byte("Manfred")) -> true - should be true
// bf.Add([]byte("manfred")) -> false - should be false
// bf.AddIfNotHas([]byte("Manfred")) -> false - should be false
// bf.AddIfNotHas([]byte("manfred")) -> true - should be true
// bf.AddTS([]byte("Hans")
// bf.HasTS([]byte("Hans")) -> true - should be true
// bf.AddTS([]byte("hans")) -> false - should be false
// bf.AddIfNotHasTS([]byte("Hans")) -> false - should be false
// bf.AddIfNotHasTS([]byte("hans")) -> true - should be true
}
func BenchmarkM_New(b *testing.B) {
for r := 0; r < b.N; r++ {
_, _ = New(float64(n*10), float64(7))
}
}
func BenchmarkM_Clear(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
for i := range wordlist1 {
bf.Add(wordlist1[i])
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
bf.Clear()
}
}
func BenchmarkM_Add(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.Add(wordlist1[i])
}
}
}
func BenchmarkM_Has(b *testing.B) {
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.Has(wordlist1[i])
}
}
}
func BenchmarkM_AddIfNotHasFALSE(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
for i := range wordlist1 {
bf.Has(wordlist1[i])
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.AddIfNotHas(wordlist1[i])
}
}
}
func BenchmarkM_AddIfNotHasClearTRUE(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.AddIfNotHas(wordlist1[i])
}
bf.Clear()
}
}
func BenchmarkM_AddTS(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.AddTS(wordlist1[i])
}
}
}
func BenchmarkM_HasTS(b *testing.B) {
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.HasTS(wordlist1[i])
}
}
}
func BenchmarkM_AddIfNotHasTSFALSE(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
for i := range wordlist1 {
bf.Has(wordlist1[i])
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.AddIfNotHasTS(wordlist1[i])
}
}
}
func BenchmarkM_AddIfNotHasTSClearTRUE(b *testing.B) {
bf, err := New(float64(n*10), float64(7))
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for r := 0; r < b.N; r++ {
for i := range wordlist1 {
bf.AddIfNotHasTS(wordlist1[i])
}
bf.Clear()
}
}