-
Notifications
You must be signed in to change notification settings - Fork 32
/
immutable.go
2459 lines (2129 loc) · 74.6 KB
/
immutable.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 immutable provides immutable collection types.
//
// # Introduction
//
// Immutable collections provide an efficient, safe way to share collections
// of data while minimizing locks. The collections in this package provide
// List, Map, and SortedMap implementations. These act similarly to slices
// and maps, respectively, except that altering a collection returns a new
// copy of the collection with that change.
//
// Because collections are unable to change, they are safe for multiple
// goroutines to read from at the same time without a mutex. However, these
// types of collections come with increased CPU & memory usage as compared
// with Go's built-in collection types so please evaluate for your specific
// use.
//
// # Collection Types
//
// The List type provides an API similar to Go slices. They allow appending,
// prepending, and updating of elements. Elements can also be fetched by index
// or iterated over using a ListIterator.
//
// The Map & SortedMap types provide an API similar to Go maps. They allow
// values to be assigned to unique keys and allow for the deletion of keys.
// Values can be fetched by key and key/value pairs can be iterated over using
// the appropriate iterator type. Both map types provide the same API. The
// SortedMap, however, provides iteration over sorted keys while the Map
// provides iteration over unsorted keys. Maps improved performance and memory
// usage as compared to SortedMaps.
//
// # Hashing and Sorting
//
// Map types require the use of a Hasher implementation to calculate hashes for
// their keys and check for key equality. SortedMaps require the use of a
// Comparer implementation to sort keys in the map.
//
// These collection types automatically provide built-in hasher and comparers
// for int, string, and byte slice keys. If you are using one of these key types
// then simply pass a nil into the constructor. Otherwise you will need to
// implement a custom Hasher or Comparer type. Please see the provided
// implementations for reference.
package immutable
import (
"fmt"
"math/bits"
"reflect"
"sort"
"strings"
"golang.org/x/exp/constraints"
)
// List is a dense, ordered, indexed collections. They are analogous to slices
// in Go. They can be updated by appending to the end of the list, prepending
// values to the beginning of the list, or updating existing indexes in the
// list.
type List[T any] struct {
root listNode[T] // root node
origin int // offset to zero index element
size int // total number of elements in use
}
// NewList returns a new empty instance of List.
func NewList[T any](values ...T) *List[T] {
l := &List[T]{
root: &listLeafNode[T]{},
}
for _, value := range values {
l.append(value, true)
}
return l
}
// clone returns a copy of the list.
func (l *List[T]) clone() *List[T] {
other := *l
return &other
}
// Len returns the number of elements in the list.
func (l *List[T]) Len() int {
return l.size
}
// cap returns the total number of possible elements for the current depth.
func (l *List[T]) cap() int {
return 1 << (l.root.depth() * listNodeBits)
}
// Get returns the value at the given index. Similar to slices, this method will
// panic if index is below zero or is greater than or equal to the list size.
func (l *List[T]) Get(index int) T {
if index < 0 || index >= l.size {
panic(fmt.Sprintf("immutable.List.Get: index %d out of bounds", index))
}
return l.root.get(l.origin + index)
}
// Set returns a new list with value set at index. Similar to slices, this
// method will panic if index is below zero or if the index is greater than
// or equal to the list size.
func (l *List[T]) Set(index int, value T) *List[T] {
return l.set(index, value, false)
}
func (l *List[T]) set(index int, value T, mutable bool) *List[T] {
if index < 0 || index >= l.size {
panic(fmt.Sprintf("immutable.List.Set: index %d out of bounds", index))
}
other := l
if !mutable {
other = l.clone()
}
other.root = other.root.set(l.origin+index, value, mutable)
return other
}
// Append returns a new list with value added to the end of the list.
func (l *List[T]) Append(value T) *List[T] {
return l.append(value, false)
}
func (l *List[T]) append(value T, mutable bool) *List[T] {
other := l
if !mutable {
other = l.clone()
}
// Expand list to the right if no slots remain.
if other.size+other.origin >= l.cap() {
newRoot := &listBranchNode[T]{d: other.root.depth() + 1}
newRoot.children[0] = other.root
other.root = newRoot
}
// Increase size and set the last element to the new value.
other.size++
other.root = other.root.set(other.origin+other.size-1, value, mutable)
return other
}
// Prepend returns a new list with value(s) added to the beginning of the list.
func (l *List[T]) Prepend(value T) *List[T] {
return l.prepend(value, false)
}
func (l *List[T]) prepend(value T, mutable bool) *List[T] {
other := l
if !mutable {
other = l.clone()
}
// Expand list to the left if no slots remain.
if other.origin == 0 {
newRoot := &listBranchNode[T]{d: other.root.depth() + 1}
newRoot.children[listNodeSize-1] = other.root
other.root = newRoot
other.origin += (listNodeSize - 1) << (other.root.depth() * listNodeBits)
}
// Increase size and move origin back. Update first element to value.
other.size++
other.origin--
other.root = other.root.set(other.origin, value, mutable)
return other
}
// Slice returns a new list of elements between start index and end index.
// Similar to slices, this method will panic if start or end are below zero or
// greater than the list size. A panic will also occur if start is greater than
// end.
//
// Unlike Go slices, references to inaccessible elements will be automatically
// removed so they can be garbage collected.
func (l *List[T]) Slice(start, end int) *List[T] {
return l.slice(start, end, false)
}
func (l *List[T]) slice(start, end int, mutable bool) *List[T] {
// Panics similar to Go slices.
if start < 0 || start > l.size {
panic(fmt.Sprintf("immutable.List.Slice: start index %d out of bounds", start))
} else if end < 0 || end > l.size {
panic(fmt.Sprintf("immutable.List.Slice: end index %d out of bounds", end))
} else if start > end {
panic(fmt.Sprintf("immutable.List.Slice: invalid slice index: [%d:%d]", start, end))
}
// Return the same list if the start and end are the entire range.
if start == 0 && end == l.size {
return l
}
// Create copy, if immutable.
other := l
if !mutable {
other = l.clone()
}
// Update origin/size.
other.origin = l.origin + start
other.size = end - start
// Contract tree while the start & end are in the same child node.
for other.root.depth() > 1 {
i := (other.origin >> (other.root.depth() * listNodeBits)) & listNodeMask
j := ((other.origin + other.size - 1) >> (other.root.depth() * listNodeBits)) & listNodeMask
if i != j {
break // branch contains at least two nodes, exit
}
// Replace the current root with the single child & update origin offset.
other.origin -= i << (other.root.depth() * listNodeBits)
other.root = other.root.(*listBranchNode[T]).children[i]
}
// Ensure all references are removed before start & after end.
other.root = other.root.deleteBefore(other.origin, mutable)
other.root = other.root.deleteAfter(other.origin+other.size-1, mutable)
return other
}
// Iterator returns a new iterator for this list positioned at the first index.
func (l *List[T]) Iterator() *ListIterator[T] {
itr := &ListIterator[T]{list: l}
itr.First()
return itr
}
// ListBuilder represents an efficient builder for creating new Lists.
type ListBuilder[T any] struct {
list *List[T] // current state
}
// NewListBuilder returns a new instance of ListBuilder.
func NewListBuilder[T any]() *ListBuilder[T] {
return &ListBuilder[T]{list: NewList[T]()}
}
// List returns the current copy of the list.
// The builder should not be used again after the list after this call.
func (b *ListBuilder[T]) List() *List[T] {
assert(b.list != nil, "immutable.ListBuilder.List(): duplicate call to fetch list")
list := b.list
b.list = nil
return list
}
// Len returns the number of elements in the underlying list.
func (b *ListBuilder[T]) Len() int {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
return b.list.Len()
}
// Get returns the value at the given index. Similar to slices, this method will
// panic if index is below zero or is greater than or equal to the list size.
func (b *ListBuilder[T]) Get(index int) T {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
return b.list.Get(index)
}
// Set updates the value at the given index. Similar to slices, this method will
// panic if index is below zero or if the index is greater than or equal to the
// list size.
func (b *ListBuilder[T]) Set(index int, value T) {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
b.list = b.list.set(index, value, true)
}
// Append adds value to the end of the list.
func (b *ListBuilder[T]) Append(value T) {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
b.list = b.list.append(value, true)
}
// Prepend adds value to the beginning of the list.
func (b *ListBuilder[T]) Prepend(value T) {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
b.list = b.list.prepend(value, true)
}
// Slice updates the list with a sublist of elements between start and end index.
// See List.Slice() for more details.
func (b *ListBuilder[T]) Slice(start, end int) {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
b.list = b.list.slice(start, end, true)
}
// Iterator returns a new iterator for the underlying list.
func (b *ListBuilder[T]) Iterator() *ListIterator[T] {
assert(b.list != nil, "immutable.ListBuilder: builder invalid after List() invocation")
return b.list.Iterator()
}
// Constants for bit shifts used for levels in the List trie.
const (
listNodeBits = 5
listNodeSize = 1 << listNodeBits
listNodeMask = listNodeSize - 1
)
// listNode represents either a branch or leaf node in a List.
type listNode[T any] interface {
depth() uint
get(index int) T
set(index int, v T, mutable bool) listNode[T]
containsBefore(index int) bool
containsAfter(index int) bool
deleteBefore(index int, mutable bool) listNode[T]
deleteAfter(index int, mutable bool) listNode[T]
}
// newListNode returns a leaf node for depth zero, otherwise returns a branch node.
func newListNode[T any](depth uint) listNode[T] {
if depth == 0 {
return &listLeafNode[T]{}
}
return &listBranchNode[T]{d: depth}
}
// listBranchNode represents a branch of a List tree at a given depth.
type listBranchNode[T any] struct {
d uint // depth
children [listNodeSize]listNode[T]
}
// depth returns the depth of this branch node from the leaf.
func (n *listBranchNode[T]) depth() uint { return n.d }
// get returns the child node at the segment of the index for this depth.
func (n *listBranchNode[T]) get(index int) T {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
return n.children[idx].get(index)
}
// set recursively updates the value at index for each lower depth from the node.
func (n *listBranchNode[T]) set(index int, v T, mutable bool) listNode[T] {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
// Find child for the given value in the branch. Create new if it doesn't exist.
child := n.children[idx]
if child == nil {
child = newListNode[T](n.depth() - 1)
}
// Return a copy of this branch with the new child.
var other *listBranchNode[T]
if mutable {
other = n
} else {
tmp := *n
other = &tmp
}
other.children[idx] = child.set(index, v, mutable)
return other
}
// containsBefore returns true if non-nil values exists between [0,index).
func (n *listBranchNode[T]) containsBefore(index int) bool {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
// Quickly check if any direct children exist before this segment of the index.
for i := 0; i < idx; i++ {
if n.children[i] != nil {
return true
}
}
// Recursively check for children directly at the given index at this segment.
if n.children[idx] != nil && n.children[idx].containsBefore(index) {
return true
}
return false
}
// containsAfter returns true if non-nil values exists between (index,listNodeSize).
func (n *listBranchNode[T]) containsAfter(index int) bool {
idx := (index >> (n.d * listNodeBits)) & listNodeMask
// Quickly check if any direct children exist after this segment of the index.
for i := idx + 1; i < len(n.children); i++ {
if n.children[i] != nil {
return true
}
}
// Recursively check for children directly at the given index at this segment.
if n.children[idx] != nil && n.children[idx].containsAfter(index) {
return true
}
return false
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listBranchNode[T]) deleteBefore(index int, mutable bool) listNode[T] {
// Ignore if no nodes exist before the given index.
if !n.containsBefore(index) {
return n
}
// Return a copy with any nodes prior to the index removed.
idx := (index >> (n.d * listNodeBits)) & listNodeMask
var other *listBranchNode[T]
if mutable {
other = n
for i := 0; i < idx; i++ {
n.children[i] = nil
}
} else {
other = &listBranchNode[T]{d: n.d}
copy(other.children[idx:][:], n.children[idx:][:])
}
if other.children[idx] != nil {
other.children[idx] = other.children[idx].deleteBefore(index, mutable)
}
return other
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listBranchNode[T]) deleteAfter(index int, mutable bool) listNode[T] {
// Ignore if no nodes exist after the given index.
if !n.containsAfter(index) {
return n
}
// Return a copy with any nodes after the index removed.
idx := (index >> (n.d * listNodeBits)) & listNodeMask
var other *listBranchNode[T]
if mutable {
other = n
for i := idx + 1; i < len(n.children); i++ {
n.children[i] = nil
}
} else {
other = &listBranchNode[T]{d: n.d}
copy(other.children[:idx+1], n.children[:idx+1])
}
if other.children[idx] != nil {
other.children[idx] = other.children[idx].deleteAfter(index, mutable)
}
return other
}
// listLeafNode represents a leaf node in a List.
type listLeafNode[T any] struct {
children [listNodeSize]T
// bitset with ones at occupied positions, position 0 is the LSB
occupied uint32
}
// depth always returns 0 for leaf nodes.
func (n *listLeafNode[T]) depth() uint { return 0 }
// get returns the value at the given index.
func (n *listLeafNode[T]) get(index int) T {
return n.children[index&listNodeMask]
}
// set returns a copy of the node with the value at the index updated to v.
func (n *listLeafNode[T]) set(index int, v T, mutable bool) listNode[T] {
idx := index & listNodeMask
var other *listLeafNode[T]
if mutable {
other = n
} else {
tmp := *n
other = &tmp
}
other.children[idx] = v
other.occupied |= 1 << idx
return other
}
// containsBefore returns true if non-nil values exists between [0,index).
func (n *listLeafNode[T]) containsBefore(index int) bool {
idx := index & listNodeMask
return bits.TrailingZeros32(n.occupied) < idx
}
// containsAfter returns true if non-nil values exists between (index,listNodeSize).
func (n *listLeafNode[T]) containsAfter(index int) bool {
idx := index & listNodeMask
lastSetPos := 31 - bits.LeadingZeros32(n.occupied)
return lastSetPos > idx
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listLeafNode[T]) deleteBefore(index int, mutable bool) listNode[T] {
if !n.containsBefore(index) {
return n
}
idx := index & listNodeMask
var other *listLeafNode[T]
if mutable {
other = n
var empty T
for i := 0; i < idx; i++ {
other.children[i] = empty
}
} else {
other = &listLeafNode[T]{occupied: n.occupied}
copy(other.children[idx:][:], n.children[idx:][:])
}
// Set the first idx bits to 0.
other.occupied &= ^((1 << idx) - 1)
return other
}
// deleteAfter returns a new node with all elements after index removed.
func (n *listLeafNode[T]) deleteAfter(index int, mutable bool) listNode[T] {
if !n.containsAfter(index) {
return n
}
idx := index & listNodeMask
var other *listLeafNode[T]
if mutable {
other = n
var empty T
for i := idx + 1; i < len(n.children); i++ {
other.children[i] = empty
}
} else {
other = &listLeafNode[T]{occupied: n.occupied}
copy(other.children[:idx+1][:], n.children[:idx+1][:])
}
// Set bits after idx to 0. idx < 31 because n.containsAfter(index) == true.
other.occupied &= (1 << (idx + 1)) - 1
return other
}
// ListIterator represents an ordered iterator over a list.
type ListIterator[T any] struct {
list *List[T] // source list
index int // current index position
stack [32]listIteratorElem[T] // search stack
depth int // stack depth
}
// Done returns true if no more elements remain in the iterator.
func (itr *ListIterator[T]) Done() bool {
return itr.index < 0 || itr.index >= itr.list.Len()
}
// First positions the iterator on the first index.
// If source list is empty then no change is made.
func (itr *ListIterator[T]) First() {
if itr.list.Len() != 0 {
itr.Seek(0)
}
}
// Last positions the iterator on the last index.
// If source list is empty then no change is made.
func (itr *ListIterator[T]) Last() {
if n := itr.list.Len(); n != 0 {
itr.Seek(n - 1)
}
}
// Seek moves the iterator position to the given index in the list.
// Similar to Go slices, this method will panic if index is below zero or if
// the index is greater than or equal to the list size.
func (itr *ListIterator[T]) Seek(index int) {
// Panic similar to Go slices.
if index < 0 || index >= itr.list.Len() {
panic(fmt.Sprintf("immutable.ListIterator.Seek: index %d out of bounds", index))
}
itr.index = index
// Reset to the bottom of the stack at seek to the correct position.
itr.stack[0] = listIteratorElem[T]{node: itr.list.root}
itr.depth = 0
itr.seek(index)
}
// Next returns the current index and its value & moves the iterator forward.
// Returns an index of -1 if the there are no more elements to return.
func (itr *ListIterator[T]) Next() (index int, value T) {
// Exit immediately if there are no elements remaining.
var empty T
if itr.Done() {
return -1, empty
}
// Retrieve current index & value.
elem := &itr.stack[itr.depth]
index, value = itr.index, elem.node.(*listLeafNode[T]).children[elem.index]
// Increase index. If index is at the end then return immediately.
itr.index++
if itr.Done() {
return index, value
}
// Move up stack until we find a node that has remaining position ahead.
for ; itr.depth > 0 && itr.stack[itr.depth].index >= listNodeSize-1; itr.depth-- {
}
// Seek to correct position from current depth.
itr.seek(itr.index)
return index, value
}
// Prev returns the current index and value and moves the iterator backward.
// Returns an index of -1 if the there are no more elements to return.
func (itr *ListIterator[T]) Prev() (index int, value T) {
// Exit immediately if there are no elements remaining.
var empty T
if itr.Done() {
return -1, empty
}
// Retrieve current index & value.
elem := &itr.stack[itr.depth]
index, value = itr.index, elem.node.(*listLeafNode[T]).children[elem.index]
// Decrease index. If index is past the beginning then return immediately.
itr.index--
if itr.Done() {
return index, value
}
// Move up stack until we find a node that has remaining position behind.
for ; itr.depth > 0 && itr.stack[itr.depth].index == 0; itr.depth-- {
}
// Seek to correct position from current depth.
itr.seek(itr.index)
return index, value
}
// seek positions the stack to the given index from the current depth.
// Elements and indexes below the current depth are assumed to be correct.
func (itr *ListIterator[T]) seek(index int) {
// Iterate over each level until we reach a leaf node.
for {
elem := &itr.stack[itr.depth]
elem.index = ((itr.list.origin + index) >> (elem.node.depth() * listNodeBits)) & listNodeMask
switch node := elem.node.(type) {
case *listBranchNode[T]:
child := node.children[elem.index]
itr.stack[itr.depth+1] = listIteratorElem[T]{node: child}
itr.depth++
case *listLeafNode[T]:
return
}
}
}
// listIteratorElem represents the node and it's child index within the stack.
type listIteratorElem[T any] struct {
node listNode[T]
index int
}
// Size thresholds for each type of branch node.
const (
maxArrayMapSize = 8
maxBitmapIndexedSize = 16
)
// Segment bit shifts within the map tree.
const (
mapNodeBits = 5
mapNodeSize = 1 << mapNodeBits
mapNodeMask = mapNodeSize - 1
)
// Map represents an immutable hash map implementation. The map uses a Hasher
// to generate hashes and check for equality of key values.
//
// It is implemented as an Hash Array Mapped Trie.
type Map[K, V any] struct {
size int // total number of key/value pairs
root mapNode[K, V] // root node of trie
hasher Hasher[K] // hasher implementation
}
// NewMap returns a new instance of Map. If hasher is nil, a default hasher
// implementation will automatically be chosen based on the first key added.
// Default hasher implementations only exist for int, string, and byte slice types.
func NewMap[K, V any](hasher Hasher[K]) *Map[K, V] {
return &Map[K, V]{
hasher: hasher,
}
}
// NewMapOf returns a new instance of Map, containing a map of provided entries.
//
// If hasher is nil, a default hasher implementation will automatically be chosen based on the first key added.
// Default hasher implementations only exist for int, string, and byte slice types.
func NewMapOf[K comparable, V any](hasher Hasher[K], entries map[K]V) *Map[K, V] {
m := &Map[K, V]{
hasher: hasher,
}
for k, v := range entries {
m.set(k, v, true)
}
return m
}
// Len returns the number of elements in the map.
func (m *Map[K, V]) Len() int {
return m.size
}
// clone returns a shallow copy of m.
func (m *Map[K, V]) clone() *Map[K, V] {
other := *m
return &other
}
// Get returns the value for a given key and a flag indicating whether the
// key exists. This flag distinguishes a nil value set on a key versus a
// non-existent key in the map.
func (m *Map[K, V]) Get(key K) (value V, ok bool) {
var empty V
if m.root == nil {
return empty, false
}
keyHash := m.hasher.Hash(key)
return m.root.get(key, 0, keyHash, m.hasher)
}
// Set returns a map with the key set to the new value. A nil value is allowed.
//
// This function will return a new map even if the updated value is the same as
// the existing value because Map does not track value equality.
func (m *Map[K, V]) Set(key K, value V) *Map[K, V] {
return m.set(key, value, false)
}
func (m *Map[K, V]) set(key K, value V, mutable bool) *Map[K, V] {
// Set a hasher on the first value if one does not already exist.
hasher := m.hasher
if hasher == nil {
hasher = NewHasher(key)
}
// Generate copy if necessary.
other := m
if !mutable {
other = m.clone()
}
other.hasher = hasher
// If the map is empty, initialize with a simple array node.
if m.root == nil {
other.size = 1
other.root = &mapArrayNode[K, V]{entries: []mapEntry[K, V]{{key: key, value: value}}}
return other
}
// Otherwise copy the map and delegate insertion to the root.
// Resized will return true if the key does not currently exist.
var resized bool
other.root = m.root.set(key, value, 0, hasher.Hash(key), hasher, mutable, &resized)
if resized {
other.size++
}
return other
}
// Delete returns a map with the given key removed.
// Removing a non-existent key will cause this method to return the same map.
func (m *Map[K, V]) Delete(key K) *Map[K, V] {
return m.delete(key, false)
}
func (m *Map[K, V]) delete(key K, mutable bool) *Map[K, V] {
// Return original map if no keys exist.
if m.root == nil {
return m
}
// If the delete did not change the node then return the original map.
var resized bool
newRoot := m.root.delete(key, 0, m.hasher.Hash(key), m.hasher, mutable, &resized)
if !resized {
return m
}
// Generate copy if necessary.
other := m
if !mutable {
other = m.clone()
}
// Return copy of map with new root and decreased size.
other.size = m.size - 1
other.root = newRoot
return other
}
// Iterator returns a new iterator for the map.
func (m *Map[K, V]) Iterator() *MapIterator[K, V] {
itr := &MapIterator[K, V]{m: m}
itr.First()
return itr
}
// MapBuilder represents an efficient builder for creating Maps.
type MapBuilder[K, V any] struct {
m *Map[K, V] // current state
}
// NewMapBuilder returns a new instance of MapBuilder.
func NewMapBuilder[K, V any](hasher Hasher[K]) *MapBuilder[K, V] {
return &MapBuilder[K, V]{m: NewMap[K, V](hasher)}
}
// Map returns the underlying map. Only call once.
// Builder is invalid after call. Will panic on second invocation.
func (b *MapBuilder[K, V]) Map() *Map[K, V] {
assert(b.m != nil, "immutable.SortedMapBuilder.Map(): duplicate call to fetch map")
m := b.m
b.m = nil
return m
}
// Len returns the number of elements in the underlying map.
func (b *MapBuilder[K, V]) Len() int {
assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
return b.m.Len()
}
// Get returns the value for the given key.
func (b *MapBuilder[K, V]) Get(key K) (value V, ok bool) {
assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
return b.m.Get(key)
}
// Set sets the value of the given key. See Map.Set() for additional details.
func (b *MapBuilder[K, V]) Set(key K, value V) {
assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
b.m = b.m.set(key, value, true)
}
// Delete removes the given key. See Map.Delete() for additional details.
func (b *MapBuilder[K, V]) Delete(key K) {
assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
b.m = b.m.delete(key, true)
}
// Iterator returns a new iterator for the underlying map.
func (b *MapBuilder[K, V]) Iterator() *MapIterator[K, V] {
assert(b.m != nil, "immutable.MapBuilder: builder invalid after Map() invocation")
return b.m.Iterator()
}
// mapNode represents any node in the map tree.
type mapNode[K, V any] interface {
get(key K, shift uint, keyHash uint32, h Hasher[K]) (value V, ok bool)
set(key K, value V, shift uint, keyHash uint32, h Hasher[K], mutable bool, resized *bool) mapNode[K, V]
delete(key K, shift uint, keyHash uint32, h Hasher[K], mutable bool, resized *bool) mapNode[K, V]
}
var _ mapNode[string, any] = (*mapArrayNode[string, any])(nil)
var _ mapNode[string, any] = (*mapBitmapIndexedNode[string, any])(nil)
var _ mapNode[string, any] = (*mapHashArrayNode[string, any])(nil)
var _ mapNode[string, any] = (*mapValueNode[string, any])(nil)
var _ mapNode[string, any] = (*mapHashCollisionNode[string, any])(nil)
// mapLeafNode represents a node that stores a single key hash at the leaf of the map tree.
type mapLeafNode[K, V any] interface {
mapNode[K, V]
keyHashValue() uint32
}
var _ mapLeafNode[string, any] = (*mapValueNode[string, any])(nil)
var _ mapLeafNode[string, any] = (*mapHashCollisionNode[string, any])(nil)
// mapArrayNode is a map node that stores key/value pairs in a slice.
// Entries are stored in insertion order. An array node expands into a bitmap
// indexed node once a given threshold size is crossed.
type mapArrayNode[K, V any] struct {
entries []mapEntry[K, V]
}
// indexOf returns the entry index of the given key. Returns -1 if key not found.
func (n *mapArrayNode[K, V]) indexOf(key K, h Hasher[K]) int {
for i := range n.entries {
if h.Equal(n.entries[i].key, key) {
return i
}
}
return -1
}
// get returns the value for the given key.
func (n *mapArrayNode[K, V]) get(key K, shift uint, keyHash uint32, h Hasher[K]) (value V, ok bool) {
i := n.indexOf(key, h)
if i == -1 {
return value, false
}
return n.entries[i].value, true
}
// set inserts or updates the value for a given key. If the key is inserted and
// the new size crosses the max size threshold, a bitmap indexed node is returned.
func (n *mapArrayNode[K, V]) set(key K, value V, shift uint, keyHash uint32, h Hasher[K], mutable bool, resized *bool) mapNode[K, V] {
idx := n.indexOf(key, h)
// Mark as resized if the key doesn't exist.
if idx == -1 {
*resized = true
}
// If we are adding and it crosses the max size threshold, expand the node.
// We do this by continually setting the entries to a value node and expanding.
if idx == -1 && len(n.entries) >= maxArrayMapSize {
var node mapNode[K, V] = newMapValueNode(h.Hash(key), key, value)
for _, entry := range n.entries {
node = node.set(entry.key, entry.value, 0, h.Hash(entry.key), h, false, resized)
}
return node
}
// Update in-place if mutable.
if mutable {
if idx != -1 {
n.entries[idx] = mapEntry[K, V]{key, value}
} else {
n.entries = append(n.entries, mapEntry[K, V]{key, value})
}
return n
}
// Update existing entry if a match is found.
// Otherwise append to the end of the element list if it doesn't exist.
var other mapArrayNode[K, V]
if idx != -1 {
other.entries = make([]mapEntry[K, V], len(n.entries))
copy(other.entries, n.entries)
other.entries[idx] = mapEntry[K, V]{key, value}
} else {
other.entries = make([]mapEntry[K, V], len(n.entries)+1)
copy(other.entries, n.entries)
other.entries[len(other.entries)-1] = mapEntry[K, V]{key, value}
}
return &other
}
// delete removes the given key from the node. Returns the same node if key does
// not exist. Returns a nil node when removing the last entry.
func (n *mapArrayNode[K, V]) delete(key K, shift uint, keyHash uint32, h Hasher[K], mutable bool, resized *bool) mapNode[K, V] {
idx := n.indexOf(key, h)
// Return original node if key does not exist.
if idx == -1 {
return n
}
*resized = true
// Return nil if this node will contain no nodes.
if len(n.entries) == 1 {
return nil
}
// Update in-place, if mutable.
if mutable {
copy(n.entries[idx:], n.entries[idx+1:])
n.entries[len(n.entries)-1] = mapEntry[K, V]{}
n.entries = n.entries[:len(n.entries)-1]
return n
}
// Otherwise create a copy with the given entry removed.
other := &mapArrayNode[K, V]{entries: make([]mapEntry[K, V], len(n.entries)-1)}
copy(other.entries[:idx], n.entries[:idx])
copy(other.entries[idx:], n.entries[idx+1:])
return other
}
// mapBitmapIndexedNode represents a map branch node with a variable number of
// node slots and indexed using a bitmap. Indexes for the node slots are
// calculated by counting the number of set bits before the target bit using popcount.
type mapBitmapIndexedNode[K, V any] struct {
bitmap uint32
nodes []mapNode[K, V]
}
// get returns the value for the given key.
func (n *mapBitmapIndexedNode[K, V]) get(key K, shift uint, keyHash uint32, h Hasher[K]) (value V, ok bool) {
bit := uint32(1) << ((keyHash >> shift) & mapNodeMask)
if (n.bitmap & bit) == 0 {