github.com/segmentio/encoding@v0.3.6/json/codec.go (about)

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