-
Notifications
You must be signed in to change notification settings - Fork 1
/
trie_test.go
913 lines (809 loc) · 23 KB
/
trie_test.go
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
package trie
import (
"math/rand"
"testing"
"github.com/probe-lab/go-libdht/kad"
"github.com/probe-lab/go-libdht/kad/kadtest"
"github.com/probe-lab/go-libdht/kad/key"
"github.com/stretchr/testify/require"
)
func trieFromKeys[K kad.Key[K], D any](kks []K) (*Trie[K, D], error) {
t := New[K, D]()
var err error
for _, kk := range kks {
var v D
t, err = Add(t, kk, v)
if err != nil {
return nil, err
}
}
return t, nil
}
func TestRepeatedAddRemove(t *testing.T) {
r := New[kadtest.Key32, int]()
testSeq(t, r)
testSeq(t, r)
}
func testSeq(t *testing.T, tr *Trie[kadtest.Key32, int]) {
t.Helper()
var err error
for _, s := range testInsertSeq {
var v int
tr, err = Add(tr, s.key, v)
if err != nil {
t.Fatalf("unexpected error during add: %v", err)
}
found, depth := Locate(tr, s.key)
if !found {
t.Fatalf("key not found: %v", s.key)
}
if depth != s.insertedDepth {
t.Errorf("inserting expected depth %d, got %d", s.insertedDepth, depth)
}
if d := CheckInvariant(tr); d != nil {
t.Fatalf("trie invariant discrepancy: %v", d)
}
}
for _, s := range testRemoveSeq {
tr, err = Remove(tr, s.key)
if err != nil {
t.Fatalf("unexpected error during remove: %v", err)
}
found, _ := Locate(tr, s.key)
if found {
t.Fatalf("key unexpectedly found: %v", s.key)
}
if d := CheckInvariant(tr); d != nil {
t.Fatalf("trie invariant discrepancy: %v", d)
}
}
}
func TestCopy(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, int](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
copy := tr.Copy()
if d := CheckInvariant(copy); d != nil {
t.Fatalf("trie invariant discrepancy: %v", d)
}
if tr == copy {
t.Errorf("Expected trie copy not to be the same reference as original")
}
if !Equal(tr, copy) {
t.Errorf("Expected tries to be equal, original: %v\n, copy: %v\n", tr, copy)
}
}
var testInsertSeq = []struct {
key kadtest.Key32
insertedDepth int
}{
{key: kadtest.Key32(0x00000000), insertedDepth: 0},
{key: kadtest.Key32(0x80000000), insertedDepth: 1},
{key: kadtest.Key32(0x10000000), insertedDepth: 4},
{key: kadtest.Key32(0xc0000000), insertedDepth: 2},
{key: kadtest.Key32(0x20000000), insertedDepth: 3},
}
var testRemoveSeq = []struct {
key kadtest.Key32
reachedDepth int
}{
{key: kadtest.Key32(0x00000000), reachedDepth: 4},
{key: kadtest.Key32(0x10000000), reachedDepth: 3},
{key: kadtest.Key32(0x20000000), reachedDepth: 1},
{key: kadtest.Key32(0x80000000), reachedDepth: 2},
{key: kadtest.Key32(0xc0000000), reachedDepth: 0},
}
func TestAddIsOrderIndependent(t *testing.T) {
for _, s := range newKeySetList(100) {
base := New[kadtest.Key32, any]()
for _, k := range s.Keys {
base.Add(k, nil)
}
if d := CheckInvariant(base); d != nil {
t.Fatalf("base trie invariant discrepancy: %v", d)
}
for j := 0; j < 100; j++ {
perm := rand.Perm(len(s.Keys))
reordered := New[kadtest.Key32, any]()
for i := range s.Keys {
reordered.Add(s.Keys[perm[i]], nil)
}
if d := CheckInvariant(reordered); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
if !Equal(base, reordered) {
t.Errorf("trie %v differs from trie %v", base, reordered)
}
}
}
}
func TestImmutableAddIsOrderIndependent(t *testing.T) {
for _, s := range newKeySetList(100) {
base := New[kadtest.Key32, any]()
for _, k := range s.Keys {
base, _ = Add(base, k, nil)
}
if d := CheckInvariant(base); d != nil {
t.Fatalf("base trie invariant discrepancy: %v", d)
}
for j := 0; j < 100; j++ {
perm := rand.Perm(len(s.Keys))
reordered := New[kadtest.Key32, any]()
for i := range s.Keys {
reordered, _ = Add(reordered, s.Keys[perm[i]], nil)
}
if d := CheckInvariant(reordered); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
if !Equal(base, reordered) {
t.Errorf("trie %v differs from trie %v", base, reordered)
}
}
}
}
func TestSize(t *testing.T) {
tr := New[kadtest.Key32, any]()
require.Equal(t, 0, tr.Size())
var err error
for _, kk := range sampleKeySet.Keys {
tr, err = Add(tr, kk, nil)
require.NoError(t, err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
}
func TestImmutableAddReturnsNewTrie(t *testing.T) {
tr := New[kadtest.Key32, any]()
for _, kk := range sampleKeySet.Keys {
var err error
trBefore := *tr // take a copy of tr before Add is called
trNext, err := Add(tr, kk, nil)
require.NoError(t, err)
// a new trie must be returned
require.NotSame(t, tr, trNext)
// old trie must be not be modified
require.EqualValues(t, trBefore, *tr)
tr = trNext
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
}
func TestAddIgnoresDuplicates(t *testing.T) {
tr := New[kadtest.Key32, any]()
for _, kk := range sampleKeySet.Keys {
added := tr.Add(kk, nil)
require.True(t, added)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
for _, kk := range sampleKeySet.Keys {
added := tr.Add(kk, nil)
require.False(t, added)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestImmutableAddIgnoresDuplicates(t *testing.T) {
tr := New[kadtest.Key32, any]()
var err error
for _, kk := range sampleKeySet.Keys {
tr, err = Add(tr, kk, nil)
require.NoError(t, err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
for _, kk := range sampleKeySet.Keys {
tr, err = Add(tr, kk, nil)
require.NoError(t, err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestImmutableAddReturnsOriginalTrieForDuplicates(t *testing.T) {
tr := New[kadtest.Key32, any]()
var err error
for _, kk := range sampleKeySet.Keys {
tr, err = Add(tr, kk, nil)
require.NoError(t, err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
for _, kk := range sampleKeySet.Keys {
next, err := Add(tr, kk, nil)
require.NoError(t, err)
// trie has not been changed
require.Same(t, tr, next)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestAddWithData(t *testing.T) {
tr := New[kadtest.Key32, int]()
for i, kk := range sampleKeySet.Keys {
added := tr.Add(kk, i)
require.True(t, added)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
for i, kk := range sampleKeySet.Keys {
found, v := Find(tr, kk)
require.True(t, found)
require.Equal(t, i, v)
}
}
func TestImmutableAddWithData(t *testing.T) {
tr := New[kadtest.Key32, int]()
for i, kk := range sampleKeySet.Keys {
var err error
trNext, err := Add(tr, kk, i)
require.NoError(t, err)
// a new trie must be returned
require.NotSame(t, tr, trNext)
tr = trNext
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
for i, kk := range sampleKeySet.Keys {
found, v := Find(tr, kk)
require.True(t, found)
require.Equal(t, i, v)
}
}
func TestRemove(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
removed := tr.Remove(sampleKeySet.Keys[0])
require.True(t, removed)
require.Equal(t, len(sampleKeySet.Keys)-1, tr.Size())
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestImmutableRemove(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
trNext, err := Remove(tr, sampleKeySet.Keys[0])
require.NoError(t, err)
require.Equal(t, len(sampleKeySet.Keys)-1, trNext.Size())
// a new trie must be returned
require.NotSame(t, tr, trNext)
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestRemoveFromEmpty(t *testing.T) {
tr := New[kadtest.Key32, any]()
removed := tr.Remove(sampleKeySet.Keys[0])
require.False(t, removed)
require.Equal(t, 0, tr.Size())
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestImmutableRemoveFromEmpty(t *testing.T) {
tr := New[kadtest.Key32, any]()
trNext, err := Remove(tr, sampleKeySet.Keys[0])
require.NoError(t, err)
require.Equal(t, 0, tr.Size())
// trie has not been changed
require.Same(t, tr, trNext)
}
func TestRemoveUnknown(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
unknown := newKeyNotInSet(sampleKeySet.Keys[0].BitLen(), sampleKeySet)
removed := tr.Remove(unknown)
require.False(t, removed)
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
if d := CheckInvariant(tr); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestImmutableRemoveUnknown(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
require.Equal(t, len(sampleKeySet.Keys), tr.Size())
unknown := newKeyNotInSet(sampleKeySet.Keys[0].BitLen(), sampleKeySet)
trNext, err := Remove(tr, unknown)
require.NoError(t, err)
// trie has not been changed
require.Same(t, tr, trNext)
if d := CheckInvariant(trNext); d != nil {
t.Fatalf("reordered trie invariant discrepancy: %v", d)
}
}
func TestEqual(t *testing.T) {
a, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
b, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
require.True(t, Equal(a, b))
sampleKeySet2 := newKeySetOfLength(12, 64)
c, err := trieFromKeys[kadtest.Key32, any](sampleKeySet2.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
require.False(t, Equal(a, c))
}
func TestFindNoData(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
for _, kk := range sampleKeySet.Keys {
found, _ := Find(tr, kk)
require.True(t, found)
}
}
func TestFindNotFound(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys[1:])
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
found, _ := Find(tr, sampleKeySet.Keys[0])
require.False(t, found)
}
func TestFindMismatchedKeyLength(t *testing.T) {
tr, err := trieFromKeys[kadtest.Key32, any](sampleKeySet.Keys)
if err != nil {
t.Fatalf("unexpected error during from keys: %v", err)
}
found, _ := Find(tr, kadtest.RandomKey())
require.False(t, found)
}
func TestFindWithData(t *testing.T) {
tr := New[kadtest.Key32, int]()
var err error
for i, kk := range sampleKeySet.Keys {
tr, err = Add(tr, kk, i)
require.NoError(t, err)
}
for i, kk := range sampleKeySet.Keys {
found, v := Find(tr, kk)
require.True(t, found)
require.Equal(t, i, v)
}
}
func TestClosest(t *testing.T) {
key0 := kadtest.Key8(0)
keys := []kadtest.Key8{
kadtest.Key8(0b00010000),
kadtest.Key8(0b00100000),
kadtest.Key8(0b00110000),
kadtest.Key8(0b00111000),
kadtest.Key8(0b00011000),
kadtest.Key8(0b00011100),
kadtest.Key8(0b00000110),
kadtest.Key8(0b00000101),
kadtest.Key8(0b00000100),
kadtest.Key8(0b00001000),
kadtest.Key8(0b00001100),
}
tr, err := trieFromKeys[kadtest.Key8, int](keys)
require.NoError(t, err)
requireEntriesOrdered := func(t *testing.T, target kadtest.Key8, found []Entry[kadtest.Key8, int]) {
t.Helper()
for i := range found {
t.Logf("found[%d]=%v (distance=%v)", i, found[i].Key, target.Xor(found[i].Key))
// assert that first key is closer or same as every other possible key
if i == 0 {
distanceFirst := target.Xor(found[0].Key)
for i, k := range keys {
// skip target and first key
if key.Equal(target, k) || key.Equal(found[0].Key, k) {
continue
}
distanceKey := target.Xor(k)
t.Logf("first result distance to target=%v, distance to key[%d]=%v", distanceFirst, i, distanceKey)
require.True(t, distanceFirst.Compare(distanceKey) <= 0, "distance from first(key:%v) to target(key:%v)=%v, distance to key[%d](key:%v)=%v", found[0].Key, distanceFirst, target, i, k, distanceKey)
}
continue
}
// assert that this key is further or same as the previous key
distancePrev := target.Xor(found[i-1].Key)
distanceThis := target.Xor(found[i].Key)
require.True(t, distancePrev.Compare(distanceThis) <= 0, "distance[%d]=%v, distance[%d]=%v", i-1, distancePrev, i, distanceThis)
}
}
t.Run("zero", func(t *testing.T) {
// find the 5 nearest keys to the zero key
found := Closest(tr, key0, 5)
require.Equal(t, 5, len(found))
requireEntriesOrdered(t, key0, found)
})
t.Run("key8", func(t *testing.T) {
// find the 3 nearest keys to keys[8]
found := Closest(tr, keys[8], 3)
require.Equal(t, 3, len(found))
requireEntriesOrdered(t, keys[8], found)
})
t.Run("key3overflow", func(t *testing.T) {
// find the more than available number of keys close to keys[3]
found := Closest(tr, keys[3], 20)
require.Equal(t, len(keys), len(found))
requireEntriesOrdered(t, keys[3], found)
})
}
func BenchmarkBuildTrieMutable(b *testing.B) {
b.Run("1000", benchmarkBuildTrieMutable(1000))
b.Run("10000", benchmarkBuildTrieMutable(10000))
b.Run("100000", benchmarkBuildTrieMutable(100000))
}
func BenchmarkBuildTrieImmutable(b *testing.B) {
b.Run("1000", benchmarkBuildTrieImmutable(1000))
b.Run("10000", benchmarkBuildTrieImmutable(10000))
b.Run("100000", benchmarkBuildTrieImmutable(100000))
}
func BenchmarkAddMutable(b *testing.B) {
b.Run("1000", benchmarkAddMutable(1000))
b.Run("10000", benchmarkAddMutable(10000))
b.Run("100000", benchmarkAddMutable(100000))
}
func BenchmarkAddImmutable(b *testing.B) {
b.Run("1000", benchmarkAddImmutable(1000))
b.Run("10000", benchmarkAddImmutable(10000))
b.Run("100000", benchmarkAddImmutable(100000))
}
func BenchmarkRemoveMutable(b *testing.B) {
b.Run("1000", benchmarkRemoveMutable(1000))
b.Run("10000", benchmarkRemoveMutable(10000))
b.Run("100000", benchmarkRemoveMutable(100000))
}
func BenchmarkRemoveImmutable(b *testing.B) {
b.Run("1000", benchmarkRemoveImmutable(1000))
b.Run("10000", benchmarkRemoveImmutable(10000))
b.Run("100000", benchmarkRemoveImmutable(100000))
}
func BenchmarkFindPositive(b *testing.B) {
b.Run("1000", benchmarkFindPositive(1000))
b.Run("10000", benchmarkFindPositive(10000))
b.Run("100000", benchmarkFindPositive(100000))
}
func BenchmarkFindNegative(b *testing.B) {
b.Run("1000", benchmarkFindNegative(1000))
b.Run("10000", benchmarkFindNegative(10000))
b.Run("100000", benchmarkFindNegative(100000))
}
func benchmarkBuildTrieMutable(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
tr := New[kadtest.Key32, any]()
for _, kk := range keys {
tr.Add(kk, nil)
}
}
kadtest.ReportTimePerItemMetric(b, n, "key")
}
}
func benchmarkBuildTrieImmutable(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
tr := New[kadtest.Key32, any]()
for _, kk := range keys {
tr, _ = Add(tr, kk, nil)
}
}
kadtest.ReportTimePerItemMetric(b, n, "key")
}
}
func benchmarkAddMutable(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
tr := New[kadtest.Key32, any]()
for _, kk := range keys {
tr, _ = Add(tr, kk, nil)
}
// number of additions has to be large enough so that benchmarking takes
// more time than cloning the trie
// see https://github.com/golang/go/issues/27217
additions := make([]kadtest.Key32, n/4)
for i := range additions {
additions[i] = kadtest.RandomKey()
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
b.StopTimer()
trclone := tr.Copy()
b.StartTimer()
for _, kk := range additions {
trclone.Add(kk, nil)
}
}
kadtest.ReportTimePerItemMetric(b, len(additions), "key")
}
}
func benchmarkAddImmutable(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
trBase := New[kadtest.Key32, any]()
for _, kk := range keys {
trBase, _ = Add(trBase, kk, nil)
}
additions := make([]kadtest.Key32, n/4)
for i := range additions {
additions[i] = kadtest.RandomKey()
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
tr := trBase
for _, kk := range additions {
tr, _ = Add(tr, kk, nil)
}
}
kadtest.ReportTimePerItemMetric(b, len(additions), "key")
}
}
func benchmarkRemoveMutable(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
tr := New[kadtest.Key32, any]()
for _, kk := range keys {
tr, _ = Add(tr, kk, nil)
}
// number of removals has to be large enough so that benchmarking takes
// more time than cloning the trie
// see https://github.com/golang/go/issues/27217
removals := make([]kadtest.Key32, n/4)
for i := range removals {
removals[i] = keys[i*4] // every 4th key
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
b.StopTimer()
trclone := tr.Copy()
b.StartTimer()
for _, kk := range removals {
trclone.Remove(kk)
}
}
kadtest.ReportTimePerItemMetric(b, len(removals), "key")
}
}
func benchmarkRemoveImmutable(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
trBase := New[kadtest.Key32, any]()
for _, kk := range keys {
trBase, _ = Add(trBase, kk, nil)
}
removals := make([]kadtest.Key32, n/4)
for i := range removals {
removals[i] = keys[i*4] // every 4th key
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
tr := trBase
for _, kk := range removals {
tr, _ = Remove(tr, kk)
}
}
kadtest.ReportTimePerItemMetric(b, len(removals), "key")
}
}
func benchmarkFindPositive(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
tr := New[kadtest.Key32, any]()
for _, kk := range keys {
tr, _ = Add(tr, kk, nil)
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Find(tr, keys[i%len(keys)])
}
}
}
func benchmarkFindNegative(n int) func(b *testing.B) {
return func(b *testing.B) {
keys := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
keys[i] = kadtest.RandomKey()
}
tr := New[kadtest.Key32, any]()
for _, kk := range keys {
tr, _ = Add(tr, kk, nil)
}
unknown := make([]kadtest.Key32, n)
for i := 0; i < n; i++ {
kk := kadtest.RandomKey()
if found, _ := Find(tr, kk); found {
continue
}
unknown[i] = kk
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
Find(tr, unknown[i%len(unknown)])
}
}
}
type keySet struct {
Keys []kadtest.Key32
}
var sampleKeySet = newKeySetOfLength(12, 64)
func newKeySetList(n int) []*keySet {
s := make([]*keySet, n)
for i := range s {
s[i] = newKeySetOfLength(31, 32)
}
return s
}
func newKeySetOfLength(n int, bits int) *keySet {
set := make([]kadtest.Key32, 0, n)
seen := make(map[string]bool)
for len(set) < n {
kk := kadtest.RandomKey()
if seen[kk.String()] {
continue
}
seen[kk.String()] = true
set = append(set, kk)
}
return &keySet{
Keys: set,
}
}
func newKeyNotInSet(bits int, ks *keySet) kadtest.Key32 {
seen := make(map[string]bool)
for i := range ks.Keys {
seen[ks.Keys[i].String()] = true
}
kk := kadtest.RandomKey()
for seen[kk.String()] {
kk = kadtest.RandomKey()
}
return kk
}
type InvariantDiscrepancy struct {
Reason string
PathToDiscrepancy string
KeyAtDiscrepancy string
}
// CheckInvariant panics of the trie does not meet its invariant.
func CheckInvariant[K kad.Key[K], D any](tr *Trie[K, D]) *InvariantDiscrepancy {
return checkInvariant(tr, 0, nil)
}
func checkInvariant[K kad.Key[K], D any](tr *Trie[K, D], depth int, pathSoFar *triePath[K]) *InvariantDiscrepancy {
switch {
case tr.IsEmptyLeaf():
return nil
case tr.IsNonEmptyLeaf():
if !pathSoFar.matchesKey(*tr.key) {
return &InvariantDiscrepancy{
Reason: "key found at invalid location in trie",
PathToDiscrepancy: pathSoFar.BitString(),
KeyAtDiscrepancy: key.BitString(*tr.key),
}
}
return nil
default:
if !tr.HasKey() {
b0, b1 := tr.branch[0], tr.branch[1]
if d0 := checkInvariant(b0, depth+1, pathSoFar.Push(0)); d0 != nil {
return d0
}
if d1 := checkInvariant(b1, depth+1, pathSoFar.Push(1)); d1 != nil {
return d1
}
switch {
case b0.IsEmptyLeaf() && b1.IsEmptyLeaf():
return &InvariantDiscrepancy{
Reason: "intermediate node with two empty leaves",
PathToDiscrepancy: pathSoFar.BitString(),
KeyAtDiscrepancy: "none",
}
case b0.IsEmptyLeaf() && b1.IsNonEmptyLeaf():
return &InvariantDiscrepancy{
Reason: "intermediate node with one empty leaf/0",
PathToDiscrepancy: pathSoFar.BitString(),
KeyAtDiscrepancy: "none",
}
case b0.IsNonEmptyLeaf() && b1.IsEmptyLeaf():
return &InvariantDiscrepancy{
Reason: "intermediate node with one empty leaf/1",
PathToDiscrepancy: pathSoFar.BitString(),
KeyAtDiscrepancy: "none",
}
default:
return nil
}
} else {
return &InvariantDiscrepancy{
Reason: "intermediate node with a key",
PathToDiscrepancy: pathSoFar.BitString(),
KeyAtDiscrepancy: key.BitString(*tr.key),
}
}
}
}
type triePath[K kad.Key[K]] struct {
parent *triePath[K]
bit byte
}
func (p *triePath[K]) Push(bit byte) *triePath[K] {
return &triePath[K]{parent: p, bit: bit}
}
func (p *triePath[K]) RootPath() []byte {
if p == nil {
return nil
} else {
return append(p.parent.RootPath(), p.bit)
}
}
func (p *triePath[K]) matchesKey(kk K) bool {
ok, _ := p.walk(kk, 0)
return ok
}
func (p *triePath[K]) walk(kk K, depthToLeaf int) (ok bool, depthToRoot int) {
if p == nil {
return true, 0
} else {
parOk, parDepthToRoot := p.parent.walk(kk, depthToLeaf+1)
return kk.Bit(parDepthToRoot) == uint(p.bit) && parOk, parDepthToRoot + 1
}
}
func (p *triePath[K]) BitString() string {
return p.bitString(0)
}
func (p *triePath[K]) bitString(depthToLeaf int) string {
if p == nil {
return ""
} else {
switch {
case p.bit == 0:
return p.parent.bitString(depthToLeaf+1) + "0"
case p.bit == 1:
return p.parent.bitString(depthToLeaf+1) + "1"
default:
panic("bit digit > 1")
}
}
}