Debian Codegraph @

json/codec.go

raw
1 package json
2
3 import (
4 "encoding"
5 "encoding/json"
6 "fmt"
7 "maps"
8 "math/big"
9 "reflect"
10 "sort"
11 "strconv"
12 "strings"
13 "sync/atomic"
14 "time"
15 "unicode"
16 "unsafe"
17
18 "github.com/segmentio/asm/keyset"
19 )
20
21 const (
22 // 1000 is the value used by the standard encoding/json package.
23 //
24 // https://cs.opensource.google/go/go/+/refs/tags/go1.17.3:src/encoding/json/encode.go;drc=refs%2Ftags%2Fgo1.17.3;l=300
25 startDetectingCyclesAfter = 1000
26 )
27
28 type codec struct {
29 encode encodeFunc
30 decode decodeFunc
31 }
32
33 type encoder struct {
34 flags AppendFlags
35 // ptrDepth tracks the depth of pointer cycles, when it reaches the value
36 // of startDetectingCyclesAfter, the ptrSeen map is allocated and the
37 // encoder starts tracking pointers it has seen as an attempt to detect
38 // whether it has entered a pointer cycle and needs to error before the
39 // goroutine runs out of stack space.
40 ptrDepth uint32
41 ptrSeen map[unsafe.Pointer]struct{}
42 }
43
44 type decoder struct {
45 flags ParseFlags
46 }
47
48 type (
49 encodeFunc func(encoder, []byte, unsafe.Pointer) ([]byte, error)
50 decodeFunc func(decoder, []byte, unsafe.Pointer) ([]byte, error)
51 )
52
53 type (
54 emptyFunc func(unsafe.Pointer) bool
55 sortFunc func([]reflect.Value)
56 )
57
58 // Eventually consistent cache mapping go types to dynamically generated
59 // codecs.
60 //
61 // Note: using a uintptr as key instead of reflect.Type shaved ~15ns off of
62 // the ~30ns Marhsal/Unmarshal functions which were dominated by the map
63 // lookup time for simple types like bool, int, etc..
64 var cache atomic.Pointer[map[unsafe.Pointer]codec]
65
66 func cacheLoad() map[unsafe.Pointer]codec {
67 p := cache.Load()
68 if p == nil {
69 return nil
70 }
71
72 return *p
73 }
74
75 func cacheStore(typ reflect.Type, cod codec, oldCodecs map[unsafe.Pointer]codec) {
76 newCodecs := make(map[unsafe.Pointer]codec, len(oldCodecs)+1)
77 maps.Copy(newCodecs, oldCodecs)
78 newCodecs[typeid(typ)] = cod
79
80 cache.Store(&newCodecs)
81 }
82
83 func typeid(t reflect.Type) unsafe.Pointer {
84 return (*iface)(unsafe.Pointer(&t)).ptr
85 }
86
87 func constructCachedCodec(t reflect.Type, cache map[unsafe.Pointer]codec) codec {
88 c := constructCodec(t, map[reflect.Type]*structType{}, t.Kind() == reflect.Ptr)
89
90 if inlined(t) {
91 c.encode = constructInlineValueEncodeFunc(c.encode)
92 }
93
94 cacheStore(t, c, cache)
95 return c
96 }
97
98 func constructCodec(t reflect.Type, seen map[reflect.Type]*structType, canAddr bool) (c codec) {
99 switch t {
100 case nullType, nil:
101 c = codec{encode: encoder.encodeNull, decode: decoder.decodeNull}
102
103 case numberType:
104 c = codec{encode: encoder.encodeNumber, decode: decoder.decodeNumber}
105
106 case bytesType:
107 c = codec{encode: encoder.encodeBytes, decode: decoder.decodeBytes}
108
109 case durationType:
110 c = codec{encode: encoder.encodeDuration, decode: decoder.decodeDuration}
111
112 case timeType:
113 c = codec{encode: encoder.encodeTime, decode: decoder.decodeTime}
114
115 case interfaceType:
116 c = codec{encode: encoder.encodeInterface, decode: decoder.decodeInterface}
117
118 case rawMessageType:
119 c = codec{encode: encoder.encodeRawMessage, decode: decoder.decodeRawMessage}
120
121 case numberPtrType:
122 c = constructPointerCodec(numberPtrType, nil)
123
124 case durationPtrType:
125 c = constructPointerCodec(durationPtrType, nil)
126
127 case timePtrType:
128 c = constructPointerCodec(timePtrType, nil)
129
130 case rawMessagePtrType:
131 c = constructPointerCodec(rawMessagePtrType, nil)
132 }
133
134 if c.encode != nil {
135 return
136 }
137
138 switch t.Kind() {
139 case reflect.Bool:
140 c = codec{encode: encoder.encodeBool, decode: decoder.decodeBool}
141
142 case reflect.Int:
143 c = codec{encode: encoder.encodeInt, decode: decoder.decodeInt}
144
145 case reflect.Int8:
146 c = codec{encode: encoder.encodeInt8, decode: decoder.decodeInt8}
147
148 case reflect.Int16:
149 c = codec{encode: encoder.encodeInt16, decode: decoder.decodeInt16}
150
151 case reflect.Int32:
152 c = codec{encode: encoder.encodeInt32, decode: decoder.decodeInt32}
153
154 case reflect.Int64:
155 c = codec{encode: encoder.encodeInt64, decode: decoder.decodeInt64}
156
157 case reflect.Uint:
158 c = codec{encode: encoder.encodeUint, decode: decoder.decodeUint}
159
160 case reflect.Uintptr:
161 c = codec{encode: encoder.encodeUintptr, decode: decoder.decodeUintptr}
162
163 case reflect.Uint8:
164 c = codec{encode: encoder.encodeUint8, decode: decoder.decodeUint8}
165
166 case reflect.Uint16:
167 c = codec{encode: encoder.encodeUint16, decode: decoder.decodeUint16}
168
169 case reflect.Uint32:
170 c = codec{encode: encoder.encodeUint32, decode: decoder.decodeUint32}
171
172 case reflect.Uint64:
173 c = codec{encode: encoder.encodeUint64, decode: decoder.decodeUint64}
174
175 case reflect.Float32:
176 c = codec{encode: encoder.encodeFloat32, decode: decoder.decodeFloat32}
177
178 case reflect.Float64:
179 c = codec{encode: encoder.encodeFloat64, decode: decoder.decodeFloat64}
180
181 case reflect.String:
182 c = codec{encode: encoder.encodeString, decode: decoder.decodeString}
183
184 case reflect.Interface:
185 c = constructInterfaceCodec(t)
186
187 case reflect.Array:
188 c = constructArrayCodec(t, seen, canAddr)
189
190 case reflect.Slice:
191 c = constructSliceCodec(t, seen)
192
193 case reflect.Map:
194 c = constructMapCodec(t, seen)
195
196 case reflect.Struct:
197 c = constructStructCodec(t, seen, canAddr)
198
199 case reflect.Ptr:
200 c = constructPointerCodec(t, seen)
201
202 default:
203 c = constructUnsupportedTypeCodec(t)
204 }
205
206 p := reflect.PointerTo(t)
207
208 if canAddr {
209 switch {
210 case p.Implements(jsonMarshalerType):
211 c.encode = constructJSONMarshalerEncodeFunc(t, true)
212 case p.Implements(textMarshalerType):
213 c.encode = constructTextMarshalerEncodeFunc(t, true)
214 }
215 }
216
217 switch {
218 case t.Implements(jsonMarshalerType):
219 c.encode = constructJSONMarshalerEncodeFunc(t, false)
220 case t.Implements(textMarshalerType):
221 c.encode = constructTextMarshalerEncodeFunc(t, false)
222 }
223
224 switch {
225 case p.Implements(jsonUnmarshalerType):
226 c.decode = constructJSONUnmarshalerDecodeFunc(t, true)
227 case p.Implements(textUnmarshalerType):
228 c.decode = constructTextUnmarshalerDecodeFunc(t, true)
229 }
230
231 return
232 }
233
234 func constructStringCodec(t reflect.Type, seen map[reflect.Type]*structType, canAddr bool) codec {
235 c := constructCodec(t, seen, canAddr)
236 return codec{
237 encode: constructStringEncodeFunc(c.encode),
238 decode: constructStringDecodeFunc(c.decode),
239 }
240 }
241
242 func constructStringEncodeFunc(encode encodeFunc) encodeFunc {
243 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
244 return e.encodeToString(b, p, encode)
245 }
246 }
247
248 func constructStringDecodeFunc(decode decodeFunc) decodeFunc {
249 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
250 return d.decodeFromString(b, p, decode)
251 }
252 }
253
254 func constructStringToIntDecodeFunc(t reflect.Type, decode decodeFunc) decodeFunc {
255 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
256 return d.decodeFromStringToInt(b, p, t, decode)
257 }
258 }
259
260 func constructArrayCodec(t reflect.Type, seen map[reflect.Type]*structType, canAddr bool) codec {
261 e := t.Elem()
262 c := constructCodec(e, seen, canAddr)
263 s := alignedSize(e)
264 return codec{
265 encode: constructArrayEncodeFunc(s, t, c.encode),
266 decode: constructArrayDecodeFunc(s, t, c.decode),
267 }
268 }
269
270 func constructArrayEncodeFunc(size uintptr, t reflect.Type, encode encodeFunc) encodeFunc {
271 n := t.Len()
272 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
273 return e.encodeArray(b, p, n, size, t, encode)
274 }
275 }
276
277 func constructArrayDecodeFunc(size uintptr, t reflect.Type, decode decodeFunc) decodeFunc {
278 n := t.Len()
279 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
280 return d.decodeArray(b, p, n, size, t, decode)
281 }
282 }
283
284 func constructSliceCodec(t reflect.Type, seen map[reflect.Type]*structType) codec {
285 e := t.Elem()
286 s := alignedSize(e)
287
288 if e.Kind() == reflect.Uint8 {
289 // Go 1.7+ behavior: slices of byte types (and aliases) may override the
290 // default encoding and decoding behaviors by implementing marshaler and
291 // unmarshaler interfaces.
292 p := reflect.PointerTo(e)
293 c := codec{}
294
295 switch {
296 case e.Implements(jsonMarshalerType):
297 c.encode = constructJSONMarshalerEncodeFunc(e, false)
298 case e.Implements(textMarshalerType):
299 c.encode = constructTextMarshalerEncodeFunc(e, false)
300 case p.Implements(jsonMarshalerType):
301 c.encode = constructJSONMarshalerEncodeFunc(e, true)
302 case p.Implements(textMarshalerType):
303 c.encode = constructTextMarshalerEncodeFunc(e, true)
304 }
305
306 switch {
307 case e.Implements(jsonUnmarshalerType):
308 c.decode = constructJSONUnmarshalerDecodeFunc(e, false)
309 case e.Implements(textUnmarshalerType):
310 c.decode = constructTextUnmarshalerDecodeFunc(e, false)
311 case p.Implements(jsonUnmarshalerType):
312 c.decode = constructJSONUnmarshalerDecodeFunc(e, true)
313 case p.Implements(textUnmarshalerType):
314 c.decode = constructTextUnmarshalerDecodeFunc(e, true)
315 }
316
317 if c.encode != nil {
318 c.encode = constructSliceEncodeFunc(s, t, c.encode)
319 } else {
320 c.encode = encoder.encodeBytes
321 }
322
323 if c.decode != nil {
324 c.decode = constructSliceDecodeFunc(s, t, c.decode)
325 } else {
326 c.decode = decoder.decodeBytes
327 }
328
329 return c
330 }
331
332 c := constructCodec(e, seen, true)
333 return codec{
334 encode: constructSliceEncodeFunc(s, t, c.encode),
335 decode: constructSliceDecodeFunc(s, t, c.decode),
336 }
337 }
338
339 func constructSliceEncodeFunc(size uintptr, t reflect.Type, encode encodeFunc) encodeFunc {
340 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
341 return e.encodeSlice(b, p, size, t, encode)
342 }
343 }
344
345 func constructSliceDecodeFunc(size uintptr, t reflect.Type, decode decodeFunc) decodeFunc {
346 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
347 return d.decodeSlice(b, p, size, t, decode)
348 }
349 }
350
351 func constructMapCodec(t reflect.Type, seen map[reflect.Type]*structType) codec {
352 var sortKeys sortFunc
353 k := t.Key()
354 v := t.Elem()
355
356 // Faster implementations for some common cases.
357 switch {
358 case k == stringType && v == interfaceType:
359 return codec{
360 encode: encoder.encodeMapStringInterface,
361 decode: decoder.decodeMapStringInterface,
362 }
363
364 case k == stringType && v == rawMessageType:
365 return codec{
366 encode: encoder.encodeMapStringRawMessage,
367 decode: decoder.decodeMapStringRawMessage,
368 }
369
370 case k == stringType && v == stringType:
371 return codec{
372 encode: encoder.encodeMapStringString,
373 decode: decoder.decodeMapStringString,
374 }
375
376 case k == stringType && v == stringsType:
377 return codec{
378 encode: encoder.encodeMapStringStringSlice,
379 decode: decoder.decodeMapStringStringSlice,
380 }
381
382 case k == stringType && v == boolType:
383 return codec{
384 encode: encoder.encodeMapStringBool,
385 decode: decoder.decodeMapStringBool,
386 }
387 }
388
389 kc := codec{}
390 vc := constructCodec(v, seen, false)
391
392 if k.Implements(textMarshalerType) || reflect.PointerTo(k).Implements(textUnmarshalerType) {
393 kc.encode = constructTextMarshalerEncodeFunc(k, false)
394 kc.decode = constructTextUnmarshalerDecodeFunc(k, true)
395
396 sortKeys = func(keys []reflect.Value) {
397 sort.Slice(keys, func(i, j int) bool {
398 // This is a performance abomination but the use case is rare
399 // enough that it shouldn't be a problem in practice.
400 k1, _ := keys[i].Interface().(encoding.TextMarshaler).MarshalText()
401 k2, _ := keys[j].Interface().(encoding.TextMarshaler).MarshalText()
402 return string(k1) < string(k2)
403 })
404 }
405 } else {
406 switch k.Kind() {
407 case reflect.String:
408 kc.encode = encoder.encodeString
409 kc.decode = decoder.decodeString
410
411 sortKeys = func(keys []reflect.Value) {
412 sort.Slice(keys, func(i, j int) bool { return keys[i].String() < keys[j].String() })
413 }
414
415 case reflect.Int,
416 reflect.Int8,
417 reflect.Int16,
418 reflect.Int32,
419 reflect.Int64:
420 kc = constructStringCodec(k, seen, false)
421
422 sortKeys = func(keys []reflect.Value) {
423 sort.Slice(keys, func(i, j int) bool { return intStringsAreSorted(keys[i].Int(), keys[j].Int()) })
424 }
425
426 case reflect.Uint,
427 reflect.Uintptr,
428 reflect.Uint8,
429 reflect.Uint16,
430 reflect.Uint32,
431 reflect.Uint64:
432 kc = constructStringCodec(k, seen, false)
433
434 sortKeys = func(keys []reflect.Value) {
435 sort.Slice(keys, func(i, j int) bool { return uintStringsAreSorted(keys[i].Uint(), keys[j].Uint()) })
436 }
437
438 default:
439 return constructUnsupportedTypeCodec(t)
440 }
441 }
442
443 if inlined(v) {
444 vc.encode = constructInlineValueEncodeFunc(vc.encode)
445 }
446
447 return codec{
448 encode: constructMapEncodeFunc(t, kc.encode, vc.encode, sortKeys),
449 decode: constructMapDecodeFunc(t, kc.decode, vc.decode),
450 }
451 }
452
453 func constructMapEncodeFunc(t reflect.Type, encodeKey, encodeValue encodeFunc, sortKeys sortFunc) encodeFunc {
454 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
455 return e.encodeMap(b, p, t, encodeKey, encodeValue, sortKeys)
456 }
457 }
458
459 func constructMapDecodeFunc(t reflect.Type, decodeKey, decodeValue decodeFunc) decodeFunc {
460 kt := t.Key()
461 vt := t.Elem()
462 kz := reflect.Zero(kt)
463 vz := reflect.Zero(vt)
464 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
465 return d.decodeMap(b, p, t, kt, vt, kz, vz, decodeKey, decodeValue)
466 }
467 }
468
469 func constructStructCodec(t reflect.Type, seen map[reflect.Type]*structType, canAddr bool) codec {
470 st := constructStructType(t, seen, canAddr)
471 return codec{
472 encode: constructStructEncodeFunc(st),
473 decode: constructStructDecodeFunc(st),
474 }
475 }
476
477 func constructStructType(t reflect.Type, seen map[reflect.Type]*structType, canAddr bool) *structType {
478 // Used for preventing infinite recursion on types that have pointers to
479 // themselves.
480 st := seen[t]
481
482 if st == nil {
483 st = &structType{
484 fields: make([]structField, 0, t.NumField()),
485 fieldsIndex: make(map[string]*structField),
486 ficaseIndex: make(map[string]*structField),
487 typ: t,
488 }
489
490 seen[t] = st
491 st.fields = appendStructFields(st.fields, t, 0, seen, canAddr)
492
493 for i := range st.fields {
494 f := &st.fields[i]
495 s := strings.ToLower(f.name)
496 st.fieldsIndex[f.name] = f
497 // When there is ambiguity because multiple fields have the same
498 // case-insensitive representation, the first field must win.
499 if _, exists := st.ficaseIndex[s]; !exists {
500 st.ficaseIndex[s] = f
501 }
502 }
503
504 // At a certain point the linear scan provided by keyset is less
505 // efficient than a map. The 32 was chosen based on benchmarks in the
506 // segmentio/asm repo run with an Intel Kaby Lake processor and go1.17.
507 if len(st.fields) <= 32 {
508 keys := make([][]byte, len(st.fields))
509 for i, f := range st.fields {
510 keys[i] = []byte(f.name)
511 }
512 st.keyset = keyset.New(keys)
513 }
514 }
515
516 return st
517 }
518
519 func constructStructEncodeFunc(st *structType) encodeFunc {
520 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
521 return e.encodeStruct(b, p, st)
522 }
523 }
524
525 func constructStructDecodeFunc(st *structType) decodeFunc {
526 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
527 return d.decodeStruct(b, p, st)
528 }
529 }
530
531 func constructEmbeddedStructPointerCodec(t reflect.Type, unexported bool, offset uintptr, field codec) codec {
532 return codec{
533 encode: constructEmbeddedStructPointerEncodeFunc(t, unexported, offset, field.encode),
534 decode: constructEmbeddedStructPointerDecodeFunc(t, unexported, offset, field.decode),
535 }
536 }
537
538 func constructEmbeddedStructPointerEncodeFunc(t reflect.Type, unexported bool, offset uintptr, encode encodeFunc) encodeFunc {
539 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
540 return e.encodeEmbeddedStructPointer(b, p, t, unexported, offset, encode)
541 }
542 }
543
544 func constructEmbeddedStructPointerDecodeFunc(t reflect.Type, unexported bool, offset uintptr, decode decodeFunc) decodeFunc {
545 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
546 return d.decodeEmbeddedStructPointer(b, p, t, unexported, offset, decode)
547 }
548 }
549
550 func appendStructFields(fields []structField, t reflect.Type, offset uintptr, seen map[reflect.Type]*structType, canAddr bool) []structField {
551 type embeddedField struct {
552 index int
553 offset uintptr
554 pointer bool
555 unexported bool
556 subtype *structType
557 subfield *structField
558 }
559
560 names := make(map[string]struct{})
561 embedded := make([]embeddedField, 0, 10)
562
563 for i := range t.NumField() {
564 f := t.Field(i)
565
566 var (
567 name = f.Name
568 anonymous = f.Anonymous
569 tag = false
570 omitempty = false
571 stringify = false
572 unexported = len(f.PkgPath) != 0
573 )
574
575 if unexported && !anonymous { // unexported
576 continue
577 }
578
579 if parts := strings.Split(f.Tag.Get("json"), ","); len(parts) != 0 {
580 if len(parts[0]) != 0 {
581 name, tag = parts[0], true
582 }
583
584 if name == "-" && len(parts) == 1 { // ignored
585 continue
586 }
587
588 if !isValidTag(name) {
589 name = f.Name
590 }
591
592 for _, tag := range parts[1:] {
593 switch tag {
594 case "omitempty":
595 omitempty = true
596 case "string":
597 stringify = true
598 }
599 }
600 }
601
602 if anonymous && !tag { // embedded
603 typ := f.Type
604 ptr := f.Type.Kind() == reflect.Ptr
605
606 if ptr {
607 typ = f.Type.Elem()
608 }
609
610 if typ.Kind() == reflect.Struct {
611 // When the embedded fields is inlined the fields can be looked
612 // up by offset from the address of the wrapping object, so we
613 // simply add the embedded struct fields to the list of fields
614 // of the current struct type.
615 subtype := constructStructType(typ, seen, canAddr)
616
617 for j := range subtype.fields {
618 embedded = append(embedded, embeddedField{
619 index: i<<32 | j,
620 offset: offset + f.Offset,
621 pointer: ptr,
622 unexported: unexported,
623 subtype: subtype,
624 subfield: &subtype.fields[j],
625 })
626 }
627
628 continue
629 }
630
631 if unexported { // ignore unexported non-struct types
632 continue
633 }
634 }
635
636 codec := constructCodec(f.Type, seen, canAddr)
637
638 if stringify {
639 // https://golang.org/pkg/encoding/json/#Marshal
640 //
641 // The "string" option signals that a field is stored as JSON inside
642 // a JSON-encoded string. It applies only to fields of string,
643 // floating point, integer, or boolean types. This extra level of
644 // encoding is sometimes used when communicating with JavaScript
645 // programs:
646 typ := f.Type
647
648 if typ.Kind() == reflect.Ptr {
649 typ = typ.Elem()
650 }
651
652 switch typ.Kind() {
653 case reflect.Int,
654 reflect.Int8,
655 reflect.Int16,
656 reflect.Int32,
657 reflect.Int64,
658 reflect.Uint,
659 reflect.Uintptr,
660 reflect.Uint8,
661 reflect.Uint16,
662 reflect.Uint32,
663 reflect.Uint64:
664 codec.encode = constructStringEncodeFunc(codec.encode)
665 codec.decode = constructStringToIntDecodeFunc(typ, codec.decode)
666 case reflect.Bool,
667 reflect.Float32,
668 reflect.Float64,
669 reflect.String:
670 codec.encode = constructStringEncodeFunc(codec.encode)
671 codec.decode = constructStringDecodeFunc(codec.decode)
672 }
673 }
674
675 fields = append(fields, structField{
676 codec: codec,
677 offset: offset + f.Offset,
678 empty: emptyFuncOf(f.Type),
679 tag: tag,
680 omitempty: omitempty,
681 name: name,
682 index: i << 32,
683 typ: f.Type,
684 zero: reflect.Zero(f.Type),
685 })
686
687 names[name] = struct{}{}
688 }
689
690 // Only unambiguous embedded fields must be serialized.
691 ambiguousNames := make(map[string]int)
692 ambiguousTags := make(map[string]int)
693
694 // Embedded types can never override a field that was already present at
695 // the top-level.
696 for name := range names {
697 ambiguousNames[name]++
698 ambiguousTags[name]++
699 }
700
701 for _, embfield := range embedded {
702 ambiguousNames[embfield.subfield.name]++
703 if embfield.subfield.tag {
704 ambiguousTags[embfield.subfield.name]++
705 }
706 }
707
708 for _, embfield := range embedded {
709 subfield := *embfield.subfield
710
711 if ambiguousNames[subfield.name] > 1 && (!subfield.tag || ambiguousTags[subfield.name] != 1) {
712 continue // ambiguous embedded field
713 }
714
715 if embfield.pointer {
716 subfield.codec = constructEmbeddedStructPointerCodec(embfield.subtype.typ, embfield.unexported, subfield.offset, subfield.codec)
717 subfield.offset = embfield.offset
718 } else {
719 subfield.offset += embfield.offset
720 }
721
722 // To prevent dominant flags more than one level below the embedded one.
723 subfield.tag = false
724
725 // To ensure the order of the fields in the output is the same is in the
726 // struct type.
727 subfield.index = embfield.index
728
729 fields = append(fields, subfield)
730 }
731
732 for i := range fields {
733 name := fields[i].name
734 fields[i].json = encodeKeyFragment(name, 0)
735 fields[i].html = encodeKeyFragment(name, EscapeHTML)
736 }
737
738 sort.Slice(fields, func(i, j int) bool { return fields[i].index < fields[j].index })
739 return fields
740 }
741
742 func encodeKeyFragment(s string, flags AppendFlags) string {
743 b := make([]byte, 1, len(s)+4)
744 b[0] = ','
745 e := encoder{flags: flags}
746 b, _ = e.encodeString(b, unsafe.Pointer(&s))
747 b = append(b, ':')
748 return *(*string)(unsafe.Pointer(&b))
749 }
750
751 func constructPointerCodec(t reflect.Type, seen map[reflect.Type]*structType) codec {
752 e := t.Elem()
753 c := constructCodec(e, seen, true)
754 return codec{
755 encode: constructPointerEncodeFunc(e, c.encode),
756 decode: constructPointerDecodeFunc(e, c.decode),
757 }
758 }
759
760 func constructPointerEncodeFunc(t reflect.Type, encode encodeFunc) encodeFunc {
761 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
762 return e.encodePointer(b, p, t, encode)
763 }
764 }
765
766 func constructPointerDecodeFunc(t reflect.Type, decode decodeFunc) decodeFunc {
767 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
768 return d.decodePointer(b, p, t, decode)
769 }
770 }
771
772 func constructInterfaceCodec(t reflect.Type) codec {
773 return codec{
774 encode: constructMaybeEmptyInterfaceEncoderFunc(t),
775 decode: constructMaybeEmptyInterfaceDecoderFunc(t),
776 }
777 }
778
779 func constructMaybeEmptyInterfaceEncoderFunc(t reflect.Type) encodeFunc {
780 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
781 return e.encodeMaybeEmptyInterface(b, p, t)
782 }
783 }
784
785 func constructMaybeEmptyInterfaceDecoderFunc(t reflect.Type) decodeFunc {
786 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
787 return d.decodeMaybeEmptyInterface(b, p, t)
788 }
789 }
790
791 func constructUnsupportedTypeCodec(t reflect.Type) codec {
792 return codec{
793 encode: constructUnsupportedTypeEncodeFunc(t),
794 decode: constructUnsupportedTypeDecodeFunc(t),
795 }
796 }
797
798 func constructUnsupportedTypeEncodeFunc(t reflect.Type) encodeFunc {
799 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
800 return e.encodeUnsupportedTypeError(b, p, t)
801 }
802 }
803
804 func constructUnsupportedTypeDecodeFunc(t reflect.Type) decodeFunc {
805 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
806 return d.decodeUnmarshalTypeError(b, p, t)
807 }
808 }
809
810 func constructJSONMarshalerEncodeFunc(t reflect.Type, pointer bool) encodeFunc {
811 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
812 return e.encodeJSONMarshaler(b, p, t, pointer)
813 }
814 }
815
816 func constructJSONUnmarshalerDecodeFunc(t reflect.Type, pointer bool) decodeFunc {
817 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
818 return d.decodeJSONUnmarshaler(b, p, t, pointer)
819 }
820 }
821
822 func constructTextMarshalerEncodeFunc(t reflect.Type, pointer bool) encodeFunc {
823 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
824 return e.encodeTextMarshaler(b, p, t, pointer)
825 }
826 }
827
828 func constructTextUnmarshalerDecodeFunc(t reflect.Type, pointer bool) decodeFunc {
829 return func(d decoder, b []byte, p unsafe.Pointer) ([]byte, error) {
830 return d.decodeTextUnmarshaler(b, p, t, pointer)
831 }
832 }
833
834 func constructInlineValueEncodeFunc(encode encodeFunc) encodeFunc {
835 return func(e encoder, b []byte, p unsafe.Pointer) ([]byte, error) {
836 return encode(e, b, noescape(unsafe.Pointer(&p)))
837 }
838 }
839
840 // noescape hides a pointer from escape analysis. noescape is
841 // the identity function but escape analysis doesn't think the
842 // output depends on the input. noescape is inlined and currently
843 // compiles down to zero instructions.
844 // USE CAREFULLY!
845 // This was copied from the runtime; see issues 23382 and 7921.
846 //
847 //go:nosplit
848 func noescape(p unsafe.Pointer) unsafe.Pointer {
849 x := uintptr(p)
850 return unsafe.Pointer(x ^ 0)
851 }
852
853 func alignedSize(t reflect.Type) uintptr {
854 a := t.Align()
855 s := t.Size()
856 return align(uintptr(a), uintptr(s))
857 }
858
859 func align(align, size uintptr) uintptr {
860 if align != 0 && (size%align) != 0 {
861 size = ((size / align) + 1) * align
862 }
863 return size
864 }
865
866 func inlined(t reflect.Type) bool {
867 switch t.Kind() {
868 case reflect.Ptr:
869 return true
870 case reflect.Map:
871 return true
872 case reflect.Struct:
873 return t.NumField() == 1 && inlined(t.Field(0).Type)
874 default:
875 return false
876 }
877 }
878
879 func isValidTag(s string) bool {
880 if s == "" {
881 return false
882 }
883 for _, c := range s {
884 switch {
885 case strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
886 // Backslash and quote chars are reserved, but
887 // otherwise any punctuation chars are allowed
888 // in a tag name.
889 default:
890 if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
891 return false
892 }
893 }
894 }
895 return true
896 }
897
898 func emptyFuncOf(t reflect.Type) emptyFunc {
899 switch t {
900 case bytesType, rawMessageType:
901 return func(p unsafe.Pointer) bool { return (*slice)(p).len == 0 }
902 }
903
904 switch t.Kind() {
905 case reflect.Array:
906 if t.Len() == 0 {
907 return func(unsafe.Pointer) bool { return true }
908 }
909
910 case reflect.Map:
911 return func(p unsafe.Pointer) bool { return reflect.NewAt(t, p).Elem().Len() == 0 }
912
913 case reflect.Slice:
914 return func(p unsafe.Pointer) bool { return (*slice)(p).len == 0 }
915
916 case reflect.String:
917 return func(p unsafe.Pointer) bool { return len(*(*string)(p)) == 0 }
918
919 case reflect.Bool:
920 return func(p unsafe.Pointer) bool { return !*(*bool)(p) }
921
922 case reflect.Int, reflect.Uint:
923 return func(p unsafe.Pointer) bool { return *(*uint)(p) == 0 }
924
925 case reflect.Uintptr:
926 return func(p unsafe.Pointer) bool { return *(*uintptr)(p) == 0 }
927
928 case reflect.Int8, reflect.Uint8:
929 return func(p unsafe.Pointer) bool { return *(*uint8)(p) == 0 }
930
931 case reflect.Int16, reflect.Uint16:
932 return func(p unsafe.Pointer) bool { return *(*uint16)(p) == 0 }
933
934 case reflect.Int32, reflect.Uint32:
935 return func(p unsafe.Pointer) bool { return *(*uint32)(p) == 0 }
936
937 case reflect.Int64, reflect.Uint64:
938 return func(p unsafe.Pointer) bool { return *(*uint64)(p) == 0 }
939
940 case reflect.Float32:
941 return func(p unsafe.Pointer) bool { return *(*float32)(p) == 0 }
942
943 case reflect.Float64:
944 return func(p unsafe.Pointer) bool { return *(*float64)(p) == 0 }
945
946 case reflect.Ptr:
947 return func(p unsafe.Pointer) bool { return *(*unsafe.Pointer)(p) == nil }
948
949 case reflect.Interface:
950 return func(p unsafe.Pointer) bool { return (*iface)(p).ptr == nil }
951 }
952
953 return func(unsafe.Pointer) bool { return false }
954 }
955
956 type iface struct {
957 typ unsafe.Pointer
958 ptr unsafe.Pointer
959 }
960
961 type slice struct {
962 data unsafe.Pointer
963 len int
964 cap int
965 }
966
967 type structType struct {
968 fields []structField
969 fieldsIndex map[string]*structField
970 ficaseIndex map[string]*structField
971 keyset []byte
972 typ reflect.Type
973 }
974
975 type structField struct {
976 codec codec
977 offset uintptr
978 empty emptyFunc
979 tag bool
980 omitempty bool
981 json string
982 html string
983 name string
984 typ reflect.Type
985 zero reflect.Value
986 index int
987 }
988
989 func unmarshalTypeError(b []byte, t reflect.Type) error {
990 return &UnmarshalTypeError{Value: strconv.Quote(prefix(b)), Type: t}
991 }
992
993 func unmarshalOverflow(b []byte, t reflect.Type) error {
994 return &UnmarshalTypeError{Value: "number " + prefix(b) + " overflows", Type: t}
995 }
996
997 func unexpectedEOF(b []byte) error {
998 return syntaxError(b, "unexpected end of JSON input")
999 }
1000
1001 var syntaxErrorMsgOffset = ^uintptr(0)
1002
1003 func init() {
1004 t := reflect.TypeOf(SyntaxError{})
1005 for i := range t.NumField() {
1006 if f := t.Field(i); f.Type.Kind() == reflect.String {
1007 syntaxErrorMsgOffset = f.Offset
1008 }
1009 }
1010 }
1011
1012 func syntaxError(b []byte, msg string, args ...any) error {
1013 e := new(SyntaxError)
1014 i := syntaxErrorMsgOffset
1015 if i != ^uintptr(0) {
1016 s := "json: " + fmt.Sprintf(msg, args...) + ": " + prefix(b)
1017 p := unsafe.Pointer(e)
1018 // Hack to set the unexported `msg` field.
1019 *(*string)(unsafe.Pointer(uintptr(p) + i)) = s
1020 }
1021 return e
1022 }
1023
1024 func objectKeyError(b []byte, err error) ([]byte, error) {
1025 if len(b) == 0 {
1026 return nil, unexpectedEOF(b)
1027 }
1028 switch err.(type) {
1029 case *UnmarshalTypeError:
1030 err = syntaxError(b, "invalid character '%c' looking for beginning of object key", b[0])
1031 }
1032 return b, err
1033 }
1034
1035 func prefix(b []byte) string {
1036 if len(b) < 32 {
1037 return string(b)
1038 }
1039 return string(b[:32]) + "..."
1040 }
1041
1042 func intStringsAreSorted(i0, i1 int64) bool {
1043 var b0, b1 [32]byte
1044 return string(strconv.AppendInt(b0[:0], i0, 10)) < string(strconv.AppendInt(b1[:0], i1, 10))
1045 }
1046
1047 func uintStringsAreSorted(u0, u1 uint64) bool {
1048 var b0, b1 [32]byte
1049 return string(strconv.AppendUint(b0[:0], u0, 10)) < string(strconv.AppendUint(b1[:0], u1, 10))
1050 }
1051
1052 func stringToBytes(s string) []byte {
1053 return *(*[]byte)(unsafe.Pointer(&sliceHeader{
1054 Data: *(*unsafe.Pointer)(unsafe.Pointer(&s)),
1055 Len: len(s),
1056 Cap: len(s),
1057 }))
1058 }
1059
1060 type sliceHeader struct {
1061 Data unsafe.Pointer
1062 Len int
1063 Cap int
1064 }
1065
1066 var (
1067 nullType = reflect.TypeOf(nil)
1068 boolType = reflect.TypeOf(false)
1069
1070 intType = reflect.TypeOf(int(0))
1071 int8Type = reflect.TypeOf(int8(0))
1072 int16Type = reflect.TypeOf(int16(0))
1073 int32Type = reflect.TypeOf(int32(0))
1074 int64Type = reflect.TypeOf(int64(0))
1075
1076 uintType = reflect.TypeOf(uint(0))
1077 uint8Type = reflect.TypeOf(uint8(0))
1078 uint16Type = reflect.TypeOf(uint16(0))
1079 uint32Type = reflect.TypeOf(uint32(0))
1080 uint64Type = reflect.TypeOf(uint64(0))
1081 uintptrType = reflect.TypeOf(uintptr(0))
1082
1083 float32Type = reflect.TypeOf(float32(0))
1084 float64Type = reflect.TypeOf(float64(0))
1085
1086 bigIntType = reflect.TypeOf(new(big.Int))
1087 numberType = reflect.TypeOf(json.Number(""))
1088 stringType = reflect.TypeOf("")
1089 stringsType = reflect.TypeOf([]string(nil))
1090 bytesType = reflect.TypeOf(([]byte)(nil))
1091 durationType = reflect.TypeOf(time.Duration(0))
1092 timeType = reflect.TypeOf(time.Time{})
1093 rawMessageType = reflect.TypeOf(RawMessage(nil))
1094
1095 numberPtrType = reflect.PointerTo(numberType)
1096 durationPtrType = reflect.PointerTo(durationType)
1097 timePtrType = reflect.PointerTo(timeType)
1098 rawMessagePtrType = reflect.PointerTo(rawMessageType)
1099
1100 sliceInterfaceType = reflect.TypeOf(([]any)(nil))
1101 sliceStringType = reflect.TypeOf(([]any)(nil))
1102 mapStringInterfaceType = reflect.TypeOf((map[string]any)(nil))
1103 mapStringRawMessageType = reflect.TypeOf((map[string]RawMessage)(nil))
1104 mapStringStringType = reflect.TypeOf((map[string]string)(nil))
1105 mapStringStringSliceType = reflect.TypeOf((map[string][]string)(nil))
1106 mapStringBoolType = reflect.TypeOf((map[string]bool)(nil))
1107
1108 interfaceType = reflect.TypeOf((*any)(nil)).Elem()
1109 jsonMarshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
1110 jsonUnmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
1111 textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
1112 textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
1113
1114 bigIntDecoder = constructJSONUnmarshalerDecodeFunc(bigIntType, false)
1115 )
1116
1117 // =============================================================================
1118 // Copyright 2009 The Go Authors. All rights reserved.
1119 // Use of this source code is governed by a BSD-style
1120 // license that can be found in the LICENSE file.
1121
1122 // appendDuration appends a human-readable representation of d to b.
1123 //
1124 // The function copies the implementation of time.Duration.String but prevents
1125 // Go from making a dynamic memory allocation on the returned value.
1126 func appendDuration(b []byte, d time.Duration) []byte {
1127 // Largest time is 2540400h10m10.000000000s
1128 var buf [32]byte
1129 w := len(buf)
1130
1131 u := uint64(d)
1132 neg := d < 0
1133 if neg {
1134 u = -u
1135 }
1136
1137 if u < uint64(time.Second) {
1138 // Special case: if duration is smaller than a second,
1139 // use smaller units, like 1.2ms
1140 var prec int
1141 w--
1142 buf[w] = 's'
1143 w--
1144 switch {
1145 case u == 0:
1146 return append(b, '0', 's')
1147 case u < uint64(time.Microsecond):
1148 // print nanoseconds
1149 prec = 0
1150 buf[w] = 'n'
1151 case u < uint64(time.Millisecond):
1152 // print microseconds
1153 prec = 3
1154 // U+00B5 'µ' micro sign == 0xC2 0xB5
1155 w-- // Need room for two bytes.
1156 copy(buf[w:], "µ")
1157 default:
1158 // print milliseconds
1159 prec = 6
1160 buf[w] = 'm'
1161 }
1162 w, u = fmtFrac(buf[:w], u, prec)
1163 w = fmtInt(buf[:w], u)
1164 } else {
1165 w--
1166 buf[w] = 's'
1167
1168 w, u = fmtFrac(buf[:w], u, 9)
1169
1170 // u is now integer seconds
1171 w = fmtInt(buf[:w], u%60)
1172 u /= 60
1173
1174 // u is now integer minutes
1175 if u > 0 {
1176 w--
1177 buf[w] = 'm'
1178 w = fmtInt(buf[:w], u%60)
1179 u /= 60
1180
1181 // u is now integer hours
1182 // Stop at hours because days can be different lengths.
1183 if u > 0 {
1184 w--
1185 buf[w] = 'h'
1186 w = fmtInt(buf[:w], u)
1187 }
1188 }
1189 }
1190
1191 if neg {
1192 w--
1193 buf[w] = '-'
1194 }
1195
1196 return append(b, buf[w:]...)
1197 }
1198
1199 // fmtFrac formats the fraction of v/10**prec (e.g., ".12345") into the
1200 // tail of buf, omitting trailing zeros. it omits the decimal
1201 // point too when the fraction is 0. It returns the index where the
1202 // output bytes begin and the value v/10**prec.
1203 func fmtFrac(buf []byte, v uint64, prec int) (nw int, nv uint64) {
1204 // Omit trailing zeros up to and including decimal point.
1205 w := len(buf)
1206 print := false
1207 for range prec {
1208 digit := v % 10
1209 print = print || digit != 0
1210 if print {
1211 w--
1212 buf[w] = byte(digit) + '0'
1213 }
1214 v /= 10
1215 }
1216 if print {
1217 w--
1218 buf[w] = '.'
1219 }
1220 return w, v
1221 }
1222
1223 // fmtInt formats v into the tail of buf.
1224 // It returns the index where the output begins.
1225 func fmtInt(buf []byte, v uint64) int {
1226 w := len(buf)
1227 if v == 0 {
1228 w--
1229 buf[w] = '0'
1230 } else {
1231 for v > 0 {
1232 w--
1233 buf[w] = byte(v%10) + '0'
1234 v /= 10
1235 }
1236 }
1237 return w
1238 }
1239
1240 // =============================================================================