-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
encoding.go
3217 lines (2967 loc) · 105 KB
/
encoding.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
// Copyright 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package encoding
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"math"
"reflect"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"unsafe"
"github.com/cockroachdb/apd/v3"
"github.com/cockroachdb/cockroach/pkg/geo/geopb"
"github.com/cockroachdb/cockroach/pkg/util/bitarray"
"github.com/cockroachdb/cockroach/pkg/util/duration"
"github.com/cockroachdb/cockroach/pkg/util/encoding/encodingtype"
"github.com/cockroachdb/cockroach/pkg/util/ipaddr"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeofday"
"github.com/cockroachdb/cockroach/pkg/util/timetz"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
)
const (
encodedNull = 0x00
// A marker greater than NULL but lower than any other value.
// This value is not actually ever present in a stored key, but
// it's used in keys used as span boundaries for index scans.
encodedNotNull = 0x01
floatNaN = encodedNotNull + 1
floatNeg = floatNaN + 1
floatZero = floatNeg + 1
floatPos = floatZero + 1
floatNaNDesc = floatPos + 1 // NaN encoded descendingly
// The gap between floatNaNDesc and bytesMarker was left for
// compatibility reasons.
bytesMarker byte = 0x12
bytesDescMarker = bytesMarker + 1
timeMarker = bytesDescMarker + 1
durationBigNegMarker = timeMarker + 1 // Only used for durations < MinInt64 nanos.
durationMarker = durationBigNegMarker + 1
durationBigPosMarker = durationMarker + 1 // Only used for durations > MaxInt64 nanos.
decimalNaN = durationBigPosMarker + 1 // 24
decimalNegativeInfinity = decimalNaN + 1
decimalNegLarge = decimalNegativeInfinity + 1
decimalNegMedium = decimalNegLarge + 11
decimalNegSmall = decimalNegMedium + 1
decimalZero = decimalNegSmall + 1
decimalPosSmall = decimalZero + 1
decimalPosMedium = decimalPosSmall + 1
decimalPosLarge = decimalPosMedium + 11
decimalInfinity = decimalPosLarge + 1
decimalNaNDesc = decimalInfinity + 1 // NaN encoded descendingly
decimalTerminator = 0x00
jsonInvertedIndex = decimalNaNDesc + 1
jsonEmptyArray = jsonInvertedIndex + 1
jsonEmptyObject = jsonEmptyArray + 1
bitArrayMarker = jsonEmptyObject + 1
bitArrayDescMarker = bitArrayMarker + 1
bitArrayDataTerminator = 0x00
bitArrayDataDescTerminator = 0xff
timeTZMarker = bitArrayDescMarker + 1
geoMarker = timeTZMarker + 1
geoDescMarker = geoMarker + 1
// Markers and terminators for key encoding Datum arrays in sorted order.
// For the arrayKeyMarker and other types like bytes and bit arrays, it
// might be unclear why we have a separate marker for the ascending and
// descending cases. This is necessary because the terminators for these
// encodings are different depending on the direction the data is encoded
// in. In order to safely decode a set of bytes without knowing the direction
// of the encoding, we must store this information in the marker. Otherwise,
// we would not know what terminator to look for when decoding this format.
arrayKeyMarker = geoDescMarker + 1
arrayKeyDescendingMarker = arrayKeyMarker + 1
box2DMarker = arrayKeyDescendingMarker + 1
geoInvertedIndexMarker = box2DMarker + 1
emptyArray = geoInvertedIndexMarker + 1
voidMarker = emptyArray + 1
arrayKeyTerminator byte = 0x00
arrayKeyDescendingTerminator byte = 0xFF
// We use different null encodings for nulls within key arrays. Doing this
// allows for the terminator to be less/greater than the null value within
// arrays. These byte values overlap with encodedNotNull and
// encodedNotNullDesc, but they can only exist within an encoded array key.
// Because of the context, they cannot be ambiguous with these other bytes.
ascendingNullWithinArrayKey byte = 0x01
descendingNullWithinArrayKey byte = 0xFE
// IntMin is chosen such that the range of int tags does not overlap the
// ascii character set that is frequently used in testing.
IntMin = 0x80 // 128
intMaxWidth = 8
intZero = IntMin + intMaxWidth // 136
intSmall = IntMax - intZero - intMaxWidth // 109
// IntMax is the maximum int tag value.
IntMax = 0xfd // 253
// Nulls come last when encoded descendingly.
// This value is not actually ever present in a stored key, but
// it's used in keys used as span boundaries for index scans.
encodedNotNullDesc = 0xfe
encodedNullDesc = 0xff
// offsetSecsToMicros is a constant that allows conversion from seconds
// to microseconds for offsetSecs type calculations (e.g. for TimeTZ).
offsetSecsToMicros = 1000000
)
const (
// EncodedDurationMaxLen is the largest number of bytes used when encoding a
// Duration.
EncodedDurationMaxLen = 1 + 3*binary.MaxVarintLen64 // 3 varints are encoded.
// EncodedTimeTZMaxLen is the largest number of bytes used when encoding a
// TimeTZ.
EncodedTimeTZMaxLen = 1 + binary.MaxVarintLen64 + binary.MaxVarintLen32
)
// Direction for ordering results.
type Direction int
// Direction values.
const (
_ Direction = iota
Ascending
Descending
)
const escapeLength = 2
// EncodeUint32Ascending encodes the uint32 value using a big-endian 4 byte
// representation. The bytes are appended to the supplied buffer and
// the final buffer is returned.
func EncodeUint32Ascending(b []byte, v uint32) []byte {
return append(b, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
// PutUint32Ascending encodes the uint32 value using a big-endian 4 byte
// representation at the specified index, lengthening the input slice if
// necessary.
func PutUint32Ascending(b []byte, v uint32, idx int) []byte {
for len(b) < idx+4 {
b = append(b, 0)
}
b[idx] = byte(v >> 24)
b[idx+1] = byte(v >> 16)
b[idx+2] = byte(v >> 8)
b[idx+3] = byte(v)
return b
}
// EncodeUint32Descending encodes the uint32 value so that it sorts in
// reverse order, from largest to smallest.
func EncodeUint32Descending(b []byte, v uint32) []byte {
return EncodeUint32Ascending(b, ^v)
}
// DecodeUint32Ascending decodes a uint32 from the input buffer, treating
// the input as a big-endian 4 byte uint32 representation. The remainder
// of the input buffer and the decoded uint32 are returned.
func DecodeUint32Ascending(b []byte) ([]byte, uint32, error) {
if len(b) < 4 {
return nil, 0, errors.Errorf("insufficient bytes to decode uint32 int value")
}
v := binary.BigEndian.Uint32(b)
return b[4:], v, nil
}
// DecodeUint32Descending decodes a uint32 value which was encoded
// using EncodeUint32Descending.
func DecodeUint32Descending(b []byte) ([]byte, uint32, error) {
leftover, v, err := DecodeUint32Ascending(b)
return leftover, ^v, err
}
const uint64AscendingEncodedLength = 8
// EncodeUint64Ascending encodes the uint64 value using a big-endian 8 byte
// representation. The bytes are appended to the supplied buffer and
// the final buffer is returned.
func EncodeUint64Ascending(b []byte, v uint64) []byte {
return append(b,
byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32),
byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
// EncodeUint64Descending encodes the uint64 value so that it sorts in
// reverse order, from largest to smallest.
func EncodeUint64Descending(b []byte, v uint64) []byte {
return EncodeUint64Ascending(b, ^v)
}
// DecodeUint64Ascending decodes a uint64 from the input buffer, treating
// the input as a big-endian 8 byte uint64 representation. The remainder
// of the input buffer and the decoded uint64 are returned.
func DecodeUint64Ascending(b []byte) ([]byte, uint64, error) {
if len(b) < 8 {
return nil, 0, errors.Errorf("insufficient bytes to decode uint64 int value")
}
v := binary.BigEndian.Uint64(b)
return b[8:], v, nil
}
// DecodeUint64Descending decodes a uint64 value which was encoded
// using EncodeUint64Descending.
func DecodeUint64Descending(b []byte) ([]byte, uint64, error) {
leftover, v, err := DecodeUint64Ascending(b)
return leftover, ^v, err
}
// MaxVarintLen is the maximum length of a value encoded using any of:
// - EncodeVarintAscending
// - EncodeVarintDescending
// - EncodeUvarintAscending
// - EncodeUvarintDescending
const MaxVarintLen = 9
// EncodeVarintAscending encodes the int64 value using a variable length
// (length-prefixed) representation. The length is encoded as a single
// byte. If the value to be encoded is negative the length is encoded
// as 8-numBytes. If the value is positive it is encoded as
// 8+numBytes. The encoded bytes are appended to the supplied buffer
// and the final buffer is returned.
func EncodeVarintAscending(b []byte, v int64) []byte {
if v < 0 {
switch {
case v >= -0xff:
return append(b, IntMin+7, byte(v))
case v >= -0xffff:
return append(b, IntMin+6, byte(v>>8), byte(v))
case v >= -0xffffff:
return append(b, IntMin+5, byte(v>>16), byte(v>>8), byte(v))
case v >= -0xffffffff:
return append(b, IntMin+4, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
case v >= -0xffffffffff:
return append(b, IntMin+3, byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8),
byte(v))
case v >= -0xffffffffffff:
return append(b, IntMin+2, byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16),
byte(v>>8), byte(v))
case v >= -0xffffffffffffff:
return append(b, IntMin+1, byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24),
byte(v>>16), byte(v>>8), byte(v))
default:
return append(b, IntMin, byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32),
byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
}
return EncodeUvarintAscending(b, uint64(v))
}
// EncodeVarintDescending encodes the int64 value so that it sorts in reverse
// order, from largest to smallest.
func EncodeVarintDescending(b []byte, v int64) []byte {
return EncodeVarintAscending(b, ^v)
}
// getVarintLen returns the encoded length of an encoded varint. Assumes the
// slice has at least one byte.
func getVarintLen(b []byte) (int, error) {
length := int(b[0]) - intZero
if length >= 0 {
if length <= intSmall {
// just the tag
return 1, nil
}
// tag and length-intSmall bytes
length = 1 + length - intSmall
} else {
// tag and -length bytes
length = 1 - length
}
if length > len(b) {
return 0, errors.Errorf("varint length %d exceeds slice length %d", length, len(b))
}
return length, nil
}
// DecodeVarintAscending decodes a value encoded by EncodeVarintAscending.
func DecodeVarintAscending(b []byte) ([]byte, int64, error) {
if len(b) == 0 {
return nil, 0, errors.Errorf("insufficient bytes to decode varint value")
}
length := int(b[0]) - intZero
if length < 0 {
length = -length
remB := b[1:]
if len(remB) < length {
return nil, 0, errors.Errorf("insufficient bytes to decode varint value: %q", remB)
}
var v int64
// Use the ones-complement of each encoded byte in order to build
// up a positive number, then take the ones-complement again to
// arrive at our negative value.
for _, t := range remB[:length] {
v = (v << 8) | int64(^t)
}
return remB[length:], ^v, nil
}
remB, v, err := DecodeUvarintAscending(b)
if err != nil {
return remB, 0, err
}
if v > math.MaxInt64 {
return nil, 0, errors.Errorf("varint %d overflows int64", v)
}
return remB, int64(v), nil
}
// DecodeVarintDescending decodes a int64 value which was encoded
// using EncodeVarintDescending.
func DecodeVarintDescending(b []byte) ([]byte, int64, error) {
leftover, v, err := DecodeVarintAscending(b)
return leftover, ^v, err
}
// EncodeUvarintAscending encodes the uint64 value using a variable length
// (length-prefixed) representation. The length is encoded as a single
// byte indicating the number of encoded bytes (-8) to follow. See
// EncodeVarintAscending for rationale. The encoded bytes are appended to the
// supplied buffer and the final buffer is returned.
func EncodeUvarintAscending(b []byte, v uint64) []byte {
switch {
case v <= intSmall:
return append(b, intZero+byte(v))
case v <= 0xff:
return append(b, IntMax-7, byte(v))
case v <= 0xffff:
return append(b, IntMax-6, byte(v>>8), byte(v))
case v <= 0xffffff:
return append(b, IntMax-5, byte(v>>16), byte(v>>8), byte(v))
case v <= 0xffffffff:
return append(b, IntMax-4, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
case v <= 0xffffffffff:
return append(b, IntMax-3, byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8),
byte(v))
case v <= 0xffffffffffff:
return append(b, IntMax-2, byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16),
byte(v>>8), byte(v))
case v <= 0xffffffffffffff:
return append(b, IntMax-1, byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24),
byte(v>>16), byte(v>>8), byte(v))
default:
return append(b, IntMax, byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32),
byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
}
// EncodedLengthUvarintAscending returns the length of the variable length
// representation, i.e. the number of bytes appended by EncodeUvarintAscending.
func EncodedLengthUvarintAscending(v uint64) int {
switch {
case v <= intSmall:
return 1
case v <= 0xff:
return 2
case v <= 0xffff:
return 3
case v <= 0xffffff:
return 4
case v <= 0xffffffff:
return 5
case v <= 0xffffffffff:
return 6
case v <= 0xffffffffffff:
return 7
case v <= 0xffffffffffffff:
return 8
default:
return 9
}
}
// EncodeUvarintDescending encodes the uint64 value so that it sorts in
// reverse order, from largest to smallest.
func EncodeUvarintDescending(b []byte, v uint64) []byte {
switch {
case v == 0:
return append(b, IntMin+8)
case v <= 0xff:
v = ^v
return append(b, IntMin+7, byte(v))
case v <= 0xffff:
v = ^v
return append(b, IntMin+6, byte(v>>8), byte(v))
case v <= 0xffffff:
v = ^v
return append(b, IntMin+5, byte(v>>16), byte(v>>8), byte(v))
case v <= 0xffffffff:
v = ^v
return append(b, IntMin+4, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
case v <= 0xffffffffff:
v = ^v
return append(b, IntMin+3, byte(v>>32), byte(v>>24), byte(v>>16), byte(v>>8),
byte(v))
case v <= 0xffffffffffff:
v = ^v
return append(b, IntMin+2, byte(v>>40), byte(v>>32), byte(v>>24), byte(v>>16),
byte(v>>8), byte(v))
case v <= 0xffffffffffffff:
v = ^v
return append(b, IntMin+1, byte(v>>48), byte(v>>40), byte(v>>32), byte(v>>24),
byte(v>>16), byte(v>>8), byte(v))
default:
v = ^v
return append(b, IntMin, byte(v>>56), byte(v>>48), byte(v>>40), byte(v>>32),
byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}
}
// highestByteIndex returns the index (0 to 7) of the highest nonzero byte in v.
func highestByteIndex(v uint64) int {
l := 0
if v > 0xffffffff {
v >>= 32
l += 4
}
if v > 0xffff {
v >>= 16
l += 2
}
if v > 0xff {
l++
}
return l
}
// EncLenUvarintAscending returns the encoding length for EncodeUvarintAscending
// without actually encoding.
func EncLenUvarintAscending(v uint64) int {
if v <= intSmall {
return 1
}
return 2 + highestByteIndex(v)
}
// EncLenUvarintDescending returns the encoding length for
// EncodeUvarintDescending without actually encoding.
func EncLenUvarintDescending(v uint64) int {
if v == 0 {
return 1
}
return 2 + highestByteIndex(v)
}
// GetUvarintLen is similar to DecodeUvarintAscending except that it returns the
// length of the prefix that encodes a uint64 value in bytes without actually
// decoding the value. An error is returned if b does not contain a valid
// encoding of an unsigned int datum.
func GetUvarintLen(b []byte) (int, error) {
if len(b) == 0 {
return 0, errors.Errorf("insufficient bytes to decode uvarint value")
}
length := int(b[0]) - intZero
if length <= intSmall {
return 1, nil
}
length -= intSmall
if length < 0 || length > 8 {
return 0, errors.Errorf("invalid uvarint length of %d", length)
} else if len(b) <= length {
// Note: we use <= for comparison here as opposed to the < in
// DecodeUvarintAscending because in the latter the first byte for the
// uvarint is removed as part of decoding. We need to account for the first
// byte when assessing the size.
return 0, errors.Errorf("insufficient bytes to decode uvarint value: %q", b)
}
return 1 + length, nil
}
// DecodeUvarintAscending decodes a uint64 encoded uint64 from the input
// buffer. The remainder of the input buffer and the decoded uint64
// are returned.
func DecodeUvarintAscending(b []byte) ([]byte, uint64, error) {
if len(b) == 0 {
return nil, 0, errors.Errorf("insufficient bytes to decode uvarint value")
}
length := int(b[0]) - intZero
b = b[1:] // skip length byte
if length <= intSmall {
return b, uint64(length), nil
}
length -= intSmall
if length < 0 || length > 8 {
return nil, 0, errors.Errorf("invalid uvarint length of %d", length)
} else if len(b) < length {
return nil, 0, errors.Errorf("insufficient bytes to decode uvarint value: %q", b)
}
var v uint64
// It is faster to range over the elements in a slice than to index
// into the slice on each loop iteration.
for _, t := range b[:length] {
v = (v << 8) | uint64(t)
}
return b[length:], v, nil
}
// DecodeUvarintDescending decodes a uint64 value which was encoded
// using EncodeUvarintDescending.
func DecodeUvarintDescending(b []byte) ([]byte, uint64, error) {
if len(b) == 0 {
return nil, 0, errors.Errorf("insufficient bytes to decode uvarint value")
}
length := intZero - int(b[0])
b = b[1:] // skip length byte
if length < 0 || length > 8 {
return nil, 0, errors.Errorf("invalid uvarint length of %d", length)
} else if len(b) < length {
return nil, 0, errors.Errorf("insufficient bytes to decode uvarint value: %q", b)
}
var x uint64
for _, t := range b[:length] {
x = (x << 8) | uint64(^t)
}
return b[length:], x, nil
}
const (
// <term> -> \x00\x01
// \x00 -> \x00\xff
escape byte = 0x00
escapedTerm byte = 0x01
escapedJSONObjectKeyTerm byte = 0x02
escapedJSONArray byte = 0x03
escaped00 byte = 0xff
escapedFF byte = 0x00
)
type escapes struct {
escape byte
escapedTerm byte
escaped00 byte
escapedFF byte
marker byte
}
var (
ascendingBytesEscapes = escapes{escape, escapedTerm, escaped00, escapedFF, bytesMarker}
descendingBytesEscapes = escapes{^escape, ^escapedTerm, ^escaped00, ^escapedFF, bytesDescMarker}
ascendingGeoEscapes = escapes{escape, escapedTerm, escaped00, escapedFF, geoMarker}
descendingGeoEscapes = escapes{^escape, ^escapedTerm, ^escaped00, ^escapedFF, geoDescMarker}
)
// EncodeBytesAscending encodes the []byte value using an escape-based
// encoding. The encoded value is terminated with the sequence
// "\x00\x01" which is guaranteed to not occur elsewhere in the
// encoded value. The encoded bytes are append to the supplied buffer
// and the resulting buffer is returned.
func EncodeBytesAscending(b []byte, data []byte) []byte {
return encodeBytesAscendingWithTerminatorAndPrefix(b, data, ascendingBytesEscapes.escapedTerm, bytesMarker)
}
// encodeBytesAscendingWithTerminatorAndPrefix encodes the []byte value using an escape-based
// encoding. The encoded value is terminated with the sequence
// "\x00\terminator". The encoded bytes are append to the supplied buffer
// and the resulting buffer is returned. The terminator allows us to pass
// different terminators for things such as JSON key encoding.
func encodeBytesAscendingWithTerminatorAndPrefix(
b []byte, data []byte, terminator byte, prefix byte,
) []byte {
b = append(b, prefix)
return encodeBytesAscendingWithTerminator(b, data, terminator)
}
// encodeBytesAscendingWithTerminator encodes the []byte value using an escape-based
// encoding. The encoded value is terminated with the sequence
// "\x00\terminator". The encoded bytes are append to the supplied buffer
// and the resulting buffer is returned. The terminator allows us to pass
// different terminators for things such as JSON key encoding.
func encodeBytesAscendingWithTerminator(b []byte, data []byte, terminator byte) []byte {
bs := encodeBytesAscendingWithoutTerminatorOrPrefix(b, data)
return append(bs, escape, terminator)
}
// encodeBytesAscendingWithoutTerminatorOrPrefix encodes the []byte value using an escape-based
// encoding.
func encodeBytesAscendingWithoutTerminatorOrPrefix(b []byte, data []byte) []byte {
for {
// IndexByte is implemented by the go runtime in assembly and is
// much faster than looping over the bytes in the slice.
i := bytes.IndexByte(data, escape)
if i == -1 {
break
}
b = append(b, data[:i]...)
b = append(b, escape, escaped00)
data = data[i+1:]
}
return append(b, data...)
}
// EncodeBytesDescending encodes the []byte value using an
// escape-based encoding and then inverts (ones complement) the result
// so that it sorts in reverse order, from larger to smaller
// lexicographically.
func EncodeBytesDescending(b []byte, data []byte) []byte {
n := len(b)
b = EncodeBytesAscending(b, data)
b[n] = bytesDescMarker
onesComplement(b[n+1:])
return b
}
// DecodeBytesAscending decodes a []byte value from the input buffer
// which was encoded using EncodeBytesAscending. The decoded bytes
// are appended to r. The remainder of the input buffer and the
// decoded []byte are returned.
func DecodeBytesAscending(b []byte, r []byte) ([]byte, []byte, error) {
return decodeBytesInternal(b, r, ascendingBytesEscapes, true /* expectMarker */, false /* deepCopy */)
}
// DecodeBytesAscendingDeepCopy is the same as DecodeBytesAscending, but the
// decoded []byte will never alias memory of b.
func DecodeBytesAscendingDeepCopy(b []byte, r []byte) ([]byte, []byte, error) {
return decodeBytesInternal(b, r, ascendingBytesEscapes, true /* expectMarker */, true /* deepCopy */)
}
// DecodeBytesDescending decodes a []byte value from the input buffer
// which was encoded using EncodeBytesDescending. The decoded bytes
// are appended to r. The remainder of the input buffer and the
// decoded []byte are returned.
//
// Note that this method internally will always perform a deep copy, so there is
// no need to introduce DecodeBytesDescendingDeepCopy to mirror
// DecodeBytesAscendingDeepCopy.
func DecodeBytesDescending(b []byte, r []byte) ([]byte, []byte, error) {
// Ask for the deep copy to make sure we never get back a sub-slice of `b`,
// since we're going to modify the contents of the slice.
b, r, err := decodeBytesInternal(b, r, descendingBytesEscapes, true /* expectMarker */, true /* deepCopy */)
onesComplement(r)
return b, r, err
}
// decodeBytesInternal decodes an encoded []byte value from b and appends it to
// r. The remainder of b and the decoded []byte are returned. If deepCopy is
// true, then the decoded []byte will be deep copied from b and there will no
// aliasing of the same memory.
func decodeBytesInternal(
b []byte, r []byte, e escapes, expectMarker bool, deepCopy bool,
) ([]byte, []byte, error) {
if expectMarker {
if len(b) == 0 || b[0] != e.marker {
return nil, nil, errors.Errorf("did not find marker %#x in buffer %#x", e.marker, b)
}
b = b[1:]
}
for {
i := bytes.IndexByte(b, e.escape)
if i == -1 {
return nil, nil, errors.Errorf("did not find terminator %#x in buffer %#x", e.escape, b)
}
if i+1 >= len(b) {
return nil, nil, errors.Errorf("malformed escape in buffer %#x", b)
}
v := b[i+1]
if v == e.escapedTerm {
if r == nil && !deepCopy {
r = b[:i]
} else {
r = append(r, b[:i]...)
}
return b[i+2:], r, nil
}
if v != e.escaped00 {
return nil, nil, errors.Errorf("unknown escape sequence: %#x %#x", e.escape, v)
}
r = append(r, b[:i]...)
r = append(r, e.escapedFF)
b = b[i+2:]
}
}
// getBytesLength finds the length of a bytes encoding.
func getBytesLength(b []byte, e escapes) (int, error) {
// Skip the tag.
skipped := 1
for {
i := bytes.IndexByte(b[skipped:], e.escape)
if i == -1 {
return 0, errors.Errorf("did not find terminator %#x in buffer %#x", e.escape, b)
}
if i+1 >= len(b) {
return 0, errors.Errorf("malformed escape in buffer %#x", b)
}
skipped += i + escapeLength
if b[skipped-1] == e.escapedTerm {
return skipped, nil
}
}
}
// prettyPrintInvertedIndexKey returns a string representation of the path part of a JSON inverted
// index.
func prettyPrintInvertedIndexKey(b []byte) (string, []byte, error) {
outBytes := ""
// We're skipping the first byte because it's the JSON tag.
tempB := b[1:]
for {
i := bytes.IndexByte(tempB, escape)
if i == -1 {
return "", nil, errors.Errorf("did not find terminator %#x in buffer %#x", escape, b)
}
if i+1 >= len(tempB) {
return "", nil, errors.Errorf("malformed escape in buffer %#x", b)
}
switch tempB[i+1] {
case escapedTerm:
if len(tempB[:i]) > 0 {
outBytes = outBytes + strconv.Quote(unsafeString(tempB[:i]))
} else {
lenOut := len(outBytes)
if lenOut > 1 && outBytes[lenOut-1] == '/' {
outBytes = outBytes[:lenOut-1]
}
}
return outBytes, tempB[i+escapeLength:], nil
case escapedJSONObjectKeyTerm:
outBytes = outBytes + strconv.Quote(unsafeString(tempB[:i])) + "/"
case escapedJSONArray:
outBytes = outBytes + "Arr/"
default:
return "", nil, errors.Errorf("malformed escape in buffer %#x", b)
}
tempB = tempB[i+escapeLength:]
}
}
// UnsafeConvertStringToBytes converts a string to a byte array to be used with
// string encoding functions. Note that the output byte array should not be
// modified if the input string is expected to be used again - doing so could
// violate Go semantics.
func UnsafeConvertStringToBytes(s string) []byte {
if len(s) == 0 {
return nil
}
// We unsafely convert the string to a []byte to avoid the
// usual allocation when converting to a []byte. This is
// kosher because we know that EncodeBytes{,Descending} does
// not keep a reference to the value it encodes. The first
// step is getting access to the string internals.
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
// Next we treat the string data as a maximally sized array which we
// slice. This usage is safe because the pointer value remains in the string.
return (*[0x7fffffff]byte)(unsafe.Pointer(hdr.Data))[:len(s):len(s)]
}
// EncodeStringAscending encodes the string value using an escape-based encoding. See
// EncodeBytes for details. The encoded bytes are append to the supplied buffer
// and the resulting buffer is returned.
func EncodeStringAscending(b []byte, s string) []byte {
return encodeStringAscendingWithTerminatorAndPrefix(b, s, ascendingBytesEscapes.escapedTerm, bytesMarker)
}
// encodeStringAscendingWithTerminatorAndPrefix encodes the string value using an escape-based encoding. See
// EncodeBytes for details. The encoded bytes are append to the supplied buffer
// and the resulting buffer is returned. We can also pass a terminator byte to be used with
// JSON key encoding.
func encodeStringAscendingWithTerminatorAndPrefix(
b []byte, s string, terminator byte, prefix byte,
) []byte {
unsafeString := UnsafeConvertStringToBytes(s)
return encodeBytesAscendingWithTerminatorAndPrefix(b, unsafeString, terminator, prefix)
}
// EncodeJSONKeyStringAscending encodes the JSON key string value with a JSON specific escaped
// terminator. This allows us to encode keys in the same number of bytes as a string,
// while at the same time giving us a sentinel to identify JSON keys. The end parameter is used
// to determine if this is the last key in a a JSON path. If it is we don't add a separator after it.
func EncodeJSONKeyStringAscending(b []byte, s string, end bool) []byte {
str := UnsafeConvertStringToBytes(s)
if end {
return encodeBytesAscendingWithoutTerminatorOrPrefix(b, str)
}
return encodeBytesAscendingWithTerminator(b, str, escapedJSONObjectKeyTerm)
}
// EncodeJSONEmptyArray returns a byte array b with a byte to signify an empty JSON array.
func EncodeJSONEmptyArray(b []byte) []byte {
return append(b, escape, escapedTerm, jsonEmptyArray)
}
// AddJSONPathTerminator adds a json path terminator to a byte array.
func AddJSONPathTerminator(b []byte) []byte {
return append(b, escape, escapedTerm)
}
// AddJSONPathSeparator adds a json path separator to a byte array.
func AddJSONPathSeparator(b []byte) []byte {
return append(b, escape, escapedJSONObjectKeyTerm)
}
// EncodeJSONEmptyObject returns a byte array b with a byte to signify an empty JSON object.
func EncodeJSONEmptyObject(b []byte) []byte {
return append(b, escape, escapedTerm, jsonEmptyObject)
}
// EncodeEmptyArray returns a byte array b with a byte to signify an empty array.
func EncodeEmptyArray(b []byte) []byte {
return append(b, emptyArray)
}
// EncodeStringDescending is the descending version of EncodeStringAscending.
func EncodeStringDescending(b []byte, s string) []byte {
if len(s) == 0 {
return EncodeBytesDescending(b, nil)
}
// We unsafely convert the string to a []byte to avoid the
// usual allocation when converting to a []byte. This is
// kosher because we know that EncodeBytes{,Descending} does
// not keep a reference to the value it encodes. The first
// step is getting access to the string internals.
hdr := (*reflect.StringHeader)(unsafe.Pointer(&s))
// Next we treat the string data as a maximally sized array which we
// slice. This usage is safe because the pointer value remains in the string.
arg := (*[0x7fffffff]byte)(unsafe.Pointer(hdr.Data))[:len(s):len(s)]
return EncodeBytesDescending(b, arg)
}
// unsafeString performs an unsafe conversion from a []byte to a string. The
// returned string will share the underlying memory with the []byte which thus
// allows the string to be mutable through the []byte. We're careful to use
// this method only in situations in which the []byte will not be modified.
func unsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// DecodeUnsafeStringAscending decodes a string value from the input buffer which was
// encoded using EncodeString or EncodeBytes. The r []byte is used as a
// temporary buffer in order to avoid memory allocations. The remainder of the
// input buffer and the decoded string are returned. Note that the returned
// string may share storage with the input buffer.
func DecodeUnsafeStringAscending(b []byte, r []byte) ([]byte, string, error) {
b, r, err := DecodeBytesAscending(b, r)
return b, unsafeString(r), err
}
// DecodeUnsafeStringAscendingDeepCopy is the same as
// DecodeUnsafeStringAscending but the returned string will never share storage
// with the input buffer.
func DecodeUnsafeStringAscendingDeepCopy(b []byte, r []byte) ([]byte, string, error) {
b, r, err := DecodeBytesAscendingDeepCopy(b, r)
return b, unsafeString(r), err
}
// DecodeUnsafeStringDescending decodes a string value from the input buffer which
// was encoded using EncodeStringDescending or EncodeBytesDescending. The r
// []byte is used as a temporary buffer in order to avoid memory
// allocations. The remainder of the input buffer and the decoded string are
// returned. Note that the returned string may share storage with the input
// buffer.
func DecodeUnsafeStringDescending(b []byte, r []byte) ([]byte, string, error) {
b, r, err := DecodeBytesDescending(b, r)
return b, unsafeString(r), err
}
// EncodeNullAscending encodes a NULL value. The encodes bytes are appended to the
// supplied buffer and the final buffer is returned. The encoded value for a
// NULL is guaranteed to not be a prefix for the EncodeVarint, EncodeFloat,
// EncodeBytes and EncodeString encodings.
func EncodeNullAscending(b []byte) []byte {
return append(b, encodedNull)
}
// EncodeJSONAscending encodes a JSON Type. The encoded bytes are appended to the
// supplied buffer and the final buffer is returned.
func EncodeJSONAscending(b []byte) []byte {
return append(b, jsonInvertedIndex)
}
// Geo inverted keys are formatted as:
// geoInvertedIndexMarker + EncodeUvarintAscending(cellid) + encoded-bbox
// We don't have a single function to do the whole encoding since a shape is typically
// indexed under multiple cellids, but has a single bbox. So the caller can more
// efficiently
// - append geoInvertedIndex to construct the prefix.
// - encode the bbox once
// - iterate over the cellids and append the encoded cellid to the prefix and then the
// previously encoded bbox.
// EncodeGeoInvertedAscending appends the geoInvertedIndexMarker.
func EncodeGeoInvertedAscending(b []byte) []byte {
return append(b, geoInvertedIndexMarker)
}
// Currently only the lowest bit is used to define the encoding kind and the
// remaining 7 bits are unused.
type geoInvertedBBoxEncodingKind byte
const (
geoInvertedFourFloats geoInvertedBBoxEncodingKind = iota
geoInvertedTwoFloats
)
// MaxGeoInvertedBBoxLen is the maximum length of the encoded bounding box for
// geo inverted keys.
const MaxGeoInvertedBBoxLen = 1 + 4*uint64AscendingEncodedLength
// EncodeGeoInvertedBBox encodes the bounding box for the geo inverted index.
func EncodeGeoInvertedBBox(b []byte, loX, loY, hiX, hiY float64) []byte {
encodeTwoFloats := loX == hiX && loY == hiY
if encodeTwoFloats {
b = append(b, byte(geoInvertedTwoFloats))
b = EncodeUntaggedFloatValue(b, loX)
b = EncodeUntaggedFloatValue(b, loY)
} else {
b = append(b, byte(geoInvertedFourFloats))
b = EncodeUntaggedFloatValue(b, loX)
b = EncodeUntaggedFloatValue(b, loY)
b = EncodeUntaggedFloatValue(b, hiX)
b = EncodeUntaggedFloatValue(b, hiY)
}
return b
}
// DecodeGeoInvertedKey decodes the bounding box from the geo inverted key.
// The cellid is skipped in the decoding.
func DecodeGeoInvertedKey(b []byte) (loX, loY, hiX, hiY float64, remaining []byte, err error) {
// Minimum: 1 byte marker + 1 byte cell length +
// 1 byte bbox encoding kind + 16 bytes for 2 floats
if len(b) < 3+2*uint64AscendingEncodedLength {
return 0, 0, 0, 0, b,
errors.Errorf("inverted key length %d too small", len(b))
}
if b[0] != geoInvertedIndexMarker {
return 0, 0, 0, 0, b, errors.Errorf("marker is not geoInvertedIndexMarker")
}
b = b[1:]
var cellLen int
if cellLen, err = getVarintLen(b); err != nil {
return 0, 0, 0, 0, b, err
}
if len(b) < cellLen+17 {
return 0, 0, 0, 0, b,
errors.Errorf("insufficient length for encoded bbox in inverted key: %d", len(b)-cellLen)
}
encodingKind := geoInvertedBBoxEncodingKind(b[cellLen])
if encodingKind != geoInvertedTwoFloats && encodingKind != geoInvertedFourFloats {
return 0, 0, 0, 0, b,
errors.Errorf("unknown encoding kind for bbox in inverted key: %d", encodingKind)
}
b = b[cellLen+1:]
if b, loX, err = DecodeUntaggedFloatValue(b); err != nil {
return 0, 0, 0, 0, b, err
}
if b, loY, err = DecodeUntaggedFloatValue(b); err != nil {
return 0, 0, 0, 0, b, err
}
if encodingKind == geoInvertedFourFloats {
if b, hiX, err = DecodeUntaggedFloatValue(b); err != nil {
return 0, 0, 0, 0, b, err
}
if b, hiY, err = DecodeUntaggedFloatValue(b); err != nil {
return 0, 0, 0, 0, b, err
}
} else {
hiX = loX
hiY = loY
}
return loX, loY, hiX, hiY, b, nil
}
// EncodeNullDescending is the descending equivalent of EncodeNullAscending.
func EncodeNullDescending(b []byte) []byte {