-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy patharray.go
More file actions
1593 lines (1323 loc) · 49.2 KB
/
Copy patharray.go
File metadata and controls
1593 lines (1323 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
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
/*
* Atree - Scalable Arrays and Ordered Maps
*
* Copyright Flow Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package atree
import (
"fmt"
"math"
"strings"
)
const (
// maxArrayElementCount is the max number of elements that can be stored in an array.
// Currently, this limit is set to math.MaxUint32 (4,294,967,295 elements per array).
// ArraySlabHeader.Count (uint32) is used to track element count in array slabs.
// NOTE: MaxArrayElementCount is uint64 since we may want to increase the limit to be
// greater than MaxUint32 in the future.
maxArrayElementCount uint64 = math.MaxUint32
)
// Array is a heterogeneous variable-size array, storing any type of values
// into a smaller ordered list of values and provides efficient functionality
// to lookup, insert and remove elements anywhere in the array.
//
// Array elements can be stored in one or more relatively fixed-sized segments.
//
// Array can be inlined into its parent container when the entire content fits in
// parent container's element size limit. Specifically, array with one segment
// which fits in size limit can be inlined, while arrays with multiple segments
// can't be inlined.
//
// Multiple *Array Go instances can exist for the same logical container;
// they all share the same *arrayState via the SlabStorage-backed registry,
// so structural mutations through any one of them are observed by all of them.
// See array_state.go for the rationale.
type Array struct {
Storage SlabStorage
// state holds the mutable per-logical-container state
// (root pointer, mutableElementIndex).
// Shared across siblings so structural changes propagate.
state *arrayState
// parentUpdater is the callback notifying the parent container
// when this *Array instance triggers a mutation.
// It is per-instance, not shared:
// a Get-loaded instance has a real parent updater,
// while a readonly-iterator-loaded instance has a trap callback
// (see parentUpdaterIsReadOnlyMutationCallback).
// A mutation through one instance must fire only its own callback.
parentUpdater parentUpdater
// parentUpdaterIsReadOnlyMutationCallback is true
// when parentUpdater is a trap callback set by a read-only iterator
// (rather than a real parent-notification callback set by setCallbackWithChild).
// Callers that cache or alias this *Array
// use this to avoid promoting a trap-bearing instance to a shared/canonical wrapper:
// mutations through such a wrapper would trip the trap.
parentUpdaterIsReadOnlyMutationCallback bool
// loadedWithRootID is true when this wrapper was created by NewArrayWithRootID.
// If such a wrapper later observes an inlined state,
// it cannot safely mutate without a parentUpdater:
// root-ID loading only proves access to a standalone root,
// while an inlined value needs a parent write-back path.
loadedWithRootID bool
}
var _ Value = &Array{}
var _ mutableValueNotifier = &Array{}
// Create, copy, and load array
func NewArray(storage SlabStorage, address Address, typeInfo TypeInfo) (*Array, error) {
extraData := &ArrayExtraData{TypeInfo: typeInfo}
sID, err := storage.GenerateSlabID(address)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(
err,
fmt.Sprintf("failed to generate slab ID for address 0x%x", address))
}
root := &ArrayDataSlab{
header: ArraySlabHeader{
slabID: sID,
size: arrayRootDataSlabPrefixSize,
},
extraData: extraData,
}
err = storeSlab(storage, root)
if err != nil {
return nil, err
}
state := newArrayState(root)
storage.SetArrayState(sID, state)
return &Array{
Storage: storage,
state: state,
}, nil
}
func NewArrayWithRootID(storage SlabStorage, rootID SlabID) (*Array, error) {
if rootID == SlabIDUndefined {
return nil, NewSlabIDErrorf("cannot create Array from undefined slab ID")
}
// If another *Array instance for this container already exists, reuse
// its shared state so structural changes propagate.
state := storage.ArrayState(rootID)
// NewArrayWithRootID only loads standalone roots.
// If the registry says this logical container is currently inlined,
// rootID is no longer a live standalone slab ID.
// Do not clear the state here:
// the inlined container may still be alive inside its parent,
// and dropping the registry would reintroduce sibling divergence.
if state != nil && state.root.Inlined() {
return nil, NewSlabNotFoundErrorf(rootID, "array slab is inlined")
}
// A registered state can outlive its container:
// storage.Remove is called both when a container is inlined (still alive)
// and when it is destroyed,
// and the registry deliberately survives Remove for the inline case.
// A non-inlined root must still have its slab in storage —
// if it doesn't, the container was destroyed,
// and returning the leftover state would resurrect it as a zombie.
// An inlined root legitimately has no standalone slab, so it is not checked
// (a container destroyed WHILE inlined never had a slab to remove,
// so it cannot be detected here; its root slab ID is not referenced
// by any remaining storable, so nothing should dereference it).
if state != nil && !state.root.Inlined() {
_, found, err := storage.Retrieve(rootID)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, fmt.Sprintf("failed to retrieve slab %s", rootID))
}
if !found {
storage.RemoveStateForSlab(rootID)
return nil, NewSlabNotFoundErrorf(rootID, "array slab not found")
}
}
if state == nil {
root, err := getArraySlab(storage, rootID)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by getArraySlab().
return nil, err
}
extraData := root.ExtraData()
if extraData == nil {
return nil, NewNotValueError(rootID)
}
state = newArrayState(root)
storage.SetArrayState(rootID, state)
}
return &Array{
Storage: storage,
state: state,
loadedWithRootID: true,
}, nil
}
type ArrayElementProvider func() (Value, error)
func NewArrayFromBatchData(storage SlabStorage, address Address, typeInfo TypeInfo, fn ArrayElementProvider) (*Array, error) {
var slabs []ArraySlab
id, err := storage.GenerateSlabID(address)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(
err,
fmt.Sprintf("failed to generate slab ID for address 0x%x", address))
}
dataSlab := &ArrayDataSlab{
header: ArraySlabHeader{
slabID: id,
size: arrayDataSlabPrefixSize,
},
}
// Batch append data by creating a list of ArrayDataSlab
for {
value, err := fn()
if err != nil {
// Wrap err as external error (if needed) because err is returned by ArrayElementProvider callback.
return nil, wrapErrorAsExternalErrorIfNeeded(err)
}
if value == nil {
break
}
// Finalize current data slab without appending new element
if dataSlab.header.size >= targetThreshold {
// Generate storage id for next data slab
nextID, err := storage.GenerateSlabID(address)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(
err,
fmt.Sprintf("failed to generate slab ID for address 0x%x", address))
}
// Save next slab's slab ID in data slab
dataSlab.next = nextID
// Append data slab to dataSlabs
slabs = append(slabs, dataSlab)
// Create next data slab
dataSlab = &ArrayDataSlab{
header: ArraySlabHeader{
slabID: nextID,
size: arrayDataSlabPrefixSize,
},
}
}
storable, err := value.Storable(storage, address, maxInlineArrayElementSize)
if err != nil {
// Wrap err as external error (if needed) because err is returned by Value interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, "failed to get value's storable")
}
// Append new element
dataSlab.elements = append(dataSlab.elements, storable)
dataSlab.header.count++
// This addition is safe from overflow because slab size is
// checked against targetThreshold before each batch append,
// and a new data slab is created when the threshold is reached.
dataSlab.header.size += storable.ByteSize()
}
// Append last data slab to slabs
slabs = append(slabs, dataSlab)
for len(slabs) > 1 {
lastSlab := slabs[len(slabs)-1]
// Rebalance last slab if needed
if underflowSize, underflow := lastSlab.IsUnderflow(); underflow {
leftSib := slabs[len(slabs)-2]
if leftSib.CanLendToRight(underflowSize) {
// Rebalance with left
err := leftSib.LendToRight(lastSlab)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.LeftToRight().
return nil, err
}
} else {
// Merge with left
err := leftSib.Merge(lastSlab)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Merge().
return nil, err
}
// Remove last slab from slabs
slabs[len(slabs)-1] = nil
slabs = slabs[:len(slabs)-1]
}
}
// All slabs are within target size range.
if len(slabs) == 1 {
// This happens when there were exactly two slabs and
// last slab has merged with the first slab.
break
}
// Store all slabs
for _, slab := range slabs {
err = storeSlab(storage, slab)
if err != nil {
return nil, err
}
}
// Get next level meta slabs
slabs, err = nextLevelArraySlabs(storage, address, slabs)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by nextLevelArraySlabs().
return nil, err
}
}
// found root slab
root := slabs[0]
// root is data slab, adjust its size
if dataSlab, ok := root.(*ArrayDataSlab); ok {
dataSlab.header.size = dataSlab.header.size - arrayDataSlabPrefixSize + arrayRootDataSlabPrefixSize
}
extraData := &ArrayExtraData{TypeInfo: typeInfo}
// Set extra data in root
root.SetExtraData(extraData)
// Store root
err = storeSlab(storage, root)
if err != nil {
return nil, err
}
state := newArrayState(root)
storage.SetArrayState(root.SlabID(), state)
return &Array{
Storage: storage,
state: state,
}, nil
}
// nextLevelArraySlabs returns next level meta data slabs from slabs.
// slabs must have at least 2 elements. It is reused and returned as next level slabs.
// Caller is responsible for rebalance last slab and storing returned slabs in storage.
func nextLevelArraySlabs(storage SlabStorage, address Address, slabs []ArraySlab) ([]ArraySlab, error) {
maxNumberOfHeadersInMetaSlab := (maxThreshold - arrayMetaDataSlabPrefixSize) / arraySlabHeaderSize
nextLevelSlabsIndex := 0
// Generate storage id
id, err := storage.GenerateSlabID(address)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(
err,
fmt.Sprintf("failed to generate slab ID for address 0x%x", address))
}
metaSlab := &ArrayMetaDataSlab{
header: ArraySlabHeader{
slabID: id,
size: arrayMetaDataSlabPrefixSize,
},
}
for _, slab := range slabs {
if len(metaSlab.childrenHeaders) == int(maxNumberOfHeadersInMetaSlab) {
slabs[nextLevelSlabsIndex] = metaSlab
nextLevelSlabsIndex++
// Generate storage id for next meta data slab
id, err = storage.GenerateSlabID(address)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(
err,
fmt.Sprintf("failed to generate slab ID for address 0x%x", address))
}
metaSlab = &ArrayMetaDataSlab{
header: ArraySlabHeader{
slabID: id,
size: arrayMetaDataSlabPrefixSize,
},
}
}
// These additions are safe from overflow because metadata slab size
// is checked against maxThreshold and is split if it exceeds the limit.
metaSlab.header.size += arraySlabHeaderSize
metaSlab.header.count += slab.Header().count
metaSlab.childrenHeaders = append(metaSlab.childrenHeaders, slab.Header())
metaSlab.childrenCountSum = append(metaSlab.childrenCountSum, metaSlab.header.count)
}
// Append last meta slab to slabs
slabs[nextLevelSlabsIndex] = metaSlab
nextLevelSlabsIndex++
return slabs[:nextLevelSlabsIndex], nil
}
// Array operations (get, set, insert, remove, and pop iterate)
func (a *Array) Get(i uint64) (Value, error) {
storable, err := a.state.root.Get(a.Storage, i)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Get().
return nil, err
}
v, err := storable.StoredValue(a.Storage)
if err != nil {
// Wrap err as external error (if needed) because err is returned by Storable interface.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, "failed to get storable's stored value")
}
// As a parent, this array (a) sets up notification callback with child
// value (v) so this array can be notified when child value is modified.
a.setCallbackWithChild(i, v, maxInlineArrayElementSize)
return v, nil
}
func (a *Array) Set(index uint64, value Value) (Storable, error) {
existingStorable, err := a.set(index, value)
if err != nil {
return nil, err
}
var existingValueID ValueID
// If overwritten storable is an inlined slab, uninline the slab and store it in storage.
// This is to prevent potential data loss because the overwritten inlined slab was not in
// storage and any future changes to it would have been lost.
existingStorable, existingValueID, _, err = uninlineStorableIfNeeded(a.Storage, existingStorable)
if err != nil {
return nil, err
}
// Remove overwritten array/map's ValueID from mutableElementIndex if:
// - new value isn't array/map, or
// - new value is array/map with different value ID
if existingValueID != emptyValueID {
unwrappedValue, _ := unwrapValue(value)
newValue, ok := unwrappedValue.(mutableValueNotifier)
if !ok || existingValueID != newValue.ValueID() {
delete(a.state.mutableElementIndex, existingValueID)
}
}
return existingStorable, nil
}
func (a *Array) set(index uint64, value Value) (Storable, error) {
err := a.ensureRootIDLoadedInlinedMutationAllowed()
if err != nil {
return nil, err
}
existingStorable, err := a.state.root.Set(a.Storage, a.Address(), index, value)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Set().
return nil, err
}
if a.state.root.IsFull() {
err = a.splitRoot()
if err != nil {
// Don't need to wrap error as external error because err is already categorized by Array.splitRoot().
return nil, err
}
}
if !a.state.root.IsData() {
root := a.state.root.(*ArrayMetaDataSlab)
if len(root.childrenHeaders) == 1 {
err = a.promoteChildAsNewRoot(root.childrenHeaders[0].slabID)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by Array.promoteChildAsNewRoot().
return nil, err
}
}
}
// This array (a) is a parent to the new child (value), and this array
// can also be a child in another container.
//
// As a parent, this array needs to setup notification callback with
// the new child value, so it can be notified when child is modified.
//
// If this array is a child, it needs to notify its parent because its
// content (maybe also its size) is changed by this "Set" operation.
// If this array is a child, it notifies parent by invoking callback because
// this array is changed by setting new child.
err = a.notifyParentIfNeeded()
if err != nil {
return nil, err
}
// As a parent, this array sets up notification callback with child value
// so this array can be notified when child value is modified.
//
// Setting up notification with new child value can happen at any time
// (either before or after this array notifies its parent) because
// setting up notification doesn't trigger any read/write ops on parent or child.
a.setCallbackWithChild(index, value, maxInlineArrayElementSize)
return existingStorable, nil
}
func (a *Array) Append(value Value) error {
// Don't need to wrap error as external error because err is already categorized by Array.Insert().
return a.Insert(a.Count(), value)
}
func (a *Array) Insert(index uint64, value Value) error {
if a.Count() == maxArrayElementCount {
// Don't insert new element if array already has max number of elements.
return NewArrayElementCannotExceedMaxElementCountError(maxArrayElementCount)
}
err := a.ensureRootIDLoadedInlinedMutationAllowed()
if err != nil {
return err
}
err = a.state.root.Insert(a.Storage, a.Address(), index, value)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Insert().
return err
}
if a.state.root.IsFull() {
err = a.splitRoot()
if err != nil {
// Don't need to wrap error as external error because err is already categorized by Array.splitRoot().
return err
}
}
err = a.incrementIndexFrom(index)
if err != nil {
return err
}
// This array (a) is a parent to the new child (value), and this array
// can also be a child in another container.
//
// As a parent, this array needs to setup notification callback with
// the new child value, so it can be notified when child is modified.
//
// If this array is a child, it needs to notify its parent because its
// content (also its size) is changed by this "Insert" operation.
// If this array is a child, it notifies parent by invoking callback because
// this array is changed by inserting new child.
err = a.notifyParentIfNeeded()
if err != nil {
return err
}
// As a parent, this array sets up notification callback with child value
// so this array can be notified when child value is modified.
//
// Setting up notification with new child value can happen at any time
// (either before or after this array notifies its parent) because
// setting up notification doesn't trigger any read/write ops on parent or child.
a.setCallbackWithChild(index, value, maxInlineArrayElementSize)
return nil
}
func (a *Array) Remove(index uint64) (Storable, error) {
storable, err := a.remove(index)
if err != nil {
return nil, err
}
// If removed storable is an inlined slab, uninline the slab and store it in storage.
// This is to prevent potential data loss because the overwritten inlined slab was not in
// storage and any future changes to it would have been lost.
removedStorable, removedValueID, _, err := uninlineStorableIfNeeded(a.Storage, storable)
if err != nil {
return nil, err
}
// Delete removed element ValueID from mutableElementIndex
if removedValueID != emptyValueID {
delete(a.state.mutableElementIndex, removedValueID)
}
return removedStorable, nil
}
func (a *Array) remove(index uint64) (Storable, error) {
err := a.ensureRootIDLoadedInlinedMutationAllowed()
if err != nil {
return nil, err
}
storable, err := a.state.root.Remove(a.Storage, index)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Remove().
return nil, err
}
if !a.state.root.IsData() {
// Set root to its child slab if root has one child slab.
root := a.state.root.(*ArrayMetaDataSlab)
if len(root.childrenHeaders) == 1 {
err = a.promoteChildAsNewRoot(root.childrenHeaders[0].slabID)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by Array.promoteChildAsNewRoot().
return nil, err
}
}
}
err = a.decrementIndexFrom(index)
if err != nil {
return nil, err
}
// If this array is a child, it notifies parent by invoking callback because
// this array is changed by removing element.
err = a.notifyParentIfNeeded()
if err != nil {
return nil, err
}
return storable, nil
}
type ArrayPopIterationFunc func(Storable)
// PopIterate iterates and removes elements backward.
// Each element is passed to ArrayPopIterationFunc callback before removal.
func (a *Array) PopIterate(fn ArrayPopIterationFunc) error {
err := a.ensureRootIDLoadedInlinedMutationAllowed()
if err != nil {
return err
}
err = a.state.root.PopIterate(a.Storage, fn)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.PopIterate().
return err
}
rootID := a.state.root.SlabID()
extraData := a.state.root.ExtraData()
inlined := a.state.root.Inlined()
size := uint32(arrayRootDataSlabPrefixSize)
if inlined {
size = inlinedArrayDataSlabPrefixSize
}
// Bump the old root's mutation counter before swapping a.root
// so that sibling wrappers whose .root still points to this orphaned slab
// can detect the root swap. See ArraySlab.MutationCount.
a.state.root.BumpMutationCount()
// Set root to empty data slab
a.state.root = &ArrayDataSlab{
header: ArraySlabHeader{
slabID: rootID,
size: size,
},
extraData: extraData,
inlined: inlined,
}
// Save root slab
if !a.Inlined() {
err = storeSlab(a.Storage, a.state.root)
if err != nil {
return err
}
}
return nil
}
// Slab operations (split root, promote child slab to root)
func (a *Array) splitRoot() error {
if a.state.root.IsData() {
// Adjust root data slab size before splitting
dataSlab := a.state.root.(*ArrayDataSlab)
dataSlab.header.size = dataSlab.header.size - arrayRootDataSlabPrefixSize + arrayDataSlabPrefixSize
}
// Get old root's extra data and reset it to nil in old root
extraData := a.state.root.RemoveExtraData()
// Save root node id
rootID := a.state.root.SlabID()
// Assign a new slab ID to old root before splitting it.
sID, err := a.Storage.GenerateSlabID(a.Address())
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return wrapErrorfAsExternalErrorIfNeeded(
err,
fmt.Sprintf("failed to generate slab ID for address 0x%x", a.Address()))
}
oldRoot := a.state.root
oldRoot.SetSlabID(sID)
// Intentionally NOT calling oldRoot.BumpMutationCount() here:
// ArraySlab.Split reuses the receiver as the LEFT child
// (see ArrayDataSlab.Split / ArrayMetaDataSlab.Split — both return (receiver, rightSlab)),
// so the "old root" is not orphaned — it stays in the tree as the left child.
// If a later promoteChildAsNewRoot picks this slab,
// MutationCount() on the live root would falsely report staleness for the initiating wrapper.
// Split old root
leftSlab, rightSlab, err := oldRoot.Split(a.Storage)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Split().
return err
}
// Invariant: ArraySlab.Split must return the receiver as the LEFT child.
// The decision to skip BumpMutationCount above relies on this —
// if Split ever returns a fresh struct for the left side,
// the receiver becomes orphaned and splitRoot must behave like
// promoteChildAsNewRoot (bump).
if Slab(oldRoot) != leftSlab {
panic(NewUnreachableError())
}
left := leftSlab.(ArraySlab)
right := rightSlab.(ArraySlab)
// Create new ArrayMetaDataSlab with the old root's slab ID
// The count and size computations are safe from overflow because the
// total count was the root's count before splitting, which already fit in uint32.
newRoot := &ArrayMetaDataSlab{
header: ArraySlabHeader{
slabID: rootID,
count: left.Header().count + right.Header().count,
size: arrayMetaDataSlabPrefixSize + arraySlabHeaderSize*2,
},
childrenHeaders: []ArraySlabHeader{left.Header(), right.Header()},
childrenCountSum: []uint32{left.Header().count, left.Header().count + right.Header().count},
extraData: extraData,
}
a.state.root = newRoot
err = storeSlab(a.Storage, left)
if err != nil {
return err
}
err = storeSlab(a.Storage, right)
if err != nil {
return err
}
return storeSlab(a.Storage, a.state.root)
}
func (a *Array) promoteChildAsNewRoot(childID SlabID) error {
child, err := getArraySlab(a.Storage, childID)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by getArraySlab().
return err
}
if child.IsData() {
// Adjust data slab size before promoting non-root data slab to root
dataSlab := child.(*ArrayDataSlab)
dataSlab.header.size = dataSlab.header.size - arrayDataSlabPrefixSize + arrayRootDataSlabPrefixSize
}
extraData := a.state.root.RemoveExtraData()
rootID := a.state.root.SlabID()
// Bump the old root's mutation counter before swapping a.root
// so that sibling wrappers whose .root still points to this orphaned slab
// can detect the root swap.
// Promote does not perturb the orphaned old root's SlabID,
// so this counter is the only signal sibling wrappers have.
// See ArraySlab.MutationCount.
a.state.root.BumpMutationCount()
a.state.root = child
a.state.root.SetSlabID(rootID)
a.state.root.SetExtraData(extraData)
err = storeSlab(a.Storage, a.state.root)
if err != nil {
return err
}
err = a.Storage.Remove(childID)
if err != nil {
// Wrap err as external error (if needed) because err is returned by SlabStorage interface.
return wrapErrorfAsExternalErrorIfNeeded(err, fmt.Sprintf("failed to remove slab %s", childID))
}
return nil
}
// mutableValue operations (parent updater callback, mutableElementIndex, etc)
// TODO: maybe optimize this
func (a *Array) incrementIndexFrom(index uint64) error {
// Although range loop over Go map is not deterministic, it is OK
// to use here because this operation is free of side-effect and
// leads to the same results independent of map order.
for id, i := range a.state.mutableElementIndex {
if i >= index {
if a.state.mutableElementIndex[id]+1 >= a.Count() {
return NewFatalError(fmt.Errorf("failed to increment index of ValueID %s in array %s: new index exceeds array count", id, a.ValueID()))
}
a.state.mutableElementIndex[id]++
}
}
return nil
}
// TODO: maybe optimize this
func (a *Array) decrementIndexFrom(index uint64) error {
// Although range loop over Go map is not deterministic, it is OK
// to use here because this operation is free of side-effect and
// leads to the same results independent of map order.
for id, i := range a.state.mutableElementIndex {
if i > index {
if a.state.mutableElementIndex[id] <= 0 {
return NewFatalError(fmt.Errorf("failed to decrement index of ValueID %s in array %s: new index < 0", id, a.ValueID()))
}
a.state.mutableElementIndex[id]--
}
}
return nil
}
func (a *Array) getIndexByValueID(id ValueID) (uint64, bool) {
index, exist := a.state.mutableElementIndex[id]
return index, exist
}
func (a *Array) setParentUpdater(f parentUpdater) {
a.parentUpdater = f
a.parentUpdaterIsReadOnlyMutationCallback = false
}
// setReadOnlyMutationCallback installs a trap callback that fires
// when the *Array is mutated through this instance,
// indicating the instance was loaded via a read-only iterator.
func (a *Array) setReadOnlyMutationCallback(f parentUpdater) {
a.parentUpdater = f
a.parentUpdaterIsReadOnlyMutationCallback = true
}
// HasParentUpdater reports whether a parent-notification (or read-only trap) callback is installed.
// Use HasReadOnlyMutationCallback to distinguish the two cases.
func (a *Array) HasParentUpdater() bool {
return a.parentUpdater != nil
}
// HasReadOnlyMutationCallback reports whether the installed parentUpdater
// is a trap callback set by a read-only iterator
// (as opposed to a real parent-notification callback).
// Callers that want to share or canonicalize the *Array should consult this
// to avoid caching a trap-bearing instance.
func (a *Array) HasReadOnlyMutationCallback() bool {
return a.parentUpdaterIsReadOnlyMutationCallback
}
// setCallbackWithChild sets up callback function with child value (child)
// so parent array (a) can be notified when child value is modified.
func (a *Array) setCallbackWithChild(i uint64, child Value, maxInlineSize uint32) {
// Unwrap child value if needed (e.g. interpreter.SomeValue)
unwrappedChild, wrapperSize := unwrapValue(child)
c, ok := unwrappedChild.(mutableValueNotifier)
if !ok {
return
}
if maxInlineSize < wrapperSize {
maxInlineSize = 0
} else {
maxInlineSize -= wrapperSize
}
vid := c.ValueID()
// mutableElementIndex is lazily initialized.
if a.state.mutableElementIndex == nil {
a.state.mutableElementIndex = make(map[ValueID]uint64)
}
// Index i will be updated with array operations, which affects element index.
a.state.mutableElementIndex[vid] = i
c.setParentUpdater(func() (found bool, err error) {
// Avoid unnecessary write operation on parent container.
// Child value was stored as SlabIDStorable (not inlined) in parent container,
// and continues to be stored as SlabIDStorable (still not inlinable),
// so no update to parent container is needed.
if !c.Inlined() && !c.Inlinable(maxInlineSize) {
return true, nil
}
// Get latest adjusted index by child value ID.
adjustedIndex, exist := a.getIndexByValueID(vid)
if !exist {
return false, nil
}
storable, err := a.state.root.Get(a.Storage, adjustedIndex)
if err != nil {
// Don't need to wrap error as external error because err is already categorized by ArraySlab.Get().
return false, err
}
storable = unwrapStorable(storable)
// Verify retrieved element is either SlabIDStorable or Slab, with identical value ID.
switch storable := storable.(type) {
case SlabIDStorable:
sid := SlabID(storable)
if !vid.equal(sid) {
return false, nil
}
case Slab:
sid := storable.SlabID()
if !vid.equal(sid) {
return false, nil
}
default:
return false, nil
}
// NOTE: Must reset child using original child (not unwrapped child)
// Set child value with parent array using updated index.
// Set() calls child.Storable() which returns inlined or not-inlined child storable.
existingValueStorable, err := a.set(adjustedIndex, child)
if err != nil {
return false, err
}
// Verify overwritten storable has identical value ID.
existingValueStorable = unwrapStorable(existingValueStorable)
switch existingValueStorable := existingValueStorable.(type) {
case SlabIDStorable:
sid := SlabID(existingValueStorable)
if !vid.equal(sid) {
return false, NewFatalError(
fmt.Errorf(
"failed to reset child value in parent updater callback: overwritten SlabIDStorable %s != value ID %s",
sid,
vid))
}
case Slab:
sid := existingValueStorable.SlabID()
if !vid.equal(sid) {
return false, NewFatalError(
fmt.Errorf(
"failed to reset child value in parent updater callback: overwritten Slab ID %s != value ID %s",
sid,
vid))
}