forked from benbjohnson/immutable
-
Notifications
You must be signed in to change notification settings - Fork 0
/
immutable.go
2734 lines (2343 loc) · 79.3 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 (
"bytes"
"fmt"
"math/bits"
"reflect"
"sort"
"strings"
)
// 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 struct {
root listNode // 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() *List {
return &List{
root: &listLeafNode{},
}
}
// clone returns a copy of the list.
func (l *List) clone() *List {
other := *l
return &other
}
// Len returns the number of elements in the list.
func (l *List) Len() int {
return l.size
}
// cap returns the total number of possible elements for the current depth.
func (l *List) 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) Get(index int) interface{} {
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) Set(index int, value interface{}) *List {
return l.set(index, value, false)
}
func (l *List) set(index int, value interface{}, mutable bool) *List {
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) Append(value interface{}) *List {
return l.append(value, false)
}
func (l *List) append(value interface{}, mutable bool) *List {
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{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 added to the beginning of the list.
func (l *List) Prepend(value interface{}) *List {
return l.prepend(value, false)
}
func (l *List) prepend(value interface{}, mutable bool) *List {
other := l
if !mutable {
other = l.clone()
}
// Expand list to the left if no slots remain.
if other.origin == 0 {
newRoot := &listBranchNode{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) Slice(start, end int) *List {
return l.slice(start, end, false)
}
func (l *List) slice(start, end int, mutable bool) *List {
// 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).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) Iterator() *ListIterator {
itr := &ListIterator{list: l}
itr.First()
return itr
}
// ListBuilder represents an efficient builder for creating new Lists.
type ListBuilder struct {
list *List // current state
}
// NewListBuilder returns a new instance of ListBuilder.
func NewListBuilder() *ListBuilder {
return &ListBuilder{list: NewList()}
}
// List returns the current copy of the list.
// The builder should not be used again after the list after this call.
func (b *ListBuilder) List() *List {
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) 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) Get(index int) interface{} {
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) Set(index int, value interface{}) {
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) Append(value interface{}) {
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) Prepend(value interface{}) {
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) 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) Iterator() *ListIterator {
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 interface {
depth() uint
get(index int) interface{}
set(index int, v interface{}, mutable bool) listNode
containsBefore(index int) bool
containsAfter(index int) bool
deleteBefore(index int, mutable bool) listNode
deleteAfter(index int, mutable bool) listNode
}
// newListNode returns a leaf node for depth zero, otherwise returns a branch node.
func newListNode(depth uint) listNode {
if depth == 0 {
return &listLeafNode{}
}
return &listBranchNode{d: depth}
}
// listBranchNode represents a branch of a List tree at a given depth.
type listBranchNode struct {
d uint // depth
children [listNodeSize]listNode
}
// depth returns the depth of this branch node from the leaf.
func (n *listBranchNode) depth() uint { return n.d }
// get returns the child node at the segment of the index for this depth.
func (n *listBranchNode) get(index int) interface{} {
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) set(index int, v interface{}, mutable bool) listNode {
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(n.depth() - 1)
}
// Return a copy of this branch with the new child.
var other *listBranchNode
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) 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) 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) deleteBefore(index int, mutable bool) listNode {
// 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
if mutable {
other = n
for i := 0; i < idx; i++ {
n.children[i] = nil
}
} else {
other = &listBranchNode{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) deleteAfter(index int, mutable bool) listNode {
// 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
if mutable {
other = n
for i := idx + 1; i < len(n.children); i++ {
n.children[i] = nil
}
} else {
other = &listBranchNode{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 struct {
children [listNodeSize]interface{}
}
// depth always returns 0 for leaf nodes.
func (n *listLeafNode) depth() uint { return 0 }
// get returns the value at the given index.
func (n *listLeafNode) get(index int) interface{} {
return n.children[index&listNodeMask]
}
// set returns a copy of the node with the value at the index updated to v.
func (n *listLeafNode) set(index int, v interface{}, mutable bool) listNode {
idx := index & listNodeMask
var other *listLeafNode
if mutable {
other = n
} else {
tmp := *n
other = &tmp
}
other.children[idx] = v
return other
}
// containsBefore returns true if non-nil values exists between [0,index).
func (n *listLeafNode) containsBefore(index int) bool {
idx := index & listNodeMask
for i := 0; i < idx; i++ {
if n.children[i] != nil {
return true
}
}
return false
}
// containsAfter returns true if non-nil values exists between (index,listNodeSize).
func (n *listLeafNode) containsAfter(index int) bool {
idx := index & listNodeMask
for i := idx + 1; i < len(n.children); i++ {
if n.children[i] != nil {
return true
}
}
return false
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listLeafNode) deleteBefore(index int, mutable bool) listNode {
if !n.containsBefore(index) {
return n
}
idx := index & listNodeMask
var other *listLeafNode
if mutable {
other = n
for i := 0; i < idx; i++ {
other.children[i] = nil
}
} else {
other = &listLeafNode{}
copy(other.children[idx:][:], n.children[idx:][:])
}
return other
}
// deleteBefore returns a new node with all elements before index removed.
func (n *listLeafNode) deleteAfter(index int, mutable bool) listNode {
if !n.containsAfter(index) {
return n
}
idx := index & listNodeMask
var other *listLeafNode
if mutable {
other = n
for i := idx + 1; i < len(n.children); i++ {
other.children[i] = nil
}
} else {
other = &listLeafNode{}
copy(other.children[:idx+1][:], n.children[:idx+1][:])
}
return other
}
// ListIterator represents an ordered iterator over a list.
type ListIterator struct {
list *List // source list
index int // current index position
stack [32]listIteratorElem // search stack
depth int // stack depth
}
// Done returns true if no more elements remain in the iterator.
func (itr *ListIterator) 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) 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) 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) 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{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) Next() (index int, value interface{}) {
// Exit immediately if there are no elements remaining.
if itr.Done() {
return -1, nil
}
// Retrieve current index & value.
elem := &itr.stack[itr.depth]
index, value = itr.index, elem.node.(*listLeafNode).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) Prev() (index int, value interface{}) {
// Exit immediately if there are no elements remaining.
if itr.Done() {
return -1, nil
}
// Retrieve current index & value.
elem := &itr.stack[itr.depth]
index, value = itr.index, elem.node.(*listLeafNode).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) 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:
child := node.children[elem.index]
itr.stack[itr.depth+1] = listIteratorElem{node: child}
itr.depth++
case *listLeafNode:
return
}
}
}
// listIteratorElem represents the node and it's child index within the stack.
type listIteratorElem struct {
node listNode
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 struct {
size int // total number of key/value pairs
root mapNode // root node of trie
hasher Hasher // 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(hasher Hasher) *Map {
return &Map{
hasher: hasher,
}
}
// Len returns the number of elements in the map.
func (m *Map) Len() int {
return m.size
}
// clone returns a shallow copy of m.
func (m *Map) clone() *Map {
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) Get(key interface{}) (value interface{}, ok bool) {
if m.root == nil {
return nil, 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) Set(key, value interface{}) *Map {
return m.set(key, value, false)
}
func (m *Map) set(key, value interface{}, mutable bool) *Map {
// 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{entries: []mapEntry{{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) Delete(key interface{}) *Map {
return m.delete(key, false)
}
func (m *Map) delete(key interface{}, mutable bool) *Map {
// 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) Iterator() *MapIterator {
itr := &MapIterator{m: m}
itr.First()
return itr
}
// MapBuilder represents an efficient builder for creating Maps.
type MapBuilder struct {
m *Map // current state
}
// NewMapBuilder returns a new instance of MapBuilder.
func NewMapBuilder(hasher Hasher) *MapBuilder {
return &MapBuilder{m: NewMap(hasher)}
}
// Map returns the underlying map. Only call once.
// Builder is invalid after call. Will panic on second invocation.
func (b *MapBuilder) Map() *Map {
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) 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) Get(key interface{}) (value interface{}, 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) Set(key, value interface{}) {
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) Delete(key interface{}) {
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) Iterator() *MapIterator {
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 interface {
get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool)
set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode
delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode
}
var _ mapNode = (*mapArrayNode)(nil)
var _ mapNode = (*mapBitmapIndexedNode)(nil)
var _ mapNode = (*mapHashArrayNode)(nil)
var _ mapNode = (*mapValueNode)(nil)
var _ mapNode = (*mapHashCollisionNode)(nil)
// mapLeafNode represents a node that stores a single key hash at the leaf of the map tree.
type mapLeafNode interface {
mapNode
keyHashValue() uint32
}
var _ mapLeafNode = (*mapValueNode)(nil)
var _ mapLeafNode = (*mapHashCollisionNode)(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 struct {
entries []mapEntry
}
// indexOf returns the entry index of the given key. Returns -1 if key not found.
func (n *mapArrayNode) indexOf(key interface{}, h Hasher) 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) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
i := n.indexOf(key, h)
if i == -1 {
return nil, 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) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
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 = 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{key, value}
} else {
n.entries = append(n.entries, mapEntry{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
if idx != -1 {
other.entries = make([]mapEntry, len(n.entries))
copy(other.entries, n.entries)
other.entries[idx] = mapEntry{key, value}
} else {
other.entries = make([]mapEntry, len(n.entries)+1)
copy(other.entries, n.entries)
other.entries[len(other.entries)-1] = mapEntry{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) delete(key interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
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{}
n.entries = n.entries[:len(n.entries)-1]
return n
}
// Otherwise create a copy with the given entry removed.
other := &mapArrayNode{entries: make([]mapEntry, 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 struct {
bitmap uint32
nodes []mapNode
}
// get returns the value for the given key.
func (n *mapBitmapIndexedNode) get(key interface{}, shift uint, keyHash uint32, h Hasher) (value interface{}, ok bool) {
bit := uint32(1) << ((keyHash >> shift) & mapNodeMask)
if (n.bitmap & bit) == 0 {
return nil, false
}
child := n.nodes[bits.OnesCount32(n.bitmap&(bit-1))]
return child.get(key, shift+mapNodeBits, keyHash, h)
}
// set inserts or updates the value for the given key. If a new key is inserted
// and the size crosses the max size threshold then a hash array node is returned.
func (n *mapBitmapIndexedNode) set(key, value interface{}, shift uint, keyHash uint32, h Hasher, mutable bool, resized *bool) mapNode {
// Extract the index for the bit segment of the key hash.
keyHashFrag := (keyHash >> shift) & mapNodeMask
// Determine the bit based on the hash index.
bit := uint32(1) << keyHashFrag
exists := (n.bitmap & bit) != 0
// Mark as resized if the key doesn't exist.
if !exists {
*resized = true
}
// Find index of node based on popcount of bits before it.