-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap.go
1871 lines (1567 loc) · 55 KB
/
map.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
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package finnishtable
import (
"math/bits"
"unsafe"
_ "unsafe"
)
//go:linkname runtime_fastrand64 runtime.fastrand64
func runtime_fastrand64() uint64
const (
// Maximum number of buckets per map.
// NOTE: Must be a power of two
// NOTE: With our hashing scheme we can have up to 256 buckets per map.
maxBuckets = 32
// Aesthically pleasing load factor
lfnumerator, lfdenominator = 27, 32
maxEntriesPerMap = maxBuckets * bucketSize
// How many splits to do before recalculating the hash for the keys? This
// also ensures that at least 8-(triehashBoundary) bits are always usable
// when matching hashes.
triehashBoundary = 4
// Maximum number of buckets to probe before switching to the sorted array.
// This is also sets the worst case distance that Get and Delete need to
// probe in the case of a lookup miss (if they don't see an empty slot
// before this).
//
// Assume cache line of 64 bytes, 2 bytes of metadata per entry and 16
// entries per bucket. We don't want to hit too many cache lines, me
// thinks.
maxProbeDistance = 8
)
type tophash = uint8
const (
tophashEmpty tophash = 0b0000_0000
tophashTombstone tophash = 0b1000_0000
)
// fixTophash adjusts the hash so that it's never the marker for empty or
// tombstone
func fixTophash(hash uint8) tophash {
// For current values of empty and tombstone the lower 7 bits are all zeros
// and both "empty" and "tombstone" are the only two possible values with
// that property.
var add uint8
if (hash & 0b0111_1111) == 0 {
add = 1
}
return hash + add
}
func isMarkerTophash(hash tophash) bool {
return hash&0b0111_1111 == 0
}
// holds metadata for each entry in the bucket
type bucketmeta struct {
// top 8-bits of the hash adjusted with fixTophash()
tophash8 [bucketSize]tophash
// relevant 8-bits of the hash to avoid hashing keys all the time in split
triehash8 [bucketSize]uint8
}
type bucket[K comparable, V any] struct {
keys [bucketSize]K
values [bucketSize]V
}
func indexIntoBuckets(hash tophash, numBuckets int) uint8 {
// https://lemire.me/blog/2016/06/27/a-fast-alternative-to-the-modulo-reduction/
return uint8((uint16(hash) * uint16(numBuckets)) >> 8)
}
func nextIndexIntoBuckets(idx uint8, numBuckets int) uint8 {
res := idx + 1
m := uint8(0)
if res < uint8(numBuckets) {
m = 1
}
return res * m
}
// noescape hides a pointer from escape analysis. noescape is
// the identity function but escape analysis doesn't think the
// output depends on the input. noescape is inlined and currently
// compiles down to zero instructions.
// USE CAREFULLY!
//
// src/runtime/stubs.go
//
//go:nosplit
func noescape(p unsafe.Pointer) unsafe.Pointer {
x := uintptr(p)
return unsafe.Pointer(x)
}
// A Finnish hash table, or fish for short. Stores key-value pairs.
type FishTable[K comparable, V any] struct {
hasher func(key unsafe.Pointer, seed uintptr) uintptr
trie []*smolMap2[K, V] // TODO: Maybe store (smolMap.depth) here to get better use of the cache-lines
seed uintptr
len int
// Real languages have bulk free() so freeing all of the the little maps
// should be fast.
}
// Makes a Finnish table.
//
// Your mother will die in her sleep tonight unless you pass in a good hash
// function.
//
// NOTE: If you are okay with _just_ your aunt dying in her sleep tonight, you
// can try to smuggle some locality sensitive hashing bits into your hash
// function. Those bits should be put into the least significant bits of your
// hash value. Depending on how successful you are at it, you will end up
// finding that keys that are close to each other ended up into the same
// hashmap. For your access pattern this may mean much more effective use of
// your CPU caches.
func MakeFishTable[K comparable, V any](hasher func(key K, seed uint64) uint64) *FishTable[K, V] {
m := new(FishTable[K, V])
m.hasher = func(key unsafe.Pointer, seed uintptr) uintptr {
return uintptr(hasher(*(*K)(key), uint64(seed)))
}
// The funny thing with random seed is that it makes cloning via
// m.Iterate() slower by a good amount
m.seed = uintptr(runtime_fastrand64())
return m
}
func MakeWithSize[K comparable, V any](size int, hasher func(key K, seed uint64) uint64) *FishTable[K, V] {
m := new(FishTable[K, V])
m.hasher = func(key unsafe.Pointer, seed uintptr) uintptr {
return uintptr(hasher(*(*K)(key), uint64(seed)))
}
// The funny thing with random seed is that it makes cloning via
// m.Iterate() slower by a good amount
m.seed = uintptr(runtime_fastrand64())
if size <= 0 {
return m
}
// Adjust size hint to accommodate for our max load factor.
sizeAdjusted := size * 4 / 3
if sizeAdjusted < size {
sizeAdjusted = size
}
// Calculate how many maps and buckets per map we need.
//
// Here we prefer creating the least amount of maps necessary, creating as
// big maps as possible.
//
// NOTE: The trie size MUST be a power of two but the number of buckets per
// map doesn't need to be so.
numMaps := sizeAdjusted / maxEntriesPerMap
numMaps = 1 << bits.Len(uint(numMaps))
numBuckets := sizeAdjusted / numMaps / bucketSize
if numBuckets <= 0 {
numBuckets = 1
}
if numBuckets > maxBuckets {
panic("oops")
}
// The above math can give us a case like (numMaps==4 && numBuckets==16)
// where we would instead prefer (numMaps==2 && numBuckets==32)
if numMaps > 1 && numBuckets == maxBuckets/2 {
numMaps >>= 1
numBuckets *= 2
}
initialDepth := uint8(bits.TrailingZeros(uint(numMaps)))
// TODO: WHERE'S MY BULK ALLOCATION?
m.trie = make([]*smolMap2[K, V], numMaps)
for i := range m.trie {
m.trie[i] = makeSmolMap2[K, V](numBuckets)
m.trie[i].depth = initialDepth
}
return m
}
func MakeWithUnsafeHasher[K comparable, V any](hasher func(key unsafe.Pointer, seed uintptr) uintptr) *FishTable[K, V] {
m := new(FishTable[K, V])
m.hasher = hasher
// The funny thing with random seed is that it makes cloning via
// m.Iterate() slower by a good amount
m.seed = uintptr(runtime_fastrand64())
return m
}
type smolMap2[K comparable, V any] struct {
// NOTE: len(bucketmetas) is not always a power-of-two
bucketmetas []bucketmeta
// NOTE: len(buckets) is not always a power-of-two
buckets []bucket[K, V] // TODO: Maybe instead just have ([]K, []V)
// holds entries that didn't find an appropriate slot in the buckets
overflow *sortedArr[K, V]
depth uint8 // <= 64
preferGrow bool
// total number of entries that can be added to the hash buckets before
// reaching the load factor. Includes present entries and tombstones.
// Excludes overflow len.
unload int16 // ??? < x <= maxEntriesPerMap
// TODO: Instead of keeping track of the number of tombstones we could just
// always scan the bucketmetas when we need the information. We usually
// need the count only when we are about to scan through bucketmetas
// anyways.
tombs uint16 // <= maxEntriesPerMap
// NOTE: I'm pretty sure that a crazy person could pack all this into
// 24 bytes or maybe even less. But not a gotard.
}
func (m *FishTable[K, V]) Len() int {
return m.len
}
func (m *FishTable[K, V]) Get(k K) (V, bool) {
trie := m.trie
if len(trie) > 0 {
hash := m.hasher(noescape(unsafe.Pointer(&k)), m.seed)
sm := trie[hash&uintptr(len(trie)-1)]
mapmetas := sm.bucketmetas // NOTE: Humbug! For large tries this is always a cache-miss
if len(mapmetas) == 0 { // nil if we shrunk very hard
goto miss
}
tophash8 := fixTophash(uint8(hash >> 56))
triehash8 := uint8(hash >> 0)
if len(trie) >= (1 << triehashBoundary) {
triehash8 = uint8(hash >> (sm.depth / triehashBoundary * triehashBoundary))
}
tophashProbe, triehashProbe := makeHashProbes(tophash8, triehash8)
bucketIndex := indexIntoBuckets(tophash8, len(mapmetas)) // start looking from tophash8 location
bucketsProbed := 1
for {
bucketmetas := &mapmetas[bucketIndex]
finder := bucketmetas.Finder()
hashMatches, empties := finder.ProbeHashMatchesAndEmpties(tophashProbe, triehashProbe)
for ; hashMatches.HasCurrent(); hashMatches.Advance() {
idx := hashMatches.Current()
bucket := &sm.buckets[bucketIndex]
if bucket.keys[idx] == k {
return bucket.values[idx], true
}
}
if empties.HasCurrent() {
// No need to look further - the probing during inserting would
// have placed the key into one of these empty slots.
goto miss
}
if bucketsProbed == len(mapmetas) {
goto miss
}
if bucketsProbed >= maxProbeDistance {
// Check overflow
if sm.overflow != nil {
v, ok := sm.overflow.Get(k, tophash8, triehash8)
if ok {
return v, true
}
}
goto miss
}
bucketIndex = nextIndexIntoBuckets(bucketIndex, len(mapmetas))
bucketsProbed++
}
}
miss:
var zerov V
return zerov, false
}
func (m *FishTable[K, V]) Delete(k K) {
trie := m.trie
if len(trie) == 0 {
return
}
hash := m.hasher(noescape(unsafe.Pointer(&k)), m.seed)
sm := trie[hash&uintptr(len(trie)-1)]
mapmetas := sm.bucketmetas // NOTE: Humbug! For large tries this is always a cache-miss
if len(mapmetas) == 0 { // nil if we shrunk very hard
return
}
tophash8 := fixTophash(uint8(hash >> 56))
triehash8 := uint8(hash >> 0)
if len(trie) >= (1 << triehashBoundary) {
triehash8 = uint8(hash >> (sm.depth / triehashBoundary * triehashBoundary))
}
tophashProbe, triehashProbe := makeHashProbes(tophash8, triehash8)
bucketIndex := indexIntoBuckets(tophash8, len(mapmetas)) // start looking from tophash8 location
bucketsProbed := 1
for {
bucketmetas := &mapmetas[bucketIndex]
finder := bucketmetas.Finder()
hashMatches, empties := finder.ProbeHashMatchesAndEmpties(tophashProbe, triehashProbe)
for ; hashMatches.HasCurrent(); hashMatches.Advance() {
slotInBucket := hashMatches.Current()
bucket := &sm.buckets[bucketIndex]
if bucket.keys[slotInBucket] == k {
// Found it!
var zerok K
var zerov V
bucket.keys[slotInBucket] = zerok
bucket.values[slotInBucket] = zerov
// If this bucket has empty slots then we know that no-one has
// inserted past this bucket (any interested party would have
// inserted into one of the empty slots). Which means we don't
// need to leave a tombstone to force probes to go onwards to
// the following buckets.
if empties.HasCurrent() {
bucketmetas.tophash8[slotInBucket] = tophashEmpty
sm.unload++
} else {
bucketmetas.tophash8[slotInBucket] = tophashTombstone
sm.tombs++
}
bucketmetas.triehash8[slotInBucket] = 0
m.len--
// Try to have an overflow entry take the slot. This ensures
// that the overflow doesn't contain any entries that could
// exist in the buckets, meaning that Put/Get don't need to
// even look at the overflow unless the probing "overflows."
//
// NOTE: Such entry for this slot could be in the overflow only
// if this bucket had no empties.
if sm.overflow != nil {
if !empties.HasCurrent() && sm.overflow.TryToMoveBackToBucket(bucketmetas, bucket, bucketIndex, slotInBucket, len(mapmetas)) {
sm.tombs--
sm.unload += 0 // -1 +1
if len(sm.overflow.hashes) == 0 {
sm.overflow = nil
}
}
}
// Shrink if ~3/4 slots free.
if int(sm.unload) >= len(mapmetas)*bucketSize*3/4 {
// When empty, release the buckets
if int(sm.unload) == len(mapmetas)*bucketSize {
sm.bucketmetas = nil
sm.buckets = nil
sm.unload = 0
sm.tombs = 0
} else if didShrink := m.maybeShrinkByFusing(sm, hash); didShrink {
} else if len(sm.bucketmetas) > 1 {
// TODO: Do we ever want to shrink by allocating a
// smaller array of buckets? Maybe when 1/8 slots used
// or something like that.
// m.inplaceShrinkSmol(sm)
// sm.preferGrow = true
}
}
return
}
}
if empties.HasCurrent() {
// No need to look further - the probing during inserting would
// have placed the key into one of these empty slots.
return
}
if bucketsProbed == len(mapmetas) {
return
}
if bucketsProbed >= maxProbeDistance {
// Check overflow
if sm.overflow != nil {
if sm.overflow.Delete(k, tophash8, triehash8) {
m.len--
if len(sm.overflow.hashes) == 0 {
sm.overflow = nil
}
}
}
return
}
bucketIndex = nextIndexIntoBuckets(bucketIndex, len(mapmetas))
bucketsProbed++
}
}
// Does the Put thing.
func (m *FishTable[K, V]) Put(k K, v V) {
hash := m.hasher(noescape(unsafe.Pointer(&k)), m.seed)
trie := m.trie
if len(trie) == 0 {
// fused alloc for first Put
type first[K comparable, V any] struct {
bucketmetas [1]bucketmeta
trie [1]*smolMap2[K, V]
buckets [1]bucket[K, V]
sm smolMap2[K, V]
}
arrs := new(first[K, V])
sm := &arrs.sm
sm.bucketmetas = arrs.bucketmetas[:]
sm.buckets = arrs.buckets[:]
arrs.trie[0] = sm
m.trie = arrs.trie[:1:len(arrs.trie)]
tophash8 := fixTophash(uint8(hash >> 56))
triehash8 := uint8(hash >> 0)
arrs.bucketmetas[0].tophash8[0] = tophash8
arrs.bucketmetas[0].triehash8[0] = triehash8
arrs.buckets[0].keys[0] = k
arrs.buckets[0].values[0] = v
sm.unload = sm.maxLoad()
sm.unload--
m.len++
return
}
top:
sm := trie[hash&uintptr(len(trie)-1)]
tophash8 := fixTophash(uint8(hash >> 56))
triehash8 := uint8(hash >> 0)
mapmetas := sm.bucketmetas // NOTE: Humbug! For large tries this is always a cache-miss
if len(mapmetas) == 0 { // nil if we shrunk very hard
sm.bucketmetas = make([]bucketmeta, 1)
sm.buckets = make([]bucket[K, V], 1)
sm.unload = sm.maxLoad()
mapmetas = sm.bucketmetas
}
if len(trie) >= (1 << triehashBoundary) {
triehash8 = uint8(hash >> (sm.depth / triehashBoundary * triehashBoundary))
}
tophashProbe, triehashProbe := makeHashProbes(tophash8, triehash8)
bucketIndex := indexIntoBuckets(tophash8, len(mapmetas)) // start looking from tophash8 location
bucketsProbed := 1
for {
bucketmetas := &mapmetas[bucketIndex]
finder := bucketmetas.Finder()
hashMatches, empties := finder.ProbeHashMatchesAndEmpties(tophashProbe, triehashProbe)
for ; hashMatches.HasCurrent(); hashMatches.Advance() {
idx := hashMatches.Current()
bucket := &sm.buckets[bucketIndex]
if bucket.keys[idx] == k {
bucket.values[idx] = v
return
}
}
// TODO: A fun and interesting thing would be to give priority access
// to the optimal buckets to those keys that would in the next grow
// belong to the "left" child. This would mean that when split()ing,
// those entries need not be moved at all. We would only need to read
// their tophash and triehash. No touching of its keys or values.
// Experiment having them take places from the "right" entries.
// If we see an empty slot then we can take it. Some earlier insert
// with the same key would have already been found as part of the
// probing, so we know that the key doesn't exist in the map yet.
if empties.HasCurrent() {
idx := empties.Current()
// TODO: If we saw a tombstone along the way then we could also
// take that spot. But do I care to? NO!
bucket := &sm.buckets[bucketIndex]
bucket.keys[idx] = k
bucket.values[idx] = v
bucketmetas.tophash8[idx] = tophash8
bucketmetas.triehash8[idx] = triehash8
sm.unload--
m.len++
// Check if we should grow. It's good to do it now that we quite
// likely probed through a good chunk of the map. Surely data is
// now in the CPU caches.
if sm.unload > 0 {
return
}
m.makeSpaceForMap(sm, hash)
return
}
if bucketsProbed >= len(mapmetas) {
// THIS IS WHERE WE GROW THEM!
m.makeSpaceForMap(sm, hash)
trie = m.trie
goto top
}
if bucketsProbed >= maxProbeDistance {
sm.ensureOverflow()
if updated := sm.overflow.Put(k, v, tophash8, triehash8); updated {
return
}
m.len++
// NOTE: Overflow doesn't count towards load because the hash
// function could shit the bed and end up putting hundreds of
// entries into the same overflow. We don't want to be trying to
// grow our map/trie in that case.
// But we should still check the load. Sometimes after splitting
// ALL ENTRIES go to one map so this code path is the only thing
// that would ever get taken.
if sm.unload <= 0 {
m.makeSpaceForMap(sm, hash)
}
return
}
bucketIndex = nextIndexIntoBuckets(bucketIndex, len(mapmetas))
bucketsProbed++
}
}
// A fine optimization. No good reason to have it disabled. This variable
// exists to mark all the places where this allocation can cause headaches.
const sharedAllocOptimizationEnabled = true
func (m *FishTable[K, V]) makeSpaceForMap(sm *smolMap2[K, V], hash uintptr) {
// Just rehash if map has tombstones
// TODO: Adjust condition
if sm.tombs > 0 {
m.rehashInplace(sm)
return
}
// Optimization for growth. We grow the sibling map as well if it's full
// enough. This allows us to do it in one big allocation which we can then
// later on turn into a single larger map. Initially the allocation is
// split equally between the two maps but the map that then becomes full
// first will kick off the other map and take the memory area all for
// himself, rehashing into it.
//
// We do waste tiny amount of load factor here but we save a lot memory if
// we end up growing once more after this growth, so it more than balances
// out.
if sharedAllocOptimizationEnabled && sm.depth > 0 {
hibi := uintptr(1) << uintptr(sm.depth-1)
step := hibi
siblingPos := hash & (hibi - 1)
firstMap := m.trie[siblingPos]
secondMap := m.trie[siblingPos+step]
self := firstMap
other := secondMap
if sm != self {
self, other = other, self
}
// Because of various growth/shrink sequences we could end up into a
// situation where the two maps don't share the allocation anymore.
//
// NOTE: If the other map has been doing some hardcore Deletes then it
// has no buckets.
var allocIsShared bool
if cap(firstMap.bucketmetas) > len(firstMap.bucketmetas) && len(secondMap.bucketmetas) > 0 {
extended := firstMap.bucketmetas[:cap(firstMap.bucketmetas):cap(firstMap.bucketmetas)]
// NOTE: POINTER EQUALITY. DO THE TWO POINTERS POINT TO THE SAME MEMORY?
if &extended[len(firstMap.bucketmetas)] == &secondMap.bucketmetas[0] {
allocIsShared = true
}
}
// Maybe some weird case after crazy sequence of growths and shrinks
if !allocIsShared && len(self.bucketmetas) < cap(self.bucketmetas) {
// Expand and then rehash it to use the newly
// available space.
oldBucketsOffset := 0
oldBucketsLen := len(self.bucketmetas)
load := self.bucketsPop()
self.bucketmetas = self.bucketmetas[:cap(self.bucketmetas):cap(self.bucketmetas)]
self.buckets = self.buckets[:cap(self.buckets):cap(self.buckets)]
self.unload = self.maxLoad() - int16(load)
m.rehashInplaceAfterResizing(self, oldBucketsOffset, oldBucketsLen)
self.preferGrow = false // split next time
return
}
// Not really our sibling if not on the same depth
if self.depth != other.depth {
goto normalGrowth
}
isBigEnoughToGrowEarly := func(sm *smolMap2[K, V]) bool {
return sm.unload <= (sm.maxLoad() / 4)
}
doSharedAlloc := func() {
temp := makeSmolMap2[K, V](len(self.bucketmetas) * 2 * 2)
fullMetas := temp.bucketmetas
fullBuckets := temp.buckets
temp.depth = firstMap.depth
temp.bucketmetas = fullMetas[:len(fullMetas)/2]
temp.buckets = fullBuckets[:len(fullBuckets)/2]
temp.unload = temp.maxLoad()
m.moveSmol(temp, firstMap)
*firstMap = *temp
firstMap.preferGrow = false // split next time
*temp = smolMap2[K, V]{}
temp.depth = secondMap.depth
temp.bucketmetas = fullMetas[len(fullMetas)/2:]
temp.buckets = fullBuckets[len(fullBuckets)/2:]
temp.unload = temp.maxLoad()
m.moveSmol(temp, secondMap)
*secondMap = *temp
secondMap.preferGrow = false // split next time
}
// Did the previous growth set up this optimization so that we could
// now collect our harvest?
if allocIsShared {
bigBucketmetas := firstMap.bucketmetas
bigBuckets := firstMap.buckets
oldOtherBuckets := other.buckets
oldOtherMetas := other.bucketmetas
selfPop := self.bucketsPop()
// Move the smaller of the two to its own allocation, also use this
// opportunity to grow it if it's full enough.
//
// But if both maps are very full... Let's just do shared alloc for
// them again!
otherIsFullEnough := isBigEnoughToGrowEarly(other)
if otherIsFullEnough {
if len(self.bucketmetas)*2*2 <= maxBuckets {
doSharedAlloc()
return
}
m.inplaceGrowSmol(other)
other.preferGrow = false // split next time
} else {
m.duplicateInplace(other)
}
// We moved the entries from other to a new allocation. Now, before
// we can use it for self we really ought to zero the memory areas
// previously used by other.
for i := range oldOtherMetas {
oldOtherMetas[i] = bucketmeta{}
}
for i := range oldOtherBuckets {
oldOtherBuckets[i] = bucket[K, V]{}
}
// Let the lucky one expand and then rehash it to use the newly available space
oldBucketsOffset := 0
if self == secondMap {
oldBucketsOffset = len(self.bucketmetas)
}
oldBucketsLen := len(self.bucketmetas)
self.bucketmetas = bigBucketmetas[:cap(bigBucketmetas):cap(bigBucketmetas)]
self.buckets = bigBuckets[:cap(bigBuckets):cap(bigBuckets)]
self.unload = self.maxLoad() - int16(selfPop)
m.rehashInplaceAfterResizing(self, oldBucketsOffset, oldBucketsLen)
self.preferGrow = false // split next time
return
}
// If the maps can have different number of buckets then the algorithm
// would need to be slightly more complex. Don't even try.
if len(self.bucketmetas) != len(other.bucketmetas) {
goto normalGrowth
}
// Are we too big to do this optimization?
if len(self.bucketmetas)*2*2 > maxBuckets {
goto normalGrowth
}
// Is the other map full enough to grow with us?
otherIsFullEnough := isBigEnoughToGrowEarly(other)
if otherIsFullEnough {
doSharedAlloc()
return
}
}
if sharedAllocOptimizationEnabled && sm.depth == 0 {
// If we shrunk after doing this optimization and now much later we are
// growing again we will have place to grow into.
if len(sm.bucketmetas)*2 == cap(sm.bucketmetas) {
oldBucketsOffset := 0
oldBucketsLen := len(sm.bucketmetas)
selfPop := sm.bucketsPop()
sm.bucketmetas = sm.bucketmetas[:cap(sm.bucketmetas):cap(sm.bucketmetas)]
sm.buckets = sm.buckets[:cap(sm.buckets):cap(sm.buckets)]
sm.unload = sm.maxLoad() - int16(selfPop)
m.rehashInplaceAfterResizing(sm, oldBucketsOffset, oldBucketsLen)
sm.preferGrow = false // split next time
return
}
}
normalGrowth:
// Instead of always splitting, we just add some more buckets to the map.
// Also it's nice to try to milk as much as possible out of the initial
// triehash8.
reallyShouldPreferGrow := sm.depth >= (triehashBoundary - 1)
if (reallyShouldPreferGrow || sm.preferGrow) && len(sm.bucketmetas) < maxBuckets {
m.inplaceGrowSmol(sm)
sm.preferGrow = false // split next time
return
}
// split it
left, right := m.split(sm)
if left != sm {
// the trie update loop below requires this
panic("oops")
}
// add more buckets next time
left.preferGrow = true
right.preferGrow = true
// But maybe the trie needs to grow as well...
oldDepth := left.depth - 1
if 1<<oldDepth == len(m.trie) {
oldTrie := m.trie
m.trie = make([]*smolMap2[K, V], len(oldTrie)*2)
copy(m.trie[:len(oldTrie)], oldTrie)
copy(m.trie[len(oldTrie):], oldTrie)
}
hibi := uintptr(1) << uintptr(oldDepth)
step := hibi
for i := uintptr(hash&(hibi-1)) + step; i < uintptr(len(m.trie)); i += (step * 2) {
m.trie[i] = right
}
}
type bucketInserter [maxBuckets]uint8
func (freeSlots *bucketInserter) findSlot(preferredBucketIdx uint8, numBuckets int) (uint8, uint8) {
bucketIdx := preferredBucketIdx
var bucketsProbed int
for {
nextFreeInBucket := freeSlots[bucketIdx]
if nextFreeInBucket >= bucketSize {
bucketIdx = nextIndexIntoBuckets(bucketIdx, numBuckets)
bucketsProbed++
if bucketsProbed >= numBuckets || bucketsProbed >= maxProbeDistance {
return uint8(numBuckets), nextFreeInBucket
}
continue
}
freeSlots[bucketIdx]++
return bucketIdx, nextFreeInBucket
}
}
type bucketTracker [maxBuckets]bucketBitmask
func (tracker *bucketTracker) findSlot(preferredBucketIdx uint8, numBuckets int, unfortunateBucket, unfortunateSlot uint8) (uint8, uint8) {
_ = tracker[0] // nil check out of the loop
bucketIdx := preferredBucketIdx
var bucketsProbed int
for {
nextFreeInBucket := tracker[bucketIdx].FirstUnmarkedSlot()
if nextFreeInBucket >= bucketSize {
bucketIdx = nextIndexIntoBuckets(bucketIdx, numBuckets)
bucketsProbed++
if bucketsProbed >= numBuckets || bucketsProbed >= maxProbeDistance {
return uint8(numBuckets), nextFreeInBucket
}
continue
}
// Try to prefer the given slot if we landed all the way into the
// unfortunate bucket
if bucketIdx == unfortunateBucket && !tracker[bucketIdx].IsMarked(unfortunateSlot) {
nextFreeInBucket = unfortunateSlot
}
tracker[bucketIdx].Mark(nextFreeInBucket)
return bucketIdx, nextFreeInBucket
}
}
type slotPtr[K comparable, V any] struct {
key *K
value *V
tophash8 *tophash
triehash8 *uint8
}
func makeSlotPtr[K comparable, V any](metas *bucketmeta, bucket *bucket[K, V], slotInBucket uint8) slotPtr[K, V] {
return slotPtr[K, V]{
key: &bucket.keys[slotInBucket],
value: &bucket.values[slotInBucket],
tophash8: &metas.tophash8[slotInBucket],
triehash8: &metas.triehash8[slotInBucket],
}
}
func makeOverflowSlotPtr[K comparable, V any](ov *sortedArr[K, V], i int) slotPtr[K, V] {
return slotPtr[K, V]{
key: &ov.keys[i],
value: &ov.values[i],
tophash8: &ov.hashes[i].tophash8,
triehash8: &ov.hashes[i].triehash8,
}
}
func writeSlot[K comparable, V any](dst, src slotPtr[K, V]) {
*dst.key = *src.key
*dst.value = *src.value
*dst.tophash8 = *src.tophash8
*dst.triehash8 = *src.triehash8
}
func swapSlots[K comparable, V any](a, b slotPtr[K, V]) {
*a.key, *b.key = *b.key, *a.key
*a.value, *b.value = *b.value, *a.value
*a.tophash8, *b.tophash8 = *b.tophash8, *a.tophash8
*a.triehash8, *b.triehash8 = *b.triehash8, *a.triehash8
}
func zeroSlot[K comparable, V any](a slotPtr[K, V]) {
var zerok K
var zerov V
*a.key = zerok
*a.value = zerov
*a.tophash8 = tophashEmpty
*a.triehash8 = 0
}
// splits m into two maps (where the "left" map is the 'm' re-used). Cleans up
// all the tombstones from 'm'.
func (h *FishTable[K, V]) split(m *smolMap2[K, V]) (*smolMap2[K, V], *smolMap2[K, V]) {
if m.depth == 64 {
// 64-bit hash values have only 64 bits :-(
panic("depth overflow")
}
m.depth++
// Re-use m as left
left := m
right := makeSmolMap2[K, V](len(left.bucketmetas))
right.depth = m.depth
oldDepthBit := uint8(1 << ((m.depth - 1) % triehashBoundary))
crossedTriehashBoundary := (m.depth % triehashBoundary) == 0
// Prove some stuff to the compiler so that the loops don't generate so
// many bounds checks.
if len(m.bucketmetas) != len(right.bucketmetas) {
panic("oops")
}
if len(m.buckets) != len(right.buckets) {
panic("oops")
}
if len(m.bucketmetas) != len(m.buckets) {
panic("oops")
}
if len(right.bucketmetas) != len(right.buckets) {
panic("oops")
}
if len(m.bucketmetas) > maxBuckets {
panic("oops")
}
rehash := func(key *K, outTriehash8 *uint8) {
hash := h.hasher(unsafe.Pointer(key), h.seed)
*outTriehash8 = uint8(hash >> (m.depth / triehashBoundary * triehashBoundary))
}
oldOverflow := m.overflow
m.overflow = nil
var previousBucketHadEmpties bool
if len(m.bucketmetas) > 1 {
bucketmetas := &m.bucketmetas[len(m.bucketmetas)-1]
finder := bucketmetas.Finder()
empties := finder.EmptySlots()
previousBucketHadEmpties = empties.HasCurrent()
}
var rightInserter bucketInserter
moveToRight := func(slot slotPtr[K, V]) {
if crossedTriehashBoundary {
rehash(slot.key, slot.triehash8)
}
preferredBucketIdx := indexIntoBuckets(*slot.tophash8, len(right.bucketmetas))
bucketIdx, nextFreeInBucket := rightInserter.findSlot(preferredBucketIdx, len(right.bucketmetas))
if nextFreeInBucket < bucketSize {
dstmetas := &right.bucketmetas[bucketIdx]
dstbuckets := &right.buckets[bucketIdx]
dstSlot := makeSlotPtr(dstmetas, dstbuckets, nextFreeInBucket)
writeSlot(dstSlot, slot)
right.unload--
} else {
right.ensureOverflow()
right.overflow.PutNotUpdateSlotPtr(slot)
}
// Zero the slot left behind. Only setting the hashes is strictly necessary
zeroSlot(slot)
}
var leftTracker bucketTracker
for bucketIndex := range m.bucketmetas {
bucketmetas := &m.bucketmetas[bucketIndex]
bucket := &m.buckets[bucketIndex]
trackingBucket := &leftTracker[bucketIndex]
finder := bucketmetas.Finder()
empties := finder.EmptySlots()
hadEmpties := empties.HasCurrent()
// bother to clear tombies if we are planning on reusing m
if left.tombs > 0 {
finder.MakeTombstonesIntoEmpties(bucketmetas)
}
presentSlots := finder.PresentSlots()
// Figure out righties. Remember to exclude the already placed entries
// because already placed entries have a new triehash if
// crossedTriehashBoundary==true
righties := finder.GoesRightForBit(oldDepthBit)
righties = righties.WithBitmaskExcluded(*trackingBucket)
newLefties := presentSlots.WithBitmaskExcluded(righties.AsBitmask() | (*trackingBucket))
if crossedTriehashBoundary {
entries := (righties.AsBitmask() | newLefties.AsBitmask()).AsMatchiter()
for ; entries.HasCurrent(); entries.Advance() {
slotInBucket := entries.Current()
rehash(&bucket.keys[slotInBucket], &bucketmetas.triehash8[slotInBucket])
}
}
// If the previous bucket had empty slots before splitting, then we