-
Notifications
You must be signed in to change notification settings - Fork 89
/
parsed_json.go
1272 lines (1166 loc) · 31.3 KB
/
parsed_json.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
/*
* MinIO Cloud Storage, (C) 2020 MinIO, Inc.
*
* 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 simdjson
import (
"errors"
"fmt"
"math"
"strconv"
)
const JSONVALUEMASK = 0xff_ffff_ffff_ffff
const JSONTAGOFFSET = 56
const JSONTAGMASK = 0xff << JSONTAGOFFSET
const STRINGBUFBIT = 0x80_0000_0000_0000
const STRINGBUFMASK = 0x7fffffffffffff
const maxdepth = 128
// FloatFlags are flags recorded when converting floats.
type FloatFlags uint64
// FloatFlag is a flag recorded when parsing floats.
type FloatFlag uint64
const (
// FloatOverflowedInteger is set when number in JSON was in integer notation,
// but under/overflowed both int64 and uint64 and therefore was parsed as float.
FloatOverflowedInteger FloatFlag = 1 << iota
)
// Contains returns whether f contains the specified flag.
func (f FloatFlags) Contains(flag FloatFlag) bool {
return FloatFlag(f)&flag == flag
}
// Flags converts the flag to FloatFlags and optionally merges more flags.
func (f FloatFlag) Flags(more ...FloatFlag) FloatFlags {
// We operate on a copy, so we can modify f.
for _, v := range more {
f |= v
}
return FloatFlags(f)
}
type TStrings struct {
B []byte
}
type ParsedJson struct {
Message []byte
Tape []uint64
Strings *TStrings
// allows to reuse the internal structures without exposing it.
internal *internalParsedJson
}
const indexSlots = 16
const indexSize = 1536 // Seems to be a good size for the index buffering
const indexSizeWithSafetyBuffer = indexSize - 128 // Make sure we never write beyond buffer
type indexChan struct {
index int
length int
indexes *[indexSize]uint32
}
type internalParsedJson struct {
ParsedJson
containingScopeOffset []uint64
isvalid bool
indexChans chan indexChan
indexesChan indexChan
buffers [indexSlots][indexSize]uint32
buffersOffset uint64
ndjson uint64
copyStrings bool
}
// Iter returns a new Iter.
func (pj *ParsedJson) Iter() Iter {
return Iter{tape: *pj}
}
// stringAt returns a string at a specific offset in the stringbuffer.
func (pj *ParsedJson) stringAt(offset, length uint64) (string, error) {
b, err := pj.stringByteAt(offset, length)
return string(b), err
}
// stringByteAt returns a string at a specific offset in the stringbuffer.
func (pj *ParsedJson) stringByteAt(offset, length uint64) ([]byte, error) {
if offset&STRINGBUFBIT == 0 {
if offset+length > uint64(len(pj.Message)) {
return nil, fmt.Errorf("string message offset (%v) outside valid area (%v)", offset+length, len(pj.Message))
}
return pj.Message[offset : offset+length], nil
}
offset = offset & STRINGBUFMASK
if offset+length > uint64(len(pj.Strings.B)) {
return nil, fmt.Errorf("string buffer offset (%v) outside valid area (%v)", offset+length, len(pj.Strings.B))
}
return pj.Strings.B[offset : offset+length], nil
}
// ForEach returns each line in NDJSON, or the top element in non-ndjson.
// This will usually be an object or an array.
// If the callback returns a non-nil error parsing stops and the errors is returned.
func (pj *ParsedJson) ForEach(fn func(i Iter) error) error {
i := Iter{tape: *pj}
var elem Iter
for {
t, err := i.AdvanceIter(&elem)
if err != nil || t != TypeRoot {
return err
}
elem.AdvanceInto()
if err = fn(elem); err != nil {
return err
}
}
}
// Clone returns a deep clone of the ParsedJson.
// If a nil destination is sent a new will be created.
func (pj *ParsedJson) Clone(dst *ParsedJson) *ParsedJson {
if dst == nil {
dst = &ParsedJson{
Message: make([]byte, len(pj.Message)),
Tape: make([]uint64, len(pj.Tape)),
Strings: &TStrings{make([]byte, len(pj.Strings.B))},
internal: nil,
}
} else {
if cap(dst.Message) < len(pj.Message) {
dst.Message = make([]byte, len(pj.Message))
}
if cap(dst.Tape) < len(pj.Tape) {
dst.Tape = make([]uint64, len(pj.Tape))
}
if dst.Strings == nil {
dst.Strings = &TStrings{make([]byte, len(pj.Strings.B))}
} else if cap(dst.Strings.B) < len(pj.Strings.B) {
dst.Strings.B = make([]byte, len(pj.Strings.B))
}
}
dst.internal = nil
dst.Tape = dst.Tape[:len(pj.Tape)]
copy(dst.Tape, pj.Tape)
dst.Message = dst.Message[:len(pj.Message)]
copy(dst.Message, pj.Message)
dst.Strings.B = dst.Strings.B[:len(pj.Strings.B)]
copy(dst.Strings.B, pj.Strings.B)
return dst
}
// Iter represents a section of JSON.
// To start iterating it, use Advance() or AdvanceIter() methods
// which will queue the first element.
// If an Iter is copied, the copy will be independent.
type Iter struct {
// The tape where this iter start.
tape ParsedJson
// offset of the next entry to be decoded
off int
// addNext is the number of entries to skip for the next entry.
addNext int
// current value, exclude tag in top bits
cur uint64
// current tag
t Tag
}
// Advance will read the type of the next element
// and queues up the value on the same level.
func (i *Iter) Advance() Type {
i.off += i.addNext
for {
if i.off >= len(i.tape.Tape) {
i.addNext = 0
i.t = TagEnd
return TypeNone
}
v := i.tape.Tape[i.off]
i.t = Tag(v >> 56)
i.off++
i.cur = v & JSONVALUEMASK
if i.t == TagNop {
i.off += int(i.cur)
continue
}
break
}
i.calcNext(false)
if i.addNext < 0 {
// We can't send error, so move to end.
i.moveToEnd()
return TypeNone
}
return TagToType[i.t]
}
// AdvanceInto will read the tag of the next element
// and move into and out of arrays , objects and root elements.
// This should only be used for strictly manual parsing.
func (i *Iter) AdvanceInto() Tag {
i.off += i.addNext
for {
if i.off >= len(i.tape.Tape) {
i.addNext = 0
i.t = TagEnd
return TagEnd
}
v := i.tape.Tape[i.off]
i.t = Tag(v >> 56)
i.cur = v & JSONVALUEMASK
if i.t == TagNop {
if i.cur <= 0 {
i.moveToEnd()
return TagEnd
}
i.off += int(i.cur)
continue
}
i.off++
break
}
i.calcNext(true)
if i.addNext < 0 {
// We can't send error, so end tape.
i.moveToEnd()
return TagEnd
}
return i.t
}
func (i *Iter) moveToEnd() {
i.off = len(i.tape.Tape)
i.addNext = 0
i.t = TagEnd
}
// calcNext will populate addNext to the correct value to skip.
// Specify whether to move into objects/array.
func (i *Iter) calcNext(into bool) {
i.addNext = 0
switch i.t {
case TagInteger, TagUint, TagFloat, TagString:
i.addNext = 1
case TagRoot, TagObjectStart, TagArrayStart:
if !into {
i.addNext = int(i.cur) - i.off
}
}
}
// Type returns the queued value type from the previous call to Advance.
func (i *Iter) Type() Type {
if i.off+i.addNext > len(i.tape.Tape) {
return TypeNone
}
return TagToType[i.t]
}
// AdvanceIter will read the type of the next element
// and return an iterator only containing the object.
// If dst and i are the same, both will contain the value inside.
func (i *Iter) AdvanceIter(dst *Iter) (Type, error) {
i.off += i.addNext
// Get current value off tape.
for {
if i.off == len(i.tape.Tape) {
i.addNext = 0
i.t = TagEnd
return TypeNone, nil
}
if i.off > len(i.tape.Tape) {
return TypeNone, errors.New("offset bigger than tape")
}
v := i.tape.Tape[i.off]
i.cur = v & JSONVALUEMASK
i.t = Tag(v >> 56)
i.off++
if i.t == TagNop {
if i.cur <= 0 {
return TypeNone, errors.New("invalid nop skip")
}
i.off += int(i.cur)
continue
}
break
}
i.calcNext(false)
if i.addNext < 0 {
i.moveToEnd()
return TypeNone, errors.New("element has negative offset")
}
// Calculate end of this object.
iEnd := i.off + i.addNext
typ := TagToType[i.t]
// Copy i if different
if i != dst {
*dst = *i
}
// Move into dst
dst.calcNext(true)
if dst.addNext < 0 {
i.moveToEnd()
return TypeNone, errors.New("element has negative offset")
}
if iEnd > len(dst.tape.Tape) {
return TypeNone, errors.New("element extends beyond tape")
}
// Restrict destination.
dst.tape.Tape = dst.tape.Tape[:iEnd]
return typ, nil
}
// PeekNext will return the next value type.
// Returns TypeNone if next ends iterator.
func (i *Iter) PeekNext() Type {
off := i.off + i.addNext
for {
if off >= len(i.tape.Tape) {
return TypeNone
}
v := i.tape.Tape[off]
t := Tag(v >> 56)
if t == TagNop {
skip := int(v & JSONVALUEMASK)
if skip <= 0 {
return TypeNone
}
off += skip
continue
}
return TagToType[t]
}
}
// PeekNextTag will return the tag at the current offset.
// Will return TagEnd if at end of iterator.
func (i *Iter) PeekNextTag() Tag {
off := i.off + i.addNext
for {
if off >= len(i.tape.Tape) {
return TagEnd
}
v := i.tape.Tape[off]
t := Tag(v >> 56)
if t == TagNop {
skip := int(v & JSONVALUEMASK)
if skip <= 0 {
return TagEnd
}
off += skip
continue
}
return t
}
}
// MarshalJSON will marshal the entire remaining scope of the iterator.
func (i *Iter) MarshalJSON() ([]byte, error) {
return i.MarshalJSONBuffer(nil)
}
// MarshalJSONBuffer will marshal the remaining scope of the iterator including the current value.
// An optional buffer can be provided for fewer allocations.
// Output will be appended to the destination.
func (i *Iter) MarshalJSONBuffer(dst []byte) ([]byte, error) {
var tmpBuf []byte
// Pre-allocate for 100 deep.
var stackTmp [100]uint8
// We have a stackNone on top of the stack
stack := stackTmp[:1]
const (
stackNone = iota
stackArray
stackObject
stackRoot
)
writeloop:
for {
// Write key names.
if stack[len(stack)-1] == stackObject && i.t != TagObjectEnd {
sb, err := i.StringBytes()
if err != nil {
return nil, fmt.Errorf("expected key within object: %w", err)
}
dst = append(dst, '"')
dst = escapeBytes(dst, sb)
dst = append(dst, '"', ':')
if i.PeekNextTag() == TagEnd {
return nil, fmt.Errorf("unexpected end of tape within object")
}
i.AdvanceInto()
}
//fmt.Println(i.t, len(stack)-1, i.off)
tagswitch:
switch i.t {
case TagRoot:
isOpenRoot := int(i.cur) > i.off
if len(stack) > 1 {
if isOpenRoot {
return dst, errors.New("root tag open, but not at top of stack")
}
l := stack[len(stack)-1]
switch l {
case stackRoot:
if i.PeekNextTag() != TagEnd {
dst = append(dst, '\n')
}
stack = stack[:len(stack)-1]
break tagswitch
case stackNone:
break writeloop
default:
return dst, errors.New("root tag, but not at top of stack, got id " + strconv.Itoa(int(l)))
}
}
if isOpenRoot {
// Always move into root.
i.addNext = 0
}
i.AdvanceInto()
stack = append(stack, stackRoot)
continue
case TagString:
sb, err := i.StringBytes()
if err != nil {
return nil, err
}
dst = append(dst, '"')
dst = escapeBytes(dst, sb)
dst = append(dst, '"')
tmpBuf = tmpBuf[:0]
case TagInteger:
v, err := i.Int()
if err != nil {
return nil, err
}
dst = strconv.AppendInt(dst, v, 10)
case TagUint:
v, err := i.Uint()
if err != nil {
return nil, err
}
dst = strconv.AppendUint(dst, v, 10)
case TagFloat:
v, err := i.Float()
if err != nil {
return nil, err
}
dst, err = appendFloat(dst, v)
if err != nil {
return nil, err
}
case TagNull:
dst = append(dst, []byte("null")...)
case TagBoolTrue:
dst = append(dst, []byte("true")...)
case TagBoolFalse:
dst = append(dst, []byte("false")...)
case TagObjectStart:
dst = append(dst, '{')
stack = append(stack, stackObject)
// We should not emit commas.
i.AdvanceInto()
continue
case TagObjectEnd:
dst = append(dst, '}')
if stack[len(stack)-1] != stackObject {
return dst, errors.New("end of object with no object on stack")
}
stack = stack[:len(stack)-1]
case TagArrayStart:
dst = append(dst, '[')
stack = append(stack, stackArray)
i.AdvanceInto()
continue
case TagArrayEnd:
dst = append(dst, ']')
if stack[len(stack)-1] != stackArray {
return nil, errors.New("end of array with no array on stack")
}
stack = stack[:len(stack)-1]
case TagEnd:
if i.PeekNextTag() == TagEnd {
return nil, errors.New("no content queued in iterator")
}
i.AdvanceInto()
continue
}
if i.PeekNextTag() == TagEnd {
break
}
i.AdvanceInto()
// Output object separators, etc.
switch stack[len(stack)-1] {
case stackArray:
switch i.t {
case TagArrayEnd:
default:
dst = append(dst, ',')
}
case stackObject:
switch i.t {
case TagObjectEnd:
default:
dst = append(dst, ',')
}
}
}
if len(stack) > 1 {
// Copy so "stack" doesn't escape.
sCopy := append(make([]uint8, 0, len(stack)-1), stack[1:]...)
return nil, fmt.Errorf("objects or arrays not closed. left on stack: %v", sCopy)
}
return dst, nil
}
// Float returns the float value of the next element.
// Integers are automatically converted to float.
func (i *Iter) Float() (float64, error) {
switch i.t {
case TagFloat:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected float, but no more values on tape")
}
v := math.Float64frombits(i.tape.Tape[i.off])
return v, nil
case TagInteger:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := int64(i.tape.Tape[i.off])
return float64(v), nil
case TagUint:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := i.tape.Tape[i.off]
return float64(v), nil
default:
return 0, fmt.Errorf("unable to convert type %v to float", i.t)
}
}
// FloatFlags returns the float value of the next element.
// This will include flags from parsing.
// Integers are automatically converted to float.
func (i *Iter) FloatFlags() (float64, FloatFlags, error) {
switch i.t {
case TagFloat:
if i.off >= len(i.tape.Tape) {
return 0, 0, errors.New("corrupt input: expected float, but no more values on tape")
}
v := math.Float64frombits(i.tape.Tape[i.off])
return v, FloatFlags(i.cur), nil
case TagInteger:
if i.off >= len(i.tape.Tape) {
return 0, 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := int64(i.tape.Tape[i.off])
return float64(v), 0, nil
case TagUint:
if i.off >= len(i.tape.Tape) {
return 0, 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := i.tape.Tape[i.off]
return float64(v), 0, nil
default:
return 0, 0, fmt.Errorf("unable to convert type %v to float", i.t)
}
}
// SetFloat can change a float, int, uint or string with the specified value.
// Attempting to change other types will return an error.
func (i *Iter) SetFloat(v float64) error {
switch i.t {
case TagFloat, TagInteger, TagUint, TagString:
i.tape.Tape[i.off-1] = uint64(TagFloat) << JSONTAGOFFSET
i.tape.Tape[i.off] = math.Float64bits(v)
i.t = TagFloat
i.cur = 0
return nil
}
return fmt.Errorf("cannot set tag %s to float", i.t.String())
}
// Int returns the integer value of the next element.
// Integers and floats within range are automatically converted.
func (i *Iter) Int() (int64, error) {
switch i.t {
case TagFloat:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected float, but no more values on tape")
}
v := math.Float64frombits(i.tape.Tape[i.off])
if v > math.MaxInt64 {
return 0, errors.New("float value overflows int64")
}
if v < math.MinInt64 {
return 0, errors.New("float value underflows int64")
}
return int64(v), nil
case TagInteger:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := int64(i.tape.Tape[i.off])
return v, nil
case TagUint:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := i.tape.Tape[i.off]
if v > math.MaxInt64 {
return 0, errors.New("unsigned integer value overflows int64")
}
return int64(v), nil
default:
return 0, fmt.Errorf("unable to convert type %v to int", i.t)
}
}
// SetInt can change a float, int, uint or string with the specified value.
// Attempting to change other types will return an error.
func (i *Iter) SetInt(v int64) error {
switch i.t {
case TagFloat, TagInteger, TagUint, TagString:
i.tape.Tape[i.off-1] = uint64(TagInteger) << JSONTAGOFFSET
i.tape.Tape[i.off] = uint64(v)
i.t = TagInteger
i.cur = uint64(v)
return nil
}
return fmt.Errorf("cannot set tag %s to int", i.t.String())
}
// Uint returns the unsigned integer value of the next element.
// Positive integers and floats within range are automatically converted.
func (i *Iter) Uint() (uint64, error) {
switch i.t {
case TagFloat:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected float, but no more values on tape")
}
v := math.Float64frombits(i.tape.Tape[i.off])
if v > math.MaxUint64 {
return 0, errors.New("float value overflows uint64")
}
if v < 0 {
return 0, errors.New("float value is negative. cannot convert to uint")
}
return uint64(v), nil
case TagInteger:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := int64(i.tape.Tape[i.off])
if v < 0 {
return 0, errors.New("integer value is negative. cannot convert to uint")
}
return uint64(v), nil
case TagUint:
if i.off >= len(i.tape.Tape) {
return 0, errors.New("corrupt input: expected integer, but no more values on tape")
}
v := i.tape.Tape[i.off]
return v, nil
default:
return 0, fmt.Errorf("unable to convert type %v to uint", i.t)
}
}
// SetUInt can change a float, int, uint or string with the specified value.
// Attempting to change other types will return an error.
func (i *Iter) SetUInt(v uint64) error {
switch i.t {
case TagString, TagFloat, TagInteger, TagUint:
i.tape.Tape[i.off-1] = uint64(TagUint) << JSONTAGOFFSET
i.tape.Tape[i.off] = v
i.t = TagUint
i.cur = v
return nil
}
return fmt.Errorf("cannot set tag %s to uint", i.t.String())
}
// String() returns a string value.
func (i *Iter) String() (string, error) {
if i.t != TagString {
return "", errors.New("value is not string")
}
if i.off >= len(i.tape.Tape) {
return "", errors.New("corrupt input: no string offset")
}
return i.tape.stringAt(i.cur, i.tape.Tape[i.off])
}
// StringBytes returns a string as byte array.
func (i *Iter) StringBytes() ([]byte, error) {
if i.t != TagString {
return nil, errors.New("value is not string")
}
if i.off >= len(i.tape.Tape) {
return nil, errors.New("corrupt input: no string offset on tape")
}
return i.tape.stringByteAt(i.cur, i.tape.Tape[i.off])
}
// SetString can change a string, int, uint or float with the specified string.
// Attempting to change other types will return an error.
func (i *Iter) SetString(v string) error {
return i.SetStringBytes([]byte(v))
}
// SetStringBytes can change a string, int, uint or float with the specified string.
// Attempting to change other types will return an error.
// Sending nil will add an empty string.
func (i *Iter) SetStringBytes(v []byte) error {
switch i.t {
case TagString, TagFloat, TagInteger, TagUint:
i.cur = ((uint64(TagString) << JSONTAGOFFSET) | STRINGBUFBIT) | uint64(len(i.tape.Strings.B))
i.tape.Tape[i.off-1] = i.cur
i.tape.Tape[i.off] = uint64(len(v))
i.t = TagString
i.tape.Strings.B = append(i.tape.Strings.B, v...)
return nil
}
return fmt.Errorf("cannot set tag %s to string", i.t.String())
}
// StringCvt returns a string representation of the value.
// Root, Object and Arrays are not supported.
func (i *Iter) StringCvt() (string, error) {
switch i.t {
case TagString:
return i.String()
case TagInteger:
v, err := i.Int()
return strconv.FormatInt(v, 10), err
case TagUint:
v, err := i.Uint()
return strconv.FormatUint(v, 10), err
case TagFloat:
v, err := i.Float()
if err != nil {
return "", err
}
return floatToString(v)
case TagBoolFalse:
return "false", nil
case TagBoolTrue:
return "true", nil
case TagNull:
return "null", nil
}
return "", fmt.Errorf("cannot convert type %s to string", TagToType[i.t])
}
// Root returns the object embedded in root as an iterator
// along with the type of the content of the first element of the iterator.
// An optional destination can be supplied to avoid allocations.
func (i *Iter) Root(dst *Iter) (Type, *Iter, error) {
if i.t != TagRoot {
return TypeNone, dst, errors.New("value is not root")
}
if i.cur > uint64(len(i.tape.Tape)) {
return TypeNone, dst, errors.New("root element extends beyond tape")
}
if dst == nil {
c := *i
dst = &c
} else {
dst.cur = i.cur
dst.off = i.off
dst.t = i.t
dst.tape.Strings = i.tape.Strings
dst.tape.Message = i.tape.Message
}
dst.addNext = 0
dst.tape.Tape = i.tape.Tape[:i.cur-1]
return dst.AdvanceInto().Type(), dst, nil
}
// FindElement allows searching for fields and objects by path from the iter and forward,
// moving into root and objects, but not arrays.
// For example "Image", "Url" will search the current root/object for an "Image"
// object and return the value of the "Url" element.
// ErrPathNotFound is returned if any part of the path cannot be found.
// If the tape contains an error it will be returned.
// The iter will *not* be advanced.
func (i *Iter) FindElement(dst *Element, path ...string) (*Element, error) {
if len(path) == 0 {
return dst, ErrPathNotFound
}
// Local copy.
cp := *i
for {
switch cp.t {
case TagObjectStart:
var o Object
obj, err := cp.Object(&o)
if err != nil {
return dst, err
}
return obj.FindPath(dst, path...)
case TagRoot:
_, _, err := cp.Root(&cp)
if err != nil {
return dst, err
}
continue
case TagEnd:
tag := cp.AdvanceInto()
if tag == TagEnd {
return dst, ErrPathNotFound
}
continue
default:
return dst, fmt.Errorf("type %q found before object was found", cp.t)
}
}
}
// Bool returns the bool value.
func (i *Iter) Bool() (bool, error) {
switch i.t {
case TagBoolTrue:
return true, nil
case TagBoolFalse:
return false, nil
}
return false, fmt.Errorf("value is not bool, but %v", i.t)
}
// SetBool can change a bool or null type to bool with the specified value.
// Attempting to change other types will return an error.
func (i *Iter) SetBool(v bool) error {
switch i.t {
case TagBoolTrue, TagBoolFalse, TagNull:
if v {
i.t = TagBoolTrue
i.cur = 0
i.tape.Tape[i.off-1] = uint64(TagBoolTrue) << JSONTAGOFFSET
} else {
i.t = TagBoolFalse
i.cur = 0
i.tape.Tape[i.off-1] = uint64(TagBoolFalse) << JSONTAGOFFSET
}
return nil
}
return fmt.Errorf("cannot set tag %s to bool", i.t.String())
}
// SetNull can change the following types to null:
// Bool, String, (Unsigned) Integer, Float, Objects and Arrays.
// Attempting to change other types will return an error.
func (i *Iter) SetNull() error {
switch i.t {
case TagBoolTrue, TagBoolFalse, TagNull:
// 1 value on stream
i.t = TagNull
i.cur = 0
i.tape.Tape[i.off-1] = uint64(TagNull) << JSONTAGOFFSET
case TagString, TagFloat, TagInteger, TagUint:
// 2 values
i.tape.Tape[i.off-1] = uint64(TagNull) << JSONTAGOFFSET
i.tape.Tape[i.off] = uint64(TagNop)<<JSONTAGOFFSET | 1
i.t = TagNull
i.cur = 0
case TagObjectStart, TagArrayStart, TagRoot:
// Read length, skipping the object/array:
i.addNext = int(i.cur) - i.off
i.tape.Tape[i.off-1] = uint64(TagNull) << JSONTAGOFFSET
// Fill with nops
for j := i.off; j < int(i.cur); j++ {
i.tape.Tape[j] = uint64(TagNop)<<JSONTAGOFFSET | (i.cur - uint64(j))
}
i.t = TagNull
i.cur = 0
default:
return fmt.Errorf("cannot set tag %s to null", i.t.String())
}
return nil
}
// Interface returns the value as an interface.
// Objects are returned as map[string]interface{}.
// Arrays are returned as []interface{}.
// Float values are returned as float64.
// Integer values are returned as int64 or uint64.
// String values are returned as string.
// Boolean values are returned as bool.
// Null values are returned as nil.
// Root objects are returned as []interface{}.
func (i *Iter) Interface() (interface{}, error) {
switch i.t.Type() {
case TypeUint:
return i.Uint()
case TypeInt:
return i.Int()
case TypeFloat:
return i.Float()
case TypeNull:
return nil, nil
case TypeArray:
arr, err := i.Array(nil)
if err != nil {
return nil, err
}
return arr.Interface()
case TypeString:
return i.String()
case TypeObject:
obj, err := i.Object(nil)
if err != nil {
return nil, err
}
return obj.Map(nil)
case TypeBool:
return i.t == TagBoolTrue, nil
case TypeRoot:
var dst []interface{}
var tmp Iter
for {
typ, obj, err := i.Root(&tmp)
if err != nil {
return nil, err
}
if typ == TypeNone {
break
}
elem, err := obj.Interface()
if err != nil {
return nil, err
}
dst = append(dst, elem)
typ = i.Advance()
if typ != TypeRoot {
break
}
}
return dst, nil
case TypeNone:
if i.PeekNextTag() == TagEnd {
return nil, errors.New("no content in iterator")
}
i.Advance()
return i.Interface()
default:
}
return nil, fmt.Errorf("unknown tag type: %v", i.t)
}
// Object will return the next element as an object.
// An optional destination can be given.
func (i *Iter) Object(dst *Object) (*Object, error) {
if i.t != TagObjectStart {
return nil, errors.New("next item is not object")