-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbytes.go
More file actions
340 lines (300 loc) · 6.75 KB
/
bytes.go
File metadata and controls
340 lines (300 loc) · 6.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
package json
import (
"fmt"
"sort"
"strconv"
"strings"
)
func arreq(a, b []string) bool {
if len(a) == len(b) {
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
return false
}
func unescape(s string) string {
n := strings.Count(s, "~")
if n == 0 {
return s
}
t := make([]byte, len(s)-n+1) // remove one char per ~
w := 0
start := 0
for i := 0; i < n; i++ {
j := start + strings.Index(s[start:], "~")
w += copy(t[w:], s[start:j])
if len(s) < j+2 {
t[w] = '~'
w++
break
}
c := s[j+1]
switch c {
case '0':
t[w] = '~'
w++
case '1':
t[w] = '/'
w++
default:
t[w] = '~'
w++
t[w] = c
w++
}
start = j + 2
}
w += copy(t[w:], s[start:])
return string(t[0:w])
}
func parsePointer(s string) []string {
a := strings.Split(s[1:], "/")
if !strings.Contains(s, "~") {
return a
}
for i := range a {
if strings.Contains(a[i], "~") {
a[i] = unescape(a[i])
}
}
return a
}
func escape(s string, out []rune) []rune {
for _, c := range s {
switch c {
case '/':
out = append(out, '~', '1')
case '~':
out = append(out, '~', '0')
default:
out = append(out, c)
}
}
return out
}
func encodePointer(p []string) string {
out := make([]rune, 0, 64)
for _, s := range p {
out = append(out, '/')
out = escape(s, out)
}
return string(out)
}
func grokLiteral(b []byte) string {
s, ok := unquoteBytes(b)
if !ok {
panic("could not grok literal " + string(b))
}
return string(s)
}
// FindDecode finds an object by JSONPointer path and then decode the
// result into a user-specified object. Errors if a properly
// formatted JSON document can't be found at the given path.
func FindDecode(data []byte, path string, into interface{}) error {
d, err := Find(data, path)
if err != nil {
return err
}
return Unmarshal(d, into)
}
// Find a section of raw JSON by specifying a JSONPointer.
func Find(data []byte, path string) ([]byte, error) {
var lastLiteral string
var sc scanner
if path == "" {
return data, nil
}
needle := parsePointer(path)
scan := setScanner(&sc, data)
scan.reset()
current := make([]string, 0, 32)
level := -1
for scan.offset < len(scan.data) {
oldOffset := scan.offset
c := data[oldOffset]
scan.offset++
newOp := scan.step(scan, c)
switch newOp {
case scanBeginArray:
level++
current = append(current, "0")
case scanObjectKey:
current[len(current)-1] = lastLiteral
case scanBeginLiteral:
if level >= 0 && scan.parseState[level] == parseObjectKey {
res, err := nextLiteral(scan)
if err != nil {
return nil, err
}
lastLiteral = string(res)
}
case scanArrayValue:
n := mustParseInt(current[len(current)-1])
current[len(current)-1] = strconv.Itoa(n + 1)
case scanEndArray, scanEndObject:
current = sliceToEnd(current)
level--
case scanBeginObject:
level++
current = append(current, "")
case scanContinue, scanSkipSpace, scanObjectValue, scanEnd:
case scanError:
return nil, scan.err
default:
return nil, fmt.Errorf("found unhandled json op: %v", newOp)
}
if (newOp == scanBeginArray || newOp == scanArrayValue ||
newOp == scanObjectKey) && arreq(needle, current) {
otmp := scan.offset
for isSpace(data[otmp]) {
otmp++
}
if data[otmp] == ']' {
// special case an array offset miss
return nil, nil
}
return nextScanValue(scan)
}
}
return nil, nil
}
func sliceToEnd(s []string) []string {
end := len(s) - 1
if end >= 0 {
s = s[:end]
}
return s
}
func mustParseInt(s string) int {
n, err := strconv.Atoi(s)
if err == nil {
return n
}
panic(err)
}
// ListPointers lists all possible pointers from the given input.
func ListPointers(data []byte) ([]string, error) {
var sc scanner
if len(data) == 0 {
return nil, fmt.Errorf("Invalid JSON")
}
rv := []string{""}
scan := setScanner(&sc, data)
scan.reset()
beganLiteral := 0
var current []string
for {
if scan.offset >= len(data) {
return rv, nil
}
oldOffset := scan.offset
c := data[oldOffset]
scan.offset++
newOp := scan.step(scan, c)
switch newOp {
case scanBeginArray:
current = append(current, "0")
case scanObjectKey:
current[len(current)-1] = grokLiteral(data[beganLiteral-1 : oldOffset])
case scanBeginLiteral:
beganLiteral = scan.offset
case scanArrayValue:
n := mustParseInt(current[len(current)-1])
current[len(current)-1] = strconv.Itoa(n + 1)
case scanEndArray, scanEndObject:
current = sliceToEnd(current)
case scanBeginObject:
current = append(current, "")
case scanError:
return nil, fmt.Errorf("Error reading JSON object at offset %v", oldOffset)
}
if newOp == scanBeginArray || newOp == scanArrayValue ||
newOp == scanObjectKey {
rv = append(rv, encodePointer(current))
}
}
}
// FindMany finds several jsonpointers in one pass through the input.
func FindMany(data []byte, paths []string) (map[string][]byte, error) {
var sc1, sc2 scanner
tpaths := make([]string, 0, len(paths))
m := map[string][]byte{}
for _, p := range paths {
if p == "" {
m[p] = data
} else {
tpaths = append(tpaths, p)
}
}
sort.Strings(tpaths)
scan := setScanner(&sc1, data)
scan.reset()
todo := len(tpaths)
beganLiteral := 0
matchedAt := 0
var current []string
for todo > 0 {
if scan.offset >= len(data) {
break
}
oldOffset := scan.offset
c := data[oldOffset]
scan.offset++
newOp := scan.step(scan, c)
switch newOp {
case scanBeginArray:
current = append(current, "0")
case scanObjectKey:
current[len(current)-1] = grokLiteral(data[beganLiteral-1 : oldOffset])
case scanBeginLiteral:
beganLiteral = scan.offset
case scanArrayValue:
n := mustParseInt(current[len(current)-1])
current[len(current)-1] = strconv.Itoa(n + 1)
case scanEndArray, scanEndObject:
current = sliceToEnd(current)
case scanBeginObject:
current = append(current, "")
}
if newOp == scanBeginArray || newOp == scanArrayValue ||
newOp == scanObjectKey {
if matchedAt < len(current)-1 {
continue
}
if matchedAt > len(current) {
matchedAt = len(current)
}
currentStr := encodePointer(current)
off := sort.SearchStrings(tpaths, currentStr)
if off < len(tpaths) {
// Check to see if the path we're
// going down could even lead to a
// possible match.
if strings.HasPrefix(tpaths[off], currentStr) {
matchedAt++
}
// And if it's not an exact match, keep parsing.
if tpaths[off] != currentStr {
continue
}
} else {
// Fell of the end of the list, no possible match
continue
}
// At this point, we have an exact match, so grab it.
stmp := setScanner(&sc2, data)
stmp.offset = scan.offset
val, _, err := nextValue(data, stmp)
if err != nil {
return m, err
}
m[currentStr] = val
todo--
}
}
return m, nil
}