-
Notifications
You must be signed in to change notification settings - Fork 9
/
bytes.go
328 lines (290 loc) · 6.71 KB
/
bytes.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
package jsonpointer
import (
"fmt"
"sort"
"strconv"
"strings"
"github.com/dustin/gojson"
)
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 := json.UnquoteBytes(b)
if !ok {
panic("could not grok literal " + string(b))
}
return string(s)
}
func isSpace(c rune) bool {
return c == ' ' || c == '\t' || c == '\r' || c == '\n'
}
// 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 json.Unmarshal(d, into)
}
// Find a section of raw JSON by specifying a JSONPointer.
func Find(data []byte, path string) ([]byte, error) {
if path == "" {
return data, nil
}
needle := parsePointer(path)
scan := &json.Scanner{}
scan.Reset()
offset := 0
beganLiteral := 0
current := make([]string, 0, 32)
for {
if offset >= len(data) {
break
}
newOp := scan.Step(scan, int(data[offset]))
offset++
switch newOp {
case json.ScanBeginArray:
current = append(current, "0")
case json.ScanObjectKey:
current[len(current)-1] = grokLiteral(data[beganLiteral-1 : offset-1])
case json.ScanBeginLiteral:
beganLiteral = offset
case json.ScanArrayValue:
n := mustParseInt(current[len(current)-1])
current[len(current)-1] = strconv.Itoa(n + 1)
case json.ScanEndArray, json.ScanEndObject:
current = sliceToEnd(current)
case json.ScanBeginObject:
current = append(current, "")
case json.ScanContinue, json.ScanSkipSpace, json.ScanObjectValue, json.ScanEnd:
default:
return nil, fmt.Errorf("found unhandled json op: %v", newOp)
}
if (newOp == json.ScanBeginArray || newOp == json.ScanArrayValue ||
newOp == json.ScanObjectKey) && arreq(needle, current) {
otmp := offset
for isSpace(rune(data[otmp])) {
otmp++
}
if data[otmp] == ']' {
// special case an array offset miss
offset = otmp
return nil, nil
}
val, _, err := json.NextValue(data[offset:], scan)
return val, err
}
}
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) {
if len(data) == 0 {
return nil, fmt.Errorf("Invalid JSON")
}
rv := []string{""}
scan := &json.Scanner{}
scan.Reset()
offset := 0
beganLiteral := 0
var current []string
for {
if offset >= len(data) {
return rv, nil
}
newOp := scan.Step(scan, int(data[offset]))
offset++
switch newOp {
case json.ScanBeginArray:
current = append(current, "0")
case json.ScanObjectKey:
current[len(current)-1] = grokLiteral(data[beganLiteral-1 : offset-1])
case json.ScanBeginLiteral:
beganLiteral = offset
case json.ScanArrayValue:
n := mustParseInt(current[len(current)-1])
current[len(current)-1] = strconv.Itoa(n + 1)
case json.ScanEndArray, json.ScanEndObject:
current = sliceToEnd(current)
case json.ScanBeginObject:
current = append(current, "")
case json.ScanError:
return nil, fmt.Errorf("Error reading JSON object at offset %v", offset)
}
if newOp == json.ScanBeginArray || newOp == json.ScanArrayValue ||
newOp == json.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) {
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 := &json.Scanner{}
scan.Reset()
offset := 0
todo := len(tpaths)
beganLiteral := 0
matchedAt := 0
var current []string
for todo > 0 {
if offset >= len(data) {
break
}
newOp := scan.Step(scan, int(data[offset]))
offset++
switch newOp {
case json.ScanBeginArray:
current = append(current, "0")
case json.ScanObjectKey:
current[len(current)-1] = grokLiteral(data[beganLiteral-1 : offset-1])
case json.ScanBeginLiteral:
beganLiteral = offset
case json.ScanArrayValue:
n := mustParseInt(current[len(current)-1])
current[len(current)-1] = strconv.Itoa(n + 1)
case json.ScanEndArray, json.ScanEndObject:
current = sliceToEnd(current)
case json.ScanBeginObject:
current = append(current, "")
}
if newOp == json.ScanBeginArray || newOp == json.ScanArrayValue ||
newOp == json.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 := &json.Scanner{}
val, _, err := json.NextValue(data[offset:], stmp)
if err != nil {
return m, err
}
m[currentStr] = val
todo--
}
}
return m, nil
}