-
Notifications
You must be signed in to change notification settings - Fork 12
/
array.go
4305 lines (3541 loc) · 121 KB
/
array.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
/*
* 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 (
"bytes"
"encoding/binary"
"fmt"
"math"
"strings"
"sync"
"github.com/fxamacker/cbor/v2"
)
// NOTE: we use encoding size (in bytes) instead of Go type size for slab operations,
// such as merge and split, so size constants here are related to encoding size.
const (
slabAddressSize = 8
slabIndexSize = 8
slabIDSize = slabAddressSize + slabIndexSize
// version and flag size: version (1 byte) + flag (1 byte)
versionAndFlagSize = 2
// slab header size: slab index (8 bytes) + count (4 bytes) + size (2 bytes)
// Support up to 4,294,967,295 elements in each array.
// Support up to 65,535 bytes for slab size limit (default limit is 1536 max bytes).
arraySlabHeaderSize = slabIndexSize + 4 + 2
// meta data slab prefix size: version (1 byte) + flag (1 byte) + address (8 bytes) + child header count (2 bytes)
// Support up to 65,535 children per metadata slab.
arrayMetaDataSlabPrefixSize = versionAndFlagSize + slabAddressSize + 2
// Encoded element head in array data slab (fixed-size for easy computation).
arrayDataSlabElementHeadSize = 3
// non-root data slab prefix size: version (1 byte) + flag (1 byte) + next id (16 bytes) + element array head (3 bytes)
// Support up to 65,535 elements in the array per data slab.
arrayDataSlabPrefixSize = versionAndFlagSize + slabIDSize + arrayDataSlabElementHeadSize
// root data slab prefix size: version (1 byte) + flag (1 byte) + element array head (3 bytes)
// Support up to 65,535 elements in the array per data slab.
arrayRootDataSlabPrefixSize = versionAndFlagSize + arrayDataSlabElementHeadSize
// 32 is faster than 24 and 40.
linearScanThreshold = 32
// inlined tag number size: CBOR tag number CBORTagInlinedArray or CBORTagInlinedMap
inlinedTagNumSize = 2
// inlined CBOR array head size: CBOR array head of 3 elements (extra data index, value id, elements)
inlinedCBORArrayHeadSize = 1
// inlined extra data index size: CBOR positive number encoded in 2 bytes [0, 255] (fixed-size for easy computation)
inlinedExtraDataIndexSize = 2
// inlined CBOR byte string head size for value ID: CBOR byte string head for byte string of 8 bytes
inlinedCBORValueIDHeadSize = 1
// inlined value id size: encoded in 8 bytes
inlinedValueIDSize = 8
// inlined array data slab prefix size:
// tag number (2 bytes) +
// 3-element array head (1 byte) +
// extra data index (2 bytes) [0, 255] +
// value ID index head (1 byte) +
// value ID index (8 bytes) +
// element array head (3 bytes)
inlinedArrayDataSlabPrefixSize = inlinedTagNumSize +
inlinedCBORArrayHeadSize +
inlinedExtraDataIndexSize +
inlinedCBORValueIDHeadSize +
inlinedValueIDSize +
arrayDataSlabElementHeadSize
maxInlinedExtraDataIndex = 255
)
type ArraySlabHeader struct {
slabID SlabID // id is used to retrieve slab from storage
size uint32 // size is used to split and merge; leaf: size of all element; internal: size of all headers
count uint32 // count is used to lookup element; leaf: number of elements; internal: number of elements in all its headers
}
type ArrayExtraData struct {
TypeInfo TypeInfo // array type
}
var _ ExtraData = &ArrayExtraData{}
// ArrayDataSlab is leaf node, implementing ArraySlab.
type ArrayDataSlab struct {
next SlabID
header ArraySlabHeader
elements []Storable
// extraData is data that is prepended to encoded slab data.
// It isn't included in slab size calculation for splitting and merging.
extraData *ArrayExtraData
// inlined indicates whether this slab is stored inlined in its parent slab.
// This flag affects Encode(), ByteSize(), etc.
inlined bool
}
func (a *ArrayDataSlab) StoredValue(storage SlabStorage) (Value, error) {
if a.extraData == nil {
return nil, NewNotValueError(a.SlabID())
}
return &Array{
Storage: storage,
root: a,
}, nil
}
var _ ArraySlab = &ArrayDataSlab{}
var _ ContainerStorable = &ArrayDataSlab{}
// ArrayMetaDataSlab is internal node, implementing ArraySlab.
type ArrayMetaDataSlab struct {
header ArraySlabHeader
childrenHeaders []ArraySlabHeader
// Cumulative counts in the children.
// For example, if the counts in childrenHeaders are [10, 15, 12],
// childrenCountSum is [10, 25, 37]
childrenCountSum []uint32
// extraData is data that is prepended to encoded slab data.
// It isn't included in slab size calculation for splitting and merging.
extraData *ArrayExtraData
}
var _ ArraySlab = &ArrayMetaDataSlab{}
func (a *ArrayMetaDataSlab) StoredValue(storage SlabStorage) (Value, error) {
if a.extraData == nil {
return nil, NewNotValueError(a.SlabID())
}
return &Array{
Storage: storage,
root: a,
}, nil
}
type ArraySlab interface {
Slab
Get(storage SlabStorage, index uint64) (Storable, error)
Set(storage SlabStorage, address Address, index uint64, value Value) (Storable, error)
Insert(storage SlabStorage, address Address, index uint64, value Value) error
Remove(storage SlabStorage, index uint64) (Storable, error)
IsData() bool
IsFull() bool
IsUnderflow() (uint32, bool)
CanLendToLeft(size uint32) bool
CanLendToRight(size uint32) bool
SetSlabID(SlabID)
Header() ArraySlabHeader
ExtraData() *ArrayExtraData
RemoveExtraData() *ArrayExtraData
SetExtraData(*ArrayExtraData)
PopIterate(SlabStorage, ArrayPopIterationFunc) error
Inlined() bool
Inlinable(maxInlineSize uint64) bool
Inline(SlabStorage) error
Uninline(SlabStorage) error
}
// 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.
type Array struct {
Storage SlabStorage
root ArraySlab
// parentUpdater is a callback that notifies parent container when this array is modified.
// If this callback is nil, this array has no parent. Otherwise, this array has parent
// and this callback must be used when this array is changed by Append, Insert, Set, Remove, etc.
//
// parentUpdater acts like "parent pointer". It is not stored physically and is only in memory.
// It is setup when child array is returned from parent's Get. It is also setup when
// new child is added to parent through Set or Insert.
parentUpdater parentUpdater
// mutableElementIndex tracks index of mutable element, such as Array and OrderedMap.
// This is needed by mutable element to properly update itself through parentUpdater.
// WARNING: since mutableElementIndex is created lazily, we need to create mutableElementIndex
// if it is nil before adding/updating elements. Range, delete, and read are no-ops on nil Go map.
// TODO: maybe optimize by replacing map to get faster updates.
mutableElementIndex map[ValueID]uint64
}
var bufferPool = sync.Pool{
New: func() interface{} {
e := new(bytes.Buffer)
e.Grow(int(maxThreshold))
return e
},
}
func getBuffer() *bytes.Buffer {
return bufferPool.Get().(*bytes.Buffer)
}
func putBuffer(e *bytes.Buffer) {
e.Reset()
bufferPool.Put(e)
}
var _ Value = &Array{}
var _ mutableValueNotifier = &Array{}
func (a *Array) Address() Address {
return a.root.SlabID().address
}
const arrayExtraDataLength = 1
func newArrayExtraDataFromData(
data []byte,
decMode cbor.DecMode,
decodeTypeInfo TypeInfoDecoder,
) (
*ArrayExtraData,
[]byte,
error,
) {
dec := decMode.NewByteStreamDecoder(data)
extraData, err := newArrayExtraData(dec, decodeTypeInfo)
if err != nil {
return nil, data, err
}
return extraData, data[dec.NumBytesDecoded():], nil
}
// newArrayExtraData decodes CBOR array to extra data:
//
// cborArray{type info}
func newArrayExtraData(dec *cbor.StreamDecoder, decodeTypeInfo TypeInfoDecoder) (*ArrayExtraData, error) {
length, err := dec.DecodeArrayHead()
if err != nil {
return nil, NewDecodingError(err)
}
if length != arrayExtraDataLength {
return nil, NewDecodingError(
fmt.Errorf(
"array extra data has invalid length %d, want %d",
length,
arrayExtraDataLength,
))
}
typeInfo, err := decodeTypeInfo(dec)
if err != nil {
// Wrap err as external error (if needed) because err is returned by TypeInfoDecoder callback.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, "failed to decode type info")
}
return &ArrayExtraData{TypeInfo: typeInfo}, nil
}
func (a *ArrayExtraData) isExtraData() bool {
return true
}
func (a *ArrayExtraData) Type() TypeInfo {
return a.TypeInfo
}
// Encode encodes extra data as CBOR array:
//
// [type info]
func (a *ArrayExtraData) Encode(enc *Encoder, encodeTypeInfo encodeTypeInfo) error {
err := enc.CBOR.EncodeArrayHead(arrayExtraDataLength)
if err != nil {
return NewEncodingError(err)
}
err = encodeTypeInfo(enc, a.TypeInfo)
if err != nil {
// Wrap err as external error (if needed) because err is returned by TypeInfo interface.
return wrapErrorfAsExternalErrorIfNeeded(err, "failed to encode type info")
}
err = enc.CBOR.Flush()
if err != nil {
return NewEncodingError(err)
}
return nil
}
func newArrayDataSlabFromData(
id SlabID,
data []byte,
decMode cbor.DecMode,
decodeStorable StorableDecoder,
decodeTypeInfo TypeInfoDecoder,
) (
*ArrayDataSlab,
error,
) {
// Check minimum data length
if len(data) < versionAndFlagSize {
return nil, NewDecodingErrorf("data is too short for array data slab")
}
h, err := newHeadFromData(data[:versionAndFlagSize])
if err != nil {
return nil, NewDecodingError(err)
}
if h.getSlabArrayType() != slabArrayData {
return nil, NewDecodingErrorf(
"data has invalid head 0x%x, want array data slab flag",
h[:],
)
}
data = data[versionAndFlagSize:]
switch h.version() {
case 0:
return newArrayDataSlabFromDataV0(id, h, data, decMode, decodeStorable, decodeTypeInfo)
case 1:
return newArrayDataSlabFromDataV1(id, h, data, decMode, decodeStorable, decodeTypeInfo)
default:
return nil, NewDecodingErrorf("unexpected version %d for array data slab", h.version())
}
}
// newArrayDataSlabFromDataV0 decodes data in version 0:
//
// Root DataSlab Header:
//
// +-------------------------------+------------+-------------------------------+
// | slab version + flag (2 bytes) | extra data | slab version + flag (2 bytes) |
// +-------------------------------+------------+-------------------------------+
//
// Non-root DataSlab Header (18 bytes):
//
// +-------------------------------+-----------------------------+
// | slab version + flag (2 bytes) | next sib slab ID (16 bytes) |
// +-------------------------------+-----------------------------+
//
// Content:
//
// CBOR encoded array of elements
//
// See ArrayExtraData.Encode() for extra data section format.
func newArrayDataSlabFromDataV0(
id SlabID,
h head,
data []byte,
decMode cbor.DecMode,
decodeStorable StorableDecoder,
decodeTypeInfo TypeInfoDecoder,
) (
*ArrayDataSlab,
error,
) {
var err error
var extraData *ArrayExtraData
// Check flag for extra data
if h.isRoot() {
// Decode extra data
extraData, data, err = newArrayExtraDataFromData(data, decMode, decodeTypeInfo)
if err != nil {
// err is categorized already by newArrayExtraDataFromData.
return nil, err
}
// Skip second head (version + flag) here because it is only present in root slab in version 0.
if len(data) < versionAndFlagSize {
return nil, NewDecodingErrorf("data is too short for array data slab")
}
data = data[versionAndFlagSize:]
}
var next SlabID
if !h.isRoot() {
// Check data length for next slab ID
if len(data) < slabIDSize {
return nil, NewDecodingErrorf("data is too short for array data slab")
}
// Decode next slab ID
next, err = NewSlabIDFromRawBytes(data)
if err != nil {
// error returned from NewSlabIDFromRawBytes is categorized already.
return nil, err
}
data = data[slabIDSize:]
}
// Check data length for array element head
if len(data) < arrayDataSlabElementHeadSize {
return nil, NewDecodingErrorf("data is too short for array data slab")
}
// Decode content (CBOR array)
cborDec := decMode.NewByteStreamDecoder(data)
elemCount, err := cborDec.DecodeArrayHead()
if err != nil {
return nil, NewDecodingError(err)
}
// Compute slab size for version 1.
slabSize := uint32(arrayDataSlabPrefixSize)
if h.isRoot() {
slabSize = arrayRootDataSlabPrefixSize
}
elements := make([]Storable, elemCount)
for i := 0; i < int(elemCount); i++ {
storable, err := decodeStorable(cborDec, id, nil)
if err != nil {
// Wrap err as external error (if needed) because err is returned by StorableDecoder callback.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, "failed to decode array element")
}
elements[i] = storable
slabSize += storable.ByteSize()
}
header := ArraySlabHeader{
slabID: id,
size: slabSize,
count: uint32(elemCount),
}
return &ArrayDataSlab{
next: next,
header: header,
elements: elements,
extraData: extraData,
}, nil
}
// newArrayDataSlabFromDataV1 decodes data in version 1:
//
// DataSlab Header:
//
// +-------------------------------+----------------------+---------------------------------+-----------------------------+
// | slab version + flag (2 bytes) | extra data (if root) | inlined extra data (if present) | next slab ID (if non-empty) |
// +-------------------------------+----------------------+---------------------------------+-----------------------------+
//
// Content:
//
// CBOR encoded array of elements
//
// See ArrayExtraData.Encode() for extra data section format.
// See InlinedExtraData.Encode() for inlined extra data section format.
func newArrayDataSlabFromDataV1(
id SlabID,
h head,
data []byte, // data doesn't include head (first two bytes)
decMode cbor.DecMode,
decodeStorable StorableDecoder,
decodeTypeInfo TypeInfoDecoder,
) (
*ArrayDataSlab,
error,
) {
var err error
var extraData *ArrayExtraData
var inlinedExtraData []ExtraData
var next SlabID
// Decode extra data
if h.isRoot() {
extraData, data, err = newArrayExtraDataFromData(data, decMode, decodeTypeInfo)
if err != nil {
// err is categorized already by newArrayExtraDataFromData.
return nil, err
}
}
// Decode inlined slab extra data
if h.hasInlinedSlabs() {
inlinedExtraData, data, err = newInlinedExtraDataFromData(
data,
decMode,
decodeStorable,
decodeTypeInfo,
)
if err != nil {
// err is categorized already by newInlinedExtraDataFromData.
return nil, err
}
}
// Decode next slab ID
if h.hasNextSlabID() {
next, err = NewSlabIDFromRawBytes(data)
if err != nil {
// error returned from NewSlabIDFromRawBytes is categorized already.
return nil, err
}
data = data[slabIDSize:]
}
// Check minimum data length after header
if len(data) < arrayDataSlabElementHeadSize {
return nil, NewDecodingErrorf("data is too short for array data slab")
}
// Decode content (CBOR array)
cborDec := decMode.NewByteStreamDecoder(data)
elemCount, err := cborDec.DecodeArrayHead()
if err != nil {
return nil, NewDecodingError(err)
}
slabSize := uint32(arrayDataSlabPrefixSize)
if h.isRoot() {
slabSize = arrayRootDataSlabPrefixSize
}
elements := make([]Storable, elemCount)
for i := 0; i < int(elemCount); i++ {
storable, err := decodeStorable(cborDec, id, inlinedExtraData)
if err != nil {
// Wrap err as external error (if needed) because err is returned by StorableDecoder callback.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, "failed to decode array element")
}
elements[i] = storable
slabSize += storable.ByteSize()
}
// Check if data reached EOF
if cborDec.NumBytesDecoded() < len(data) {
return nil, NewDecodingErrorf("data has %d bytes of extraneous data for array data slab", len(data)-cborDec.NumBytesDecoded())
}
header := ArraySlabHeader{
slabID: id,
size: slabSize,
count: uint32(elemCount),
}
return &ArrayDataSlab{
next: next,
header: header,
elements: elements,
extraData: extraData,
inlined: false, // this function is only called when slab is not inlined.
}, nil
}
// DecodeInlinedArrayStorable decodes inlined array data slab. Encoding is
// version 1 with CBOR tag having tag number CBORTagInlinedArray, and tag contant
// as 3-element array:
//
// +------------------+----------------+----------+
// | extra data index | value ID index | elements |
// +------------------+----------------+----------+
//
// NOTE: This function doesn't decode tag number because tag number is decoded
// in the caller and decoder only contains tag content.
func DecodeInlinedArrayStorable(
dec *cbor.StreamDecoder,
decodeStorable StorableDecoder,
parentSlabID SlabID,
inlinedExtraData []ExtraData,
) (
Storable,
error,
) {
const inlinedArrayDataSlabArrayCount = 3
arrayCount, err := dec.DecodeArrayHead()
if err != nil {
return nil, NewDecodingError(err)
}
if arrayCount != inlinedArrayDataSlabArrayCount {
return nil, NewDecodingError(
fmt.Errorf(
"failed to decode inlined array data slab: expect %d elements, got %d elements",
inlinedArrayDataSlabArrayCount,
arrayCount))
}
// element 0: extra data index
extraDataIndex, err := dec.DecodeUint64()
if err != nil {
return nil, NewDecodingError(err)
}
if extraDataIndex >= uint64(len(inlinedExtraData)) {
return nil, NewDecodingError(
fmt.Errorf(
"failed to decode inlined array data slab: inlined extra data index %d exceeds number of inlined extra data %d",
extraDataIndex,
len(inlinedExtraData)))
}
extraData, ok := inlinedExtraData[extraDataIndex].(*ArrayExtraData)
if !ok {
return nil, NewDecodingError(
fmt.Errorf(
"failed to decode inlined array data slab: expect *ArrayExtraData, got %T",
inlinedExtraData[extraDataIndex]))
}
// element 1: slab index
b, err := dec.DecodeBytes()
if err != nil {
return nil, NewDecodingError(err)
}
if len(b) != slabIndexSize {
return nil, NewDecodingError(
fmt.Errorf(
"failed to decode inlined array data slab: expect %d bytes for slab index, got %d bytes",
slabIndexSize,
len(b)))
}
var index SlabIndex
copy(index[:], b)
slabID := NewSlabID(parentSlabID.address, index)
// Decode array elements (CBOR array)
elemCount, err := dec.DecodeArrayHead()
if err != nil {
return nil, NewDecodingError(err)
}
size := uint32(inlinedArrayDataSlabPrefixSize)
elements := make([]Storable, elemCount)
for i := 0; i < int(elemCount); i++ {
storable, err := decodeStorable(dec, slabID, inlinedExtraData)
if err != nil {
// Wrap err as external error (if needed) because err is returned by StorableDecoder callback.
return nil, wrapErrorfAsExternalErrorIfNeeded(err, "failed to decode array element")
}
elements[i] = storable
size += storable.ByteSize()
}
header := ArraySlabHeader{
slabID: slabID,
size: size,
count: uint32(elemCount),
}
return &ArrayDataSlab{
header: header,
elements: elements,
extraData: &ArrayExtraData{
// Make a copy of extraData.TypeInfo because
// inlined extra data are shared by all inlined slabs.
TypeInfo: extraData.TypeInfo.Copy(),
},
inlined: true,
}, nil
}
// encodeAsInlined encodes inlined array data slab. Encoding is
// version 1 with CBOR tag having tag number CBORTagInlinedArray,
// and tag contant as 3-element array:
//
// +------------------+----------------+----------+
// | extra data index | value ID index | elements |
// +------------------+----------------+----------+
func (a *ArrayDataSlab) encodeAsInlined(enc *Encoder) error {
if a.extraData == nil {
return NewEncodingError(
fmt.Errorf("failed to encode non-root array data slab as inlined"))
}
if !a.inlined {
return NewEncodingError(
fmt.Errorf("failed to encode standalone array data slab as inlined"))
}
extraDataIndex, err := enc.inlinedExtraData().addArrayExtraData(a.extraData)
if err != nil {
// err is already categorized by InlinedExtraData.addArrayExtraData().
return err
}
if extraDataIndex > maxInlinedExtraDataIndex {
return NewEncodingError(
fmt.Errorf("failed to encode inlined array data slab: extra data index %d exceeds limit %d", extraDataIndex, maxInlinedExtraDataIndex))
}
// Encode tag number and array head of 3 elements
err = enc.CBOR.EncodeRawBytes([]byte{
// tag number
0xd8, CBORTagInlinedArray,
// array head of 3 elements
0x83,
})
if err != nil {
return NewEncodingError(err)
}
// element 0: extra data index
// NOTE: encoded extra data index is fixed sized CBOR uint
err = enc.CBOR.EncodeRawBytes([]byte{
0x18,
byte(extraDataIndex),
})
if err != nil {
return NewEncodingError(err)
}
// element 1: slab index
err = enc.CBOR.EncodeBytes(a.header.slabID.index[:])
if err != nil {
return NewEncodingError(err)
}
// element 2: array elements
err = a.encodeElements(enc)
if err != nil {
// err is already categorized by ArrayDataSlab.encodeElements().
return err
}
err = enc.CBOR.Flush()
if err != nil {
return NewEncodingError(err)
}
return nil
}
// Encode encodes this array data slab to the given encoder.
//
// DataSlab Header:
//
// +-------------------------------+----------------------+---------------------------------+-----------------------------+
// | slab version + flag (2 bytes) | extra data (if root) | inlined extra data (if present) | next slab ID (if non-empty) |
// +-------------------------------+----------------------+---------------------------------+-----------------------------+
//
// Content:
//
// CBOR encoded array of elements
//
// See ArrayExtraData.Encode() for extra data section format.
// See InlinedExtraData.Encode() for inlined extra data section format.
func (a *ArrayDataSlab) Encode(enc *Encoder) error {
if a.inlined {
return a.encodeAsInlined(enc)
}
// Encoding is done in two steps:
//
// 1. Encode array elements using a new buffer while collecting inlined extra data from inlined elements.
// 2. Encode slab with deduplicated inlined extra data and copy encoded elements from previous buffer.
// Get a buffer from a pool to encode elements.
elementBuf := getBuffer()
defer putBuffer(elementBuf)
elementEnc := NewEncoder(elementBuf, enc.encMode)
err := a.encodeElements(elementEnc)
if err != nil {
// err is already categorized by Array.encodeElements().
return err
}
err = elementEnc.CBOR.Flush()
if err != nil {
return NewEncodingError(err)
}
const version = 1
h, err := newArraySlabHead(version, slabArrayData)
if err != nil {
return NewEncodingError(err)
}
if a.HasPointer() {
h.setHasPointers()
}
if a.next != SlabIDUndefined {
h.setHasNextSlabID()
}
if a.extraData != nil {
h.setRoot()
}
if elementEnc.hasInlinedExtraData() {
h.setHasInlinedSlabs()
}
// Encode head (version + flag)
_, err = enc.Write(h[:])
if err != nil {
return NewEncodingError(err)
}
// Encode extra data
if a.extraData != nil {
// Use defaultEncodeTypeInfo to encode root level TypeInfo as is.
err = a.extraData.Encode(enc, defaultEncodeTypeInfo)
if err != nil {
// err is already categorized by ArrayExtraData.Encode().
return err
}
}
// Encode inlined extra data
if elementEnc.hasInlinedExtraData() {
err = elementEnc.inlinedExtraData().Encode(enc)
if err != nil {
// err is already categorized by inlinedExtraData.Encode().
return err
}
}
// Encode next slab ID
if a.next != SlabIDUndefined {
n, err := a.next.ToRawBytes(enc.Scratch[:])
if err != nil {
// Don't need to wrap because err is already categorized by SlabID.ToRawBytes().
return err
}
_, err = enc.Write(enc.Scratch[:n])
if err != nil {
return NewEncodingError(err)
}
}
// Encode elements by copying raw bytes from previous buffer
err = enc.CBOR.EncodeRawBytes(elementBuf.Bytes())
if err != nil {
return NewEncodingError(err)
}
err = enc.CBOR.Flush()
if err != nil {
return NewEncodingError(err)
}
return nil
}
func (a *ArrayDataSlab) encodeElements(enc *Encoder) error {
// Encode CBOR array size manually for fix-sized encoding
enc.Scratch[0] = 0x80 | 25
countOffset := 1
const countSize = 2
binary.BigEndian.PutUint16(
enc.Scratch[countOffset:],
uint16(len(a.elements)),
)
// Write scratch content to encoder
totalSize := countOffset + countSize
err := enc.CBOR.EncodeRawBytes(enc.Scratch[:totalSize])
if err != nil {
return NewEncodingError(err)
}
// Encode data slab content (array of elements)
for _, e := range a.elements {
err = e.Encode(enc)
if err != nil {
// Wrap err as external error (if needed) because err is returned by Storable interface.
return wrapErrorfAsExternalErrorIfNeeded(err, "failed to encode array element")
}
}
err = enc.CBOR.Flush()
if err != nil {
return NewEncodingError(err)
}
return nil
}
func (a *ArrayDataSlab) Inlined() bool {
return a.inlined
}
// Inlinable returns true if
// - array data slab is root slab
// - size of inlined array data slab <= maxInlineSize
func (a *ArrayDataSlab) Inlinable(maxInlineSize uint64) bool {
if a.extraData == nil {
// Non-root data slab is not inlinable.
return false
}
// At this point, this data slab is either
// - inlined data slab, or
// - not inlined root data slab
// Compute inlined size from cached slab size
inlinedSize := a.header.size
if !a.inlined {
inlinedSize = inlinedSize -
arrayRootDataSlabPrefixSize +
inlinedArrayDataSlabPrefixSize
}
// Inlined byte size must be less than max inline size.
return uint64(inlinedSize) <= maxInlineSize
}
// Inline converts not-inlined ArrayDataSlab to inlined ArrayDataSlab and removes it from storage.
func (a *ArrayDataSlab) Inline(storage SlabStorage) error {
if a.inlined {
return NewFatalError(fmt.Errorf("failed to inline ArrayDataSlab %s: it is inlined already", a.header.slabID))
}
id := a.header.slabID
// Remove slab from storage because it is going to be inlined.
err := storage.Remove(id)
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", id))
}
// Update data slab size as inlined slab.
a.header.size = a.header.size -
arrayRootDataSlabPrefixSize +
inlinedArrayDataSlabPrefixSize
// Update data slab inlined status.
a.inlined = true
return nil
}
// Uninline converts an inlined ArrayDataSlab to uninlined ArrayDataSlab and stores it in storage.
func (a *ArrayDataSlab) Uninline(storage SlabStorage) error {
if !a.inlined {
return NewFatalError(fmt.Errorf("failed to un-inline ArrayDataSlab %s: it is not inlined", a.header.slabID))
}
// Update data slab size
a.header.size = a.header.size -
inlinedArrayDataSlabPrefixSize +
arrayRootDataSlabPrefixSize
// Update data slab inlined status
a.inlined = false
// Store slab in storage
return storeSlab(storage, a)