-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathjsonslice.go
1222 lines (1139 loc) · 26.9 KB
/
jsonslice.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jsonslice
/**
JsonSlice 1.1.0
By Michael Gurov, 2018-2021
MIT licenced
Slice a part of a raw json ([]byte) using jsonpath, without unmarshalling the whole thing.
The result is also []byte.
**/
import (
"bytes"
"errors"
"strconv"
"sync"
"github.com/bhmj/xpression"
)
var (
nodePool sync.Pool
errPathEmpty,
errPathInvalidChar,
errPathRootExpected,
errPathUnexpectedEnd,
errPathUnknownEscape,
errPathUnknownFunction,
errFieldNotFound,
errColonExpected,
errUnrecognizedValue,
errUnexpectedEnd,
errInvalidLengthUsage,
errUnexpectedStringEnd,
errObjectOrArrayExpected error
)
func init() {
nodePool = sync.Pool{
New: func() interface{} {
return &tNode{
Keys: make([]word, 0, 1), // most common case: a single key
Elems: make([]int, 0),
}
},
}
errPathEmpty = errors.New("path: empty")
errPathInvalidChar = errors.New("path: invalid character")
errPathRootExpected = errors.New("path: $ expected")
errPathUnexpectedEnd = errors.New("path: unexpected end of path")
errPathUnknownEscape = errors.New("path: unknown escape")
errPathUnknownFunction = errors.New("path: unknown function")
errFieldNotFound = errors.New(`field not found`)
errColonExpected = errors.New("':' expected")
errUnrecognizedValue = errors.New("unrecognized value: true, false or null expected")
errUnexpectedEnd = errors.New("unexpected end of input")
errInvalidLengthUsage = errors.New("length() is only applicable to array or string")
errObjectOrArrayExpected = errors.New("object or array expected")
errUnexpectedStringEnd = errors.New("unexpected end of string")
}
type word []byte
const (
cDot = 1 << iota // 1 common [dot-]node
cAgg = 1 << iota // 2 aggregating
cFunction = 1 << iota // 4 function
cSlice = 1 << iota // 8 slice array [x:y:s]
cFullScan = 1 << iota // 16 array slice: need fullscan
cFilter = 1 << iota // 32 filter
cWild = 1 << iota // 64 wildcard (*)
cDeep = 1 << iota // 128 deepscan (..)
cEmpty = 1 << 29 // empty number
cNAN = 1 << 30 // not-a-number
)
type tNode struct {
//Key word
Keys []word
Type int // properties
Slice [3]int
Elems []int
Next *tNode
Filter []*xpression.Token
}
func getEmptyNode() *tNode {
nod := nodePool.Get().(*tNode)
nod.Elems = nod.Elems[:0]
nod.Filter = nil
nod.Keys = nod.Keys[:0]
nod.Slice[0] = cEmpty
nod.Slice[1] = cEmpty
nod.Slice[2] = 1
nod.Next = nil
nod.Type = 0
return nod
}
// Get returns a part of input, matching jsonpath.
// In terms of allocations there are two cases of retreiving data from the input:
// 1. simple case: the result is a simple subslice of a source input.
// 2. the result is a merge of several non-contiguous parts of input. More allocations are needed.
func Get(input []byte, path string) ([]byte, error) {
if len(path) == 0 {
return nil, errPathEmpty
}
if len(path) == 1 && path[0] == '$' {
return input, nil
}
if path[0] != '$' {
return nil, errPathRootExpected
}
node, i, err := readRef(unspace([]byte(path)), 1, 0)
if err != nil {
repool(node)
return nil, errors.New(err.Error() + " at " + strconv.Itoa(i))
}
n := node
for {
if n == nil {
break
}
if n.Filter != nil {
for i, tok := range n.Filter {
if tok.Type == xpression.VariableOperand && tok.Operand.Str[0] == '$' {
// every variable has an empty token right after it for storing the result
result := n.Filter[i+1]
// evaluate root-based reference
val, err := Get(input, string(tok.Operand.Str))
if err != nil {
// not found or other error
result.Type = xpression.UndefinedOperand
}
_ = decodeValue(val, &result.Operand)
}
}
}
n = n.Next
}
result, err := getValue(input, node, false)
repool(node)
return result, err
}
// returns true if b matches one of the elements of seq
func bytein(b byte, seq []byte) bool {
for i := 0; i < len(seq); i++ {
if b == seq[i] {
return true
}
}
return false
}
var pathTerminator = []byte{' ', '\t', '<', '=', '>', '+', '-', '*', '/', ')', '&', '|', '!', '^'}
var keyTerminator = []byte{' ', '\t', ':', '.', ',', '[', '(', ')', ']', '<', '=', '>', '+', '-', '*', '/', '&', '|', '!'}
// readRef recursively reads input path until EOL or path terminator encountered.
// Returns single-linked list of nodes, end position or error.
func readRef(path []byte, i int, uptype int) (*tNode, int, error) {
var err error
var next *tNode
var sep byte
var flags int
var key word
if i >= len(path) {
// EOL encountered
return nil, i, nil
}
if bytein(path[i], pathTerminator) {
// path terminator encountered
return nil, i, nil
}
if !bytein(path[i], []byte{'.', '['}) {
// only dot and bracket notation allowed
return nil, i, errPathInvalidChar
}
nod := getEmptyNode()
l := len(path)
// [optional] dots
if path[i] == '.' {
nod.Type = cDot // simple dor notation
if i+1 < l && path[i+1] == '.' {
nod.Type = cDeep // .. means deepscan
i++
}
i++
if i == l {
return nil, i, errPathUnexpectedEnd // need key after dot(s)
}
}
// NOTE: this sequence of blocks supports .[] notation. Maybe should restrict that?
if path[i] == '[' {
// bracket notated
i++
i, err = readBrackets(nod, path, i)
if i == l || err != nil {
return nod, i, err
}
} else {
// dot (or deepscan) notated
key, nod.Slice[0], sep, i, flags, _ = readKey(path, i)
if len(key) > 0 {
nod.Keys = append(nod.Keys, key)
}
nod.Type |= flags // cWild, cFullScan
if i == l {
return nod, i, nil
}
// function
if sep == '(' && i+1 < l && path[i+1] == ')' {
_, i, err = detectFn(path, i, nod)
return nod, i, err
}
}
// recurse
next, i, err = readRef(path, i, nod.Type)
nod.Next = next
return nod, i, err
}
// readBrackets read bracket-notated expression.
//
// consumes final ']'
func readBrackets(nod *tNode, path []byte, i int) (int, error) {
var (
key []byte
ikey int
sep byte
err error
flags int
)
l := len(path)
if i < l-1 && path[i] == '?' && path[i+1] == '(' {
// ?(...): filter
return readFilter(path, i+2, nod)
}
for pos := 0; i < l && path[i] != ']'; pos++ {
key, ikey, sep, i, flags, err = readKey(path, i)
nod.Type |= flags // cWild, cFullScan // CAUTION: [*,1,2] is possible
if err != nil {
return i, err
}
err = setupNode(nod, key, ikey, sep, pos)
if err != nil {
return i, err
}
if nod.Type&(cSlice|cAgg) == cSlice|cAgg {
return i, errPathInvalidChar
}
if sep == ':' || sep == ',' {
i++
}
}
if i == l {
return i, errPathUnexpectedEnd
}
if nod.Type&cSlice > 0 && nod.Slice[0]+nod.Slice[1]+nod.Slice[2] == 2*cEmpty+1 {
nod.Type |= cWild
}
if len(nod.Elems) > 0 {
nod.Type &^= cWild
}
i++ // ']'
return i, nil
}
// readKey reads next key from path[i].
// Key must be any of the following: quoted string, word bounded by keyTerminator, *, 123
// returns:
//
// key = the key
// ikey = integer converted key
// sep = key list separator (expected , : [ ] . +-*/=! 0)
// i = current i (on separator)
// flags = cWild if wildcard
// err = error
func readKey(path []byte, i int) ([]byte, int, byte, int, int, error) {
l := len(path)
var bound byte
var key []byte
var err error
var flag int
if i == l {
return nil, 0, 0, i, 0, errPathUnexpectedEnd
}
if bytein(path[i], []byte{'\'', '"'}) {
// quoted string
key, i, err = readQuotedKey(path, i)
} else {
// terminator bounded string
key, i, err = readTerminatorBounded(path, i, keyTerminator)
if len(key) == 1 && key[0] == '*' {
flag = cWild
key = key[:0]
}
}
if err != nil {
return nil, 0, 0, i, 0, err
}
if i < l {
bound = path[i]
} else {
bound = 0
}
ikey := toInt(key)
if ikey < 0 || ikey == cEmpty {
flag |= cFullScan // fullscan if $[-1], $[1,-1] or $[1:-1] or $[1:]
}
return key, ikey, bound, i, flag, nil
}
// setupNode sets up node Type and either (appens Keys or Elems) or (fills up Slice) depending on note Type
func setupNode(nod *tNode, key []byte, ikey int, sep byte, pos int) error {
switch sep {
case ']':
// end of key list
case ',':
nod.Type |= cAgg | cDot // cDot to extract values
case ':':
nod.Type |= cSlice
case 0:
return errPathUnexpectedEnd
default:
return errPathInvalidChar
}
if nod.Type&cAgg > 0 {
nod.Keys = append(nod.Keys, key)
if ikey != cNAN && ikey != cEmpty {
nod.Elems = append(nod.Elems, ikey)
}
return nil
}
if nod.Type&cSlice > 0 {
if ikey == cNAN || pos > 2 {
return errPathInvalidChar
}
if pos == 2 {
if ikey == cEmpty || ikey == 0 {
ikey = 1
}
if ikey != 1 {
nod.Type |= cFullScan
}
}
nod.Slice[pos] = ikey
return nil
}
// cDot
if len(key) > 0 {
nod.Keys = append(nod.Keys, key)
}
nod.Slice[0] = ikey
nod.Type |= cDot
return nil
}
func detectFn(path []byte, i int, nod *tNode) (bool, int, error) {
if len(nod.Keys) == 0 {
return true, i, errPathUnknownFunction
}
if !(bytes.EqualFold(nod.Keys[0], []byte("length")) ||
bytes.EqualFold(nod.Keys[0], []byte("count")) ||
bytes.EqualFold(nod.Keys[0], []byte("size"))) {
return true, i, errPathUnknownFunction
}
nod.Type |= cFunction
nod.Type &^= cDot
return true, i + 2, nil
}
// getValue returns value specified by nod or nil if no match
// 'inside' specifies recursive mode
func getValue(input []byte, nod *tNode, inside bool) (result []byte, err error) {
if len(input) == 0 {
return nil, nil
}
if nod == nil {
e, err := skipValue(input, 0)
if !inside {
return input[:e], err
}
return input[:e:e], err
}
i, _ := skipSpaces(input, 0) // we're at the value
input = input[i:]
agg := nod.Type&(cAgg|cSlice|cDeep|cWild|cFilter) > 0
switch {
case nod.Type&(cDot|cDeep) > 0: // single or multiple key
result, err = getValueDot(input, nod, agg || inside) // recurse inside
case nod.Type&cSlice > 0: // array slice [::]
result, err = getValueSlice(input, nod) // recurse inside
case nod.Type&cFunction > 0: // func()
result, err = doFunc(input, nod) // no recurse
case nod.Type&cFilter > 0: // [?(...)]
result, err = getValueFilter(input, nod, agg || inside) // no recurse
default:
return nil, errFieldNotFound
}
if agg && !inside {
result = append(append([]byte{'['}, result...), byte(']'))
}
return result, err
}
// $.foo, $['foo','bar'], $[1], $[1,2]
func getValueDot(input []byte, nod *tNode, inside bool) (result []byte, err error) {
if len(input) == 0 {
return
}
switch input[0] {
case '{':
return objectValueByKey(input, nod, inside) // 1+ (recurse inside) (+deep)
case '[':
return arrayElemByIndex(input, nod, inside) // 1+ (recurse inside)
default:
return nil, nil
}
}
// $[1:3], $[1:7:2]
// $..[1:3], $..[1:7:2]
func getValueSlice(input []byte, nod *tNode) (result []byte, err error) {
if len(input) == 0 {
return
}
switch input[0] {
case '{':
if nod.Type&cDeep > 0 {
return objectDeep(input, nod) // (recurse inside) (+deep)
}
return
case '[':
return arraySlice(input, nod) // 1+ (recurse inside) (+deep)
default:
return nil, nil
}
}
func getValueFilter(input []byte, nod *tNode, inside bool) ([]byte, error) {
if len(input) == 0 {
return nil, errUnexpectedEnd
}
switch input[0] {
case '{':
if nod.Type&cDeep > 0 {
return objectDeep(input, nod) // (recurse inside) (+deep)
}
return nil, nil
case '[':
return arrayElemByFilter(input, nod, true) // 1+ (recurse inside)
default:
return nil, errObjectOrArrayExpected
}
}
// TODO: deep
func arrayElemByFilter(input []byte, nod *tNode, inside bool) (result []byte, err error) {
var s, e int
var b bool
var sub []byte
i := 1 // skip '['
l := len(input)
for i < l && input[i] != ']' {
s, e, i, err = valuate(input, i)
if err != nil {
return nil, err
}
b, err = filterMatch(input[s:e], nod.Filter)
if err != nil {
return nil, err
}
if b {
sub, err = getValue(input[s:e], nod.Next, inside) // recurse
if len(sub) > 0 {
result = plus(result, sub)
}
}
}
return result, err
}
// ***
func objectValueByKey(input []byte, nod *tNode, inside bool) ([]byte, error) {
var (
err error
key []byte
)
i := 1 // skip '{'
l := len(input)
var res []byte
var elems [][]byte
if len(nod.Keys) > 1 || nod.Type&cDeep > 0 {
elems = make([][]byte, len(nod.Keys))
}
for i < l && input[i] != '}' {
key, i, err = readObjectKey(input, i)
if err != nil {
return nil, err
}
elems, res, i, err = keyCheck(key, input, i, nod, elems, res, inside)
if err != nil {
return nil, err
}
if nod.Type&cDot > 0 && len(res) > 0 && nod.Type&cDeep == 0 {
return res, nil
}
}
if i == l {
return nil, errUnexpectedEnd
}
for i := 0; i < len(elems); i++ {
if elems[i] != nil {
res = plus(res, elems[i])
}
}
return res, nil
}
func objectDeep(input []byte, nod *tNode) ([]byte, error) {
var (
err error
s, e int
deep []byte
)
i := 1 // skip '{'
l := len(input)
var res []byte
for i < l && input[i] != '}' {
_, i, err = readObjectKey(input, i)
if err != nil {
return nil, err
}
s, e, i, err = valuate(input, i) // s:e holds a value
if err != nil {
return nil, err
}
deep, err = getValue(input[s:e], nod, true) // recurse
if err != nil {
return nil, err
}
if len(deep) > 0 {
res = plus(res, deep)
}
}
if i == l {
return nil, errUnexpectedEnd
}
return res, nil
}
// [x]
// seek to key
// read key
// seek to value
//
// return key, i
func readObjectKey(input []byte, i int) ([]byte, int, error) {
l := len(input)
for input[i] != '"' {
i++
if i == l {
return nil, i, errUnexpectedEnd
}
if input[i] == '}' {
return nil, i, nil
}
}
key, i, err := readQuotedKey(input, i)
if err != nil {
return nil, i, err
}
i, err = seekToValue(input, i)
if err != nil {
return nil, i, err
}
return key, i, nil
}
// get array element(s) by index
//
// $[3] or $[-3] or $[1,2,-3]
// $..[3] or $..[1,2,-3]
//
// recurse inside
func arrayElemByIndex(input []byte, nod *tNode, inside bool) ([]byte, error) {
var res []byte
elems, elem, err := arrayIterateElems(input, nod)
if err != nil {
return nil, err
}
if len(nod.Elems) == 0 && nod.Slice[0] < 0 { // $[-3]
i := len(elems) + nod.Slice[0]
if i >= 0 && i < len(elems) {
elem = input[elems[i].start:elems[i].end]
}
}
if elem != nil { // $[3] or $[-3]
res, err = getValue(elem, nod.Next, inside) // next node
if err != nil || nod.Type&cDeep == 0 {
return res, err
}
}
// $[1,...] or $..[1,...]
return collectRecurse(input, nod, elems, res, inside) // process elems + deepscan inside
}
// get array slice
//
// $[:3] or $[1:5:2] or $[:]
// $..[1:5] or $..[5:1:-1]
//
// recurse inside
func arraySlice(input []byte, nod *tNode) ([]byte, error) {
elems, _, err := arrayIterateElems(input, nod)
if err != nil {
return nil, err
}
if len(elems) > 0 && nod.Type&cFullScan == 0 && nod.Next == nil {
// 5.1)
return input[elems[0].start:elems[len(elems)-1].end], nil
}
return sliceRecurse(input, nod, elems)
}
// iterate over array elements
//
// cases
// 1) $[2] cDot: nod.Left (>0) --> seek to elem
// 2) $[2,3] cDot: nod.Elems (>0) --> scan collecting elems
// 3) $[-3] cDot: nod.Left (<0) --> full scan (cFullScan)
// 4) $[2,-3] cDot: nod.Elems (<0) --> full scan (cFullScan)
// 5) $[1:3] cSlice: Left < Right --> scan up to right --> elems
// 5.1) terminal: return input[left:right]
// 5.2) non-term: iterate and recurse
// 6) ..... cSlice: other --> full scan (cFullScan), apply bounds & recurse
// 7) cWild, cDeep: --> full scan (cFullScan), apply bounds & recurse
//
// returns
//
// elem - for a single index or cDeep
// elems - for a list of indexes or cDeep
func arrayIterateElems(input []byte, nod *tNode) (elems []tElem, elem []byte, err error) {
var i, s, e int
l := len(input)
i = 1 // skip '['
BFOR:
for pos := 0; i < l && input[i] != ']'; pos++ {
s, e, i, err = valuate(input, i)
if err != nil {
return
}
found := nod.Type&(cFullScan|cWild|cDeep) > 0 // 3) 4) 6?) 7)
for f := 0; !found && f < len(nod.Elems); f++ {
if nod.Elems[f] == pos { // 2)
found = true
}
}
if nod.Slice[2] == 1 {
switch nod.Type & (cDot | cSlice | cFullScan | cWild) {
case cSlice: // 5)
found = pos >= nod.Slice[0]
if pos >= nod.Slice[1] {
break BFOR
}
case cDot:
if nod.Slice[0] == pos { // 1)
elem = input[s:e]
if nod.Type&cDeep == 0 {
break BFOR // found single
}
}
}
}
if found {
elems = append(elems, tElem{s, e})
if nod.Type&cFullScan == 0 && len(elems) == len(nod.Elems) {
break // $[1,2,3] --> found them all
}
}
}
return
}
// aggregate non-empty elems and possibly non-empty ret
func collectRecurse(input []byte, nod *tNode, elems []tElem, res []byte, inside bool) ([]byte, error) {
var err error
if nod.Type&cFullScan == 0 || nod.Type&cWild > 0 {
// special case 2): elems already listed
for i := 0; i < len(elems); i++ {
//if nod.Type&cWild > 0 {
// res = plus(res, input[elems[i].start:elems[i].end]) // wild
//}
res, err = subSlice(input, nod, elems, i, res, inside) // recurse + deep
if err != nil {
return res, err
}
}
return res, err
}
// collect & recurse (cFullScan)
for i := 0; i < len(nod.Elems); i++ {
e := nod.Elems[i]
if e < 0 {
e += len(elems)
}
if e >= 0 && e < len(elems) {
res, err = subSlice(input, nod, elems, e, res, inside) // recurse + deep
if err != nil {
return res, err
}
}
}
return res, err
}
// slice requested elements
//
// recurse on each element
//
// deepscan on each element if needed
func sliceRecurse(input []byte, nod *tNode, elems []tElem) ([]byte, error) {
var res []byte
var err error
a, b, step, err := adjustBounds(nod.Slice[0], nod.Slice[1], nod.Slice[2], len(elems))
if err != nil {
return nil, err
}
if nod.Type&cWild > 0 {
a, b, step = 0, len(elems), 1
}
if nod.Type&(cFullScan|cDeep|cWild) > 0 {
for ; (a > b && step < 0) || (a < b && step > 0); a += step {
res, err = subSlice(input, nod, elems, a, res, false) // TODO: make option to switch this to TRUE (nested aggregation)
if err != nil {
return nil, err
}
}
} else {
// 5.2) special case: elems already filtered
for i := 0; i < len(elems); i++ {
res, err = subSlice(input, nod, elems, i, res, false) // TODO: make option to switch this to TRUE (nested aggregation)
if err != nil {
return nil, err
}
}
}
return res, err
}
func subSlice(input []byte, nod *tNode, elems []tElem, i int, res []byte, inside bool) ([]byte, error) {
var sub []byte
var err error
if nod.Type&(cWild|cDeep) != cDeep {
sub, err = getValue(input[elems[i].start:elems[i].end], nod.Next, inside)
if err != nil {
return nil, err
}
if len(sub) > 0 {
res = plus(res, sub)
}
}
if nod.Type&cDeep > 0 {
sub, _ = getValue(input[elems[i].start:elems[i].end], nod, true) // deepscan
if len(sub) > 0 {
res = plus(res, sub)
}
}
return res, nil
}
// Check for key match (or wildscan)
// "key" has been found earlier in input json
// If match then get value, if not match then skip value
// return "res" with a value and "i" pointing after the value
func keyCheck(key []byte, input []byte, i int, nod *tNode, elems [][]byte, res []byte, inside bool) ([][]byte, []byte, int, error) {
var err error
i, err = skipSpaces(input, i)
if err != nil {
return elems, res, i, err
}
b := i
if nod.Type&cWild > 0 {
elems, res, i, err = processKey(nod, nil, key, input, i, elems, res, false) // TODO: make option to switch the last FALSE to "inside" (nested aggregation)
} else {
for ii := range nod.Keys {
elems, res, i, err = processKey(nod, nod.Keys[ii], key, input, i, elems, res, false) // TODO: make option to switch the last FALSE to "inside" (nested aggregation)
}
}
if nod.Type&cDot > 0 && len(res) > 0 {
return elems, res, i, err
}
if b == i {
i, err = skipValue(input, i)
if err != nil {
return elems, res, i, err
}
}
i, err = skipSpaces(input, i)
return elems, res, i, err
}
func processKey(
nod *tNode,
nodkey []byte,
key []byte,
input []byte,
i int,
elems [][]byte,
res []byte,
inside bool,
) ([][]byte, []byte, int, error) {
var err error
var deep []byte
var sub []byte
e := i
match := matchKeys(key, nodkey) || nod.Type&cWild > 0
if nod.Type&cDeep > 0 || match {
// key match
if nod.Type&cDeep == 0 { // $.a $.a.x $[a,b] $.*
if len(nod.Keys) == 1 {
// $.a $.a.x
res, err = getValue(input[i:], nod.Next, inside || nod.Type&cWild > 0) // recurse
return elems, res, i, err
}
// $[a,b] $[a,b].x $.*
e, err = skipValue(input, i)
if err != nil {
return elems, res, i, err
}
sub, err = getValue(input[i:e], nod.Next, inside || nod.Type&cWild > 0)
if len(sub) > 0 {
elems = append(elems, sub)
}
} else { // deep: $..a $..[a,b]
/*
if len(nod.Keys) == 1 {
// $.a $.a.x
res, err = getValue(input[i:], nod.Next, inside || nod.Type&cWild > 0) // recurse
return elems, res, i, err
}
// $[a,b] $[a,b].x $.*
e, err = skipValue(input, i)
if err != nil {
return elems, res, i, err
}
sub, err = getValue(input[i:e], nod.Next, inside || nod.Type&cWild > 0)
if len(sub) > 0 {
elems = append(elems, sub)
}
*/
e, err = skipValue(input, i)
if err != nil {
return elems, res, i, err
}
if match {
sub, _ = getValue(input[i:e:e], nod.Next, inside || nod.Type&cWild > 0)
if len(sub) > 0 {
res = plus(res, sub)
}
}
deep, err = getValue(input[i:e:e], nod, true) // deepscan
if err != nil {
return elems, res, i, err
}
if len(deep) > 0 {
res = plus(res, deep)
}
e, err = skipSpaces(input, e)
}
}
return elems, res, e, err
}
func matchKeys(key []byte, nodkey []byte) bool {
a, b := 0, 0
la, lb := len(key), len(nodkey)
for a < la && b < lb {
ch := key[a]
if ch != nodkey[b] {
return false
}
a++
b++
}
return a == la && b == lb
}
// get current value from input
// returns
//
// s = start of value
// e = end of value
// i = next item
func valuate(input []byte, i int) (int, int, int, error) {
var err error
var s int
s, err = skipSpaces(input, i)
if err != nil {
return 0, 0, i, err
}
e, err := skipValue(input, s) // s:e holds a value
if err != nil {
return s, e, i, err
}
i, err = skipSpaces(input, e)
return s, e, i, err
}
func plus(res []byte, val []byte) []byte {
if len(val) == 0 {
return res
}
if len(res) > 0 {
res = append(res[:len(res):len(res)], ',')
}
return append(res[:len(res):len(res)], val...)
}
type tElem struct {
start int
end int
}
// always moving from start to end;
// step sets the direction;
// start bound always included;
// non-empty end bound always excluded;
//
// empty bound rules:
//
// positive step:
// empty start = 0
// empty end = last item (included)
// negative step:
// empty start = last item
// empty end = first item (included)
func adjustBounds(start int, stop int, step int, n int) (int, int, int, error) {
if n == 0 {
return 0, 0, 0, nil
}
if step == 0 || step == cEmpty {
step = 1
}
if start == cEmpty {
if step > 0 {
start = 0
} else {
start = n - 1
}
}
if stop < 0 {
stop += n
}
if stop < 0 {
stop = -1
}
if stop == cEmpty {
if step > 0 {
stop = n
} else {
stop = -1
}
}
if start < 0 {
start += n
}