Debian Codegraph @

internal/decoder/struct.go

raw
1 package decoder
2
3 import (
4 "fmt"
5 "math/bits"
6 "reflect"
7 "unsafe"
8
9 "github.com/goccy/go-json/internal/errors"
10 )
11
12 type structFieldSet struct {
13 dec Decoder
14 offset uintptr
15 isTaggedKey bool
16 fieldIdx int
17 key string
18 keyLen int64
19 err error
20 }
21
22 type structDecoder struct {
23 // fields are the fields of the struct in their order, by their exact keys.
24 fields []*structFieldSet
25 keys *structKeys
26 // fieldUniqueNameNum is the number of the fields which differ by their folded keys: under FirstWinOption,
27 // the rest of an object is skipped when every one of them was decoded.
28 fieldUniqueNameNum int
29 stringDecoder *stringDecoder
30 structName string
31 fieldName string
32 // typ is the struct type, and typeName its name, which the type errors report.
33 typ reflect.Type
34 typeName string
35 // embedded are the names of the embedded fields which the fields are promoted through, from the struct, which
36 // only the type errors report ( see typeErrorPath ).
37 embedded map[*structFieldSet][]string
38 }
39
40 func newStructDecoder(structName, fieldName string) *structDecoder {
41 return &structDecoder{
42 keys: newStructKeys(nil),
43 stringDecoder: newStringDecoder(structName, fieldName),
44 structName: structName,
45 fieldName: fieldName,
46 }
47 }
48
49 // setFields sets the fields of the struct, which are in the order of the struct, and makes their tables.
50 func (d *structDecoder) setFields(fields []*structFieldSet) {
51 d.fields = fields
52 d.keys = newStructKeys(fields)
53 indexByFolded := map[string]int{}
54 for _, field := range fields {
55 folded := string(appendFoldedKey(nil, []byte(field.key)))
56 idx, exists := indexByFolded[folded]
57 if !exists {
58 idx = len(indexByFolded)
59 indexByFolded[folded] = idx
60 }
61 field.fieldIdx = idx
62 }
63 d.fieldUniqueNameNum = len(indexByFolded)
64 }
65
66 func (d *structDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
67 buf := ctx.Buf
68 depth++
69 if depth > maxDecodeNestingDepth {
70 return 0, errors.ErrExceededMaxDepth(buf[cursor], cursor)
71 }
72 buflen := int64(len(buf))
73 cursor = skipWhiteSpace(buf, cursor)
74 b := (*sliceHeader)(unsafe.Pointer(&buf)).data
75 switch char(b, cursor) {
76 case 'n':
77 if err := validateNull(buf, cursor); err != nil {
78 return 0, err
79 }
80 cursor += 4
81 return cursor, nil
82 case '{':
83 default:
84 return d.decodeOther(ctx, cursor, depth-1)
85 }
86 cursor++
87 cursor = skipWhiteSpace(buf, cursor)
88 if buf[cursor] == '}' {
89 cursor++
90 return cursor, nil
91 }
92 if (ctx.Option.Flags & FirstWinOption) != 0 {
93 return d.decodeObjectFirstWin(ctx, cursor, depth, p)
94 }
95 disallowUnknownFields := (ctx.Option.Flags & DisallowUnknownFieldsOption) != 0
96 for {
97 field, c, err := d.decodeKey(buf, cursor, disallowUnknownFields)
98 if err != nil {
99 return 0, err
100 }
101 if char(b, c) == ':' {
102 cursor = c + 1
103 } else {
104 cursor = skipWhiteSpace(buf, c)
105 if char(b, cursor) != ':' {
106 return 0, errors.ErrExpected("colon after object key", cursor)
107 }
108 cursor++
109 }
110 if cursor >= buflen {
111 return 0, errors.ErrExpected("object value after colon", cursor)
112 }
113 if field != nil {
114 if field.err != nil {
115 // a field which can't be set: the error is recorded as a type error, and the decoding goes on
116 c, err := d.unsettableField(ctx, cursor, depth, field.err)
117 if err != nil {
118 return 0, err
119 }
120 cursor = c
121 } else {
122 c, err := field.dec.Decode(ctx, cursor, depth, unsafe.Add(p, field.offset))
123 if err != nil {
124 return 0, err
125 }
126 cursor = c
127 }
128 } else {
129 c, err := skipValue(buf, cursor, depth)
130 if err != nil {
131 return 0, err
132 }
133 cursor = c
134 }
135 cursor = skipWhiteSpace(buf, cursor)
136 if char(b, cursor) == '}' {
137 cursor++
138 return cursor, nil
139 }
140 if char(b, cursor) != ',' {
141 return 0, errors.ErrExpected("comma after object element", cursor)
142 }
143 cursor++
144 }
145 }
146
147 // decodeObjectFirstWin is the loop of Decode under FirstWinOption, from the first key of a non-empty object at
148 // cursor: a field is decoded at its first key, the value of a later key of the field is skipped, and the rest of
149 // the object is skipped once every field is decoded. It is a function of its own, so that the loop of Decode keeps
150 // nothing of it in its registers.
151 func (d *structDecoder) decodeObjectFirstWin(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
152 buf := ctx.Buf
153 buflen := int64(len(buf))
154 b := (*sliceHeader)(unsafe.Pointer(&buf)).data
155 // seen and seenMore are the fields decoded in the object, by their indexes: the bits of seen are the first 64
156 // fields, and the ones of seenMore the others ( see decodedBefore ); seenFieldNum is their number.
157 var (
158 seen uint64
159 seenMore []uint64
160 seenFieldNum int
161 )
162 disallowUnknownFields := (ctx.Option.Flags & DisallowUnknownFieldsOption) != 0
163 for {
164 field, c, err := d.decodeKey(buf, cursor, disallowUnknownFields)
165 if err != nil {
166 return 0, err
167 }
168 if char(b, c) == ':' {
169 cursor = c + 1
170 } else {
171 cursor = skipWhiteSpace(buf, c)
172 if char(b, cursor) != ':' {
173 return 0, errors.ErrExpected("colon after object key", cursor)
174 }
175 cursor++
176 }
177 if cursor >= buflen {
178 return 0, errors.ErrExpected("object value after colon", cursor)
179 }
180 if field != nil {
181 // the first 64 fields are the bits of seen, in a register; the others are looked at by a call
182 var decoded bool
183 if field.err != nil {
184 // a field which can't be set: the error is recorded as a type error, and the decoding goes on
185 c, err := d.unsettableField(ctx, cursor, depth, field.err)
186 if err != nil {
187 return 0, err
188 }
189 cursor = c
190 } else if idx := field.fieldIdx; idx < 64 {
191 bit := uint64(1) << uint(idx)
192 decoded = seen&bit != 0
193 seen |= bit
194 } else {
195 decoded = d.decodedBefore(idx, &seenMore)
196 }
197 switch {
198 case field.err != nil:
199 case decoded:
200 c, err := skipValue(buf, cursor, depth)
201 if err != nil {
202 return 0, err
203 }
204 cursor = c
205 default:
206 c, err := field.dec.Decode(ctx, cursor, depth, unsafe.Add(p, field.offset))
207 if err != nil {
208 return 0, err
209 }
210 cursor = c
211 seenFieldNum++
212 if d.fieldUniqueNameNum <= seenFieldNum {
213 // every field is decoded: the rest of the object is skipped, which is nothing in most objects,
214 // whose last key is the last field
215 if cursor = skipWhiteSpace(buf, cursor); char(b, cursor) == '}' {
216 return cursor + 1, nil
217 }
218 return skipRestOfObject(buf, cursor, depth)
219 }
220 }
221 } else {
222 c, err := skipValue(buf, cursor, depth)
223 if err != nil {
224 return 0, err
225 }
226 cursor = c
227 }
228 cursor = skipWhiteSpace(buf, cursor)
229 if char(b, cursor) == '}' {
230 cursor++
231 return cursor, nil
232 }
233 if char(b, cursor) != ',' {
234 return 0, errors.ErrExpected("comma after object element", cursor)
235 }
236 cursor++
237 }
238 }
239
240 // decodedBefore reports whether the field of the index, which is 64 or more, was decoded before in the object, under
241 // FirstWinOption, and marks it decoded: its bit is in more, which is made for a struct of more than 64 fields when
242 // such a field is decoded. The first 64 fields are marked in decodeObjectFirstWin itself, without an allocation.
243 //
244 //go:noinline
245 func (d *structDecoder) decodedBefore(idx int, more *[]uint64) bool {
246 if *more == nil {
247 *more = make([]uint64, (d.fieldUniqueNameNum-64+63)/64)
248 }
249 idx -= 64
250 w, bit := &(*more)[idx/64], uint64(1)<<uint(idx%64)
251 decoded := *w&bit != 0
252 *w |= bit
253 return decoded
254 }
255
256 // unsettableField records err, the error of a field which can't be set, for the value at cursor, and skips the
257 // value. It is not inlined, so that Decode keeps the size it had.
258 //
259 //go:noinline
260 func (d *structDecoder) unsettableField(ctx *RuntimeContext, cursor, depth int64, err error) (int64, error) {
261 return ctx.unsettableFieldError(cursor, depth, d.typ, err)
262 }
263
264 func (d *structDecoder) DecodePath(ctx *RuntimeContext, cursor, depth int64) ([][]byte, int64, error) {
265 return nil, 0, fmt.Errorf("json: struct decoder does not support decode path")
266 }
267
268 // decodeKey reads the key of an object at cursor, and returns its field or nil, and the position after it.
269 // A key which matches no field is an error if disallowUnknownFields is set. It is a function of its own, so that
270 // the loop of Decode keeps its values in the registers, and the key is not returned, which would take registers
271 // of the loop too.
272 func (d *structDecoder) decodeKey(buf []byte, cursor int64, disallowUnknownFields bool) (*structFieldSet, int64, error) {
273 if buf[cursor] != '"' {
274 cursor = skipWhiteSpace(buf, cursor)
275 if buf[cursor] != '"' {
276 return nil, 0, errors.ErrInvalidBeginningOfValue(buf[cursor], cursor)
277 }
278 }
279 // A key of ASCII without an escape is found by the words of the buffer, which may be read up to its capacity:
280 // the nul byte at its end stops a key before it. Any other key, and a key near the end of a buffer which has
281 // no room after it, is scanned as a string.
282 if start := cursor + 1; start+16 <= int64(cap(buf)) {
283 keys := d.keys
284 w0 := load64(buf, start)
285 special := specialKeyBytes(w0)
286 if special != 0 {
287 // A key of less than 8 bytes, which is most keys. The first entry of the table for it is looked at
288 // here: most keys are found in it. Its index is made from the bytes of the key before their fold, and
289 // so is computed while they are folded, and the mask of the bytes from the bits of the special byte.
290 n := bits.TrailingZeros64(special) / 8
291 if buf[start+int64(n)] != '"' {
292 return d.decodeKeyNotASCII(buf, cursor, disallowUnknownFields)
293 }
294 m := (special ^ (special - 1)) >> 8
295 w0 &= m
296 fw := foldASCIIWord(w0)
297 e := &keys.entries[keys.index(w0|bit5&m, 0)]
298 var field *structFieldSet
299 if e.short == fw {
300 field = e.unique
301 } else if e.fields != nil && keys.hasLength(n) {
302 field = keys.findASCII(buf[start:start+int64(n)], w0, 0)
303 }
304 if field == nil && disallowUnknownFields {
305 return nil, 0, unknownFieldError(buf[start : start+int64(n)])
306 }
307 return field, start + int64(n) + 1, nil
308 }
309 // A key of 8 bytes or more, whose end is looked for word by word. It is looked up by its first and last
310 // words, as a short key is.
311 end := start + 8
312 special = specialKeyBytes(load64(buf, end))
313 for special == 0 {
314 end += 8
315 if end+8 > int64(cap(buf)) {
316 return d.decodeKeyByScan(buf, cursor, disallowUnknownFields)
317 }
318 special = specialKeyBytes(load64(buf, end))
319 }
320 end += int64(bits.TrailingZeros64(special) / 8)
321 if buf[end] != '"' {
322 return d.decodeKeyNotASCII(buf, cursor, disallowUnknownFields)
323 }
324 key := buf[start:end]
325 n := len(key)
326 var field *structFieldSet
327 // A key of a length which no field has, which is a key of no field in most objects of such a length,
328 // is not looked up.
329 if keys.hasLength(n) {
330 w1 := load64(buf, end-8)
331 fw0, fw1 := foldASCIIWord(w0), foldASCIIWord(w1)
332 e := &keys.entries[keys.index(w0|bit5, w1|bit5)]
333 if e.n == n && e.w0 == fw0 && e.w1 == fw1 && e.unique != nil && (n <= 16 || equalFoldedASCII(key, e.folded)) {
334 field = e.unique
335 } else if e.fields != nil {
336 field = keys.findASCII(key, w0, w1)
337 }
338 }
339 if field == nil && disallowUnknownFields {
340 return nil, 0, unknownFieldError(key)
341 }
342 return field, end + 1, nil
343 }
344 return d.decodeKeyByScan(buf, cursor, disallowUnknownFields)
345 }
346
347 // decodeKeyNotASCII is decodeKey for a key which has a byte which is not ASCII, or an escape. A key without an
348 // escape is read word by word too, and looked up by its bytes as they are among the keys which are not ASCII
349 // first: a key is usually the same as the key of its field, which it is found by whatever the fold of its runes,
350 // because a key which is the same wins over the others. Any other key is folded rune by rune if its runes may
351 // fold to the ones of a key, and else is of no field. A key with an escape is scanned as a string.
352 func (d *structDecoder) decodeKeyNotASCII(buf []byte, cursor int64, disallowUnknownFields bool) (*structFieldSet, int64, error) {
353 start := cursor + 1
354 end := start
355 for {
356 if end+8 > int64(cap(buf)) {
357 return d.decodeKeyByScan(buf, cursor, disallowUnknownFields)
358 }
359 if special := keyEndBytes(load64(buf, end)); special != 0 {
360 end += int64(bits.TrailingZeros64(special) / 8)
361 break
362 }
363 end += 8
364 }
365 if buf[end] != '"' {
366 return d.decodeKeyByScan(buf, cursor, disallowUnknownFields)
367 }
368 key := buf[start:end]
369 n := len(key)
370 keys := d.keys
371 // the words of the key, as keyWords makes them, read from the buffer
372 w0 := load64(buf, start)
373 var w1 uint64
374 if n < 8 {
375 w0 &= 1<<(uint(n)*8&63) - 1
376 } else {
377 w1 = load64(buf, end-8)
378 }
379 var field *structFieldSet
380 if keys.hasExactLength(n) {
381 // the first entry of the key is looked at here: most keys are found in it.
382 h0, h1 := hashWords(w0, w1, n)
383 e := &keys.exact[indexOf(h0, h1, keys.exactShift)]
384 if e.n == n && e.w0 == w0 && e.w1 == w1 && e.unique != nil && (n <= 16 || equalMiddleWords(key, e.folded)) {
385 return e.unique, end + 1, nil
386 }
387 if e.unique != nil {
388 field = keys.findExact(key, w0, w1)
389 }
390 }
391 if field == nil {
392 // Most keys which are not the key of a field are told so by their first rune which is not ASCII, which
393 // folds to no rune of a key ( see mayFold ); the others are looked at rune by rune.
394 if keys.leadMayFold(w0) && keys.firstRuneMayFold(key, w0) && keys.mayFold(key) {
395 field, key = keys.lookup(key, stringInfo{firstEscape: -1, nonASCII: true})
396 } else if disallowUnknownFields {
397 key = decodeLiteral(key, stringInfo{firstEscape: -1, nonASCII: true})
398 }
399 }
400 if field == nil && disallowUnknownFields {
401 return nil, 0, unknownFieldError(key)
402 }
403 return field, end + 1, nil
404 }
405
406 // decodeKeyByScan is decodeKey for any key, which it scans as a string.
407 func (d *structDecoder) decodeKeyByScan(buf []byte, cursor int64, disallowUnknownFields bool) (*structFieldSet, int64, error) {
408 rawKey, next, info, err := d.stringDecoder.scanString(buf, cursor)
409 if next < 0 {
410 rawKey, next, info, err = d.stringDecoder.scanStringRest(buf, rawKey, -next-1, info)
411 }
412 if err != nil {
413 return nil, 0, err
414 }
415 field, key := d.keys.lookup(rawKey, info)
416 if field == nil && disallowUnknownFields {
417 return nil, 0, unknownFieldError(key)
418 }
419 return field, next, nil
420 }
421
422 // decodeOther skips the value at cursor, which is not an object: a value of another kind is a type error, and
423 // anything else a syntax error. It is a function of its own, so that Decode keeps the size it had.
424 //
425 //go:noinline
426 func (d *structDecoder) decodeOther(ctx *RuntimeContext, cursor, depth int64) (int64, error) {
427 if c := ctx.Buf[cursor]; isOtherValue(c, objectValue) {
428 return ctx.skipTypeError(cursor, depth, d.typ)
429 }
430 return 0, errors.ErrInvalidBeginningOfValue(ctx.Buf[cursor], cursor)
431 }
432
433 func unknownFieldError(key []byte) error {
434 return fmt.Errorf("json: unknown field %q", key)
435 }
436
437 // specialKeyBytes returns the word which has the top bit of the first byte of w which ends a simple key, and
438 // maybe the top bits of bytes after it: a quote, a backslash, a control character or a byte which is not ASCII.
439 func specialKeyBytes(w uint64) uint64 {
440 // Only the first such byte is looked for, so the masks may be wrong in the bytes after it, which saves
441 // instructions: a subtraction borrows from the next byte only at a byte which is found.
442 // A byte of a quote or a backslash is 0 in q or s, whose subtraction sets its top bit; the one of a control
443 // character sets the top bit of the subtraction of 0x20, and the one of a byte which is not ASCII is set.
444 q := w ^ ('"' * lsb)
445 s := w ^ ('\\' * lsb)
446 return (((q - lsb) &^ q) | ((s - lsb) &^ s) | (w - 0x20*lsb) | w) & msb
447 }
448
449 // keyEndBytes is specialKeyBytes for a key which may have bytes which are not ASCII: it has the top bit of the
450 // first byte of w which is a quote, a backslash or a control character, and maybe of bytes after it.
451 func keyEndBytes(w uint64) uint64 {
452 // a byte of 0x80 or more is none of them: its top bit is cleared from the subtractions, which don't borrow
453 // from the next byte at such a byte.
454 q := w ^ ('"' * lsb)
455 s := w ^ ('\\' * lsb)
456 return (((q - lsb) &^ q) | ((s - lsb) &^ s) | ((w - 0x20*lsb) &^ w)) & msb
457 }