Black Lives Matter. Support the Equal Justice Initiative.

Source file src/encoding/json/encode.go

Documentation: encoding/json

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package json implements encoding and decoding of JSON as defined in
     6  // RFC 7159. The mapping between JSON and Go values is described
     7  // in the documentation for the Marshal and Unmarshal functions.
     8  //
     9  // See "JSON and Go" for an introduction to this package:
    10  // https://golang.org/doc/articles/json_and_go.html
    11  package json
    12  
    13  import (
    14  	"bytes"
    15  	"encoding"
    16  	"encoding/base64"
    17  	"fmt"
    18  	"math"
    19  	"reflect"
    20  	"sort"
    21  	"strconv"
    22  	"strings"
    23  	"sync"
    24  	"unicode"
    25  	"unicode/utf8"
    26  )
    27  
    28  // Marshal returns the JSON encoding of v.
    29  //
    30  // Marshal traverses the value v recursively.
    31  // If an encountered value implements the Marshaler interface
    32  // and is not a nil pointer, Marshal calls its MarshalJSON method
    33  // to produce JSON. If no MarshalJSON method is present but the
    34  // value implements encoding.TextMarshaler instead, Marshal calls
    35  // its MarshalText method and encodes the result as a JSON string.
    36  // The nil pointer exception is not strictly necessary
    37  // but mimics a similar, necessary exception in the behavior of
    38  // UnmarshalJSON.
    39  //
    40  // Otherwise, Marshal uses the following type-dependent default encodings:
    41  //
    42  // Boolean values encode as JSON booleans.
    43  //
    44  // Floating point, integer, and Number values encode as JSON numbers.
    45  //
    46  // String values encode as JSON strings coerced to valid UTF-8,
    47  // replacing invalid bytes with the Unicode replacement rune.
    48  // So that the JSON will be safe to embed inside HTML <script> tags,
    49  // the string is encoded using HTMLEscape,
    50  // which replaces "<", ">", "&", U+2028, and U+2029 are escaped
    51  // to "\u003c","\u003e", "\u0026", "\u2028", and "\u2029".
    52  // This replacement can be disabled when using an Encoder,
    53  // by calling SetEscapeHTML(false).
    54  //
    55  // Array and slice values encode as JSON arrays, except that
    56  // []byte encodes as a base64-encoded string, and a nil slice
    57  // encodes as the null JSON value.
    58  //
    59  // Struct values encode as JSON objects.
    60  // Each exported struct field becomes a member of the object, using the
    61  // field name as the object key, unless the field is omitted for one of the
    62  // reasons given below.
    63  //
    64  // The encoding of each struct field can be customized by the format string
    65  // stored under the "json" key in the struct field's tag.
    66  // The format string gives the name of the field, possibly followed by a
    67  // comma-separated list of options. The name may be empty in order to
    68  // specify options without overriding the default field name.
    69  //
    70  // The "omitempty" option specifies that the field should be omitted
    71  // from the encoding if the field has an empty value, defined as
    72  // false, 0, a nil pointer, a nil interface value, and any empty array,
    73  // slice, map, or string.
    74  //
    75  // As a special case, if the field tag is "-", the field is always omitted.
    76  // Note that a field with name "-" can still be generated using the tag "-,".
    77  //
    78  // Examples of struct field tags and their meanings:
    79  //
    80  //   // Field appears in JSON as key "myName".
    81  //   Field int `json:"myName"`
    82  //
    83  //   // Field appears in JSON as key "myName" and
    84  //   // the field is omitted from the object if its value is empty,
    85  //   // as defined above.
    86  //   Field int `json:"myName,omitempty"`
    87  //
    88  //   // Field appears in JSON as key "Field" (the default), but
    89  //   // the field is skipped if empty.
    90  //   // Note the leading comma.
    91  //   Field int `json:",omitempty"`
    92  //
    93  //   // Field is ignored by this package.
    94  //   Field int `json:"-"`
    95  //
    96  //   // Field appears in JSON as key "-".
    97  //   Field int `json:"-,"`
    98  //
    99  // The "string" option signals that a field is stored as JSON inside a
   100  // JSON-encoded string. It applies only to fields of string, floating point,
   101  // integer, or boolean types. This extra level of encoding is sometimes used
   102  // when communicating with JavaScript programs:
   103  //
   104  //    Int64String int64 `json:",string"`
   105  //
   106  // The key name will be used if it's a non-empty string consisting of
   107  // only Unicode letters, digits, and ASCII punctuation except quotation
   108  // marks, backslash, and comma.
   109  //
   110  // Anonymous struct fields are usually marshaled as if their inner exported fields
   111  // were fields in the outer struct, subject to the usual Go visibility rules amended
   112  // as described in the next paragraph.
   113  // An anonymous struct field with a name given in its JSON tag is treated as
   114  // having that name, rather than being anonymous.
   115  // An anonymous struct field of interface type is treated the same as having
   116  // that type as its name, rather than being anonymous.
   117  //
   118  // The Go visibility rules for struct fields are amended for JSON when
   119  // deciding which field to marshal or unmarshal. If there are
   120  // multiple fields at the same level, and that level is the least
   121  // nested (and would therefore be the nesting level selected by the
   122  // usual Go rules), the following extra rules apply:
   123  //
   124  // 1) Of those fields, if any are JSON-tagged, only tagged fields are considered,
   125  // even if there are multiple untagged fields that would otherwise conflict.
   126  //
   127  // 2) If there is exactly one field (tagged or not according to the first rule), that is selected.
   128  //
   129  // 3) Otherwise there are multiple fields, and all are ignored; no error occurs.
   130  //
   131  // Handling of anonymous struct fields is new in Go 1.1.
   132  // Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of
   133  // an anonymous struct field in both current and earlier versions, give the field
   134  // a JSON tag of "-".
   135  //
   136  // Map values encode as JSON objects. The map's key type must either be a
   137  // string, an integer type, or implement encoding.TextMarshaler. The map keys
   138  // are sorted and used as JSON object keys by applying the following rules,
   139  // subject to the UTF-8 coercion described for string values above:
   140  //   - keys of any string type are used directly
   141  //   - encoding.TextMarshalers are marshaled
   142  //   - integer keys are converted to strings
   143  //
   144  // Pointer values encode as the value pointed to.
   145  // A nil pointer encodes as the null JSON value.
   146  //
   147  // Interface values encode as the value contained in the interface.
   148  // A nil interface value encodes as the null JSON value.
   149  //
   150  // Channel, complex, and function values cannot be encoded in JSON.
   151  // Attempting to encode such a value causes Marshal to return
   152  // an UnsupportedTypeError.
   153  //
   154  // JSON cannot represent cyclic data structures and Marshal does not
   155  // handle them. Passing cyclic structures to Marshal will result in
   156  // an error.
   157  //
   158  func Marshal(v interface{}) ([]byte, error) {
   159  	e := newEncodeState()
   160  
   161  	err := e.marshal(v, encOpts{escapeHTML: true})
   162  	if err != nil {
   163  		return nil, err
   164  	}
   165  	buf := append([]byte(nil), e.Bytes()...)
   166  
   167  	encodeStatePool.Put(e)
   168  
   169  	return buf, nil
   170  }
   171  
   172  // MarshalIndent is like Marshal but applies Indent to format the output.
   173  // Each JSON element in the output will begin on a new line beginning with prefix
   174  // followed by one or more copies of indent according to the indentation nesting.
   175  func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) {
   176  	b, err := Marshal(v)
   177  	if err != nil {
   178  		return nil, err
   179  	}
   180  	var buf bytes.Buffer
   181  	err = Indent(&buf, b, prefix, indent)
   182  	if err != nil {
   183  		return nil, err
   184  	}
   185  	return buf.Bytes(), nil
   186  }
   187  
   188  // HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029
   189  // characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029
   190  // so that the JSON will be safe to embed inside HTML <script> tags.
   191  // For historical reasons, web browsers don't honor standard HTML
   192  // escaping within <script> tags, so an alternative JSON encoding must
   193  // be used.
   194  func HTMLEscape(dst *bytes.Buffer, src []byte) {
   195  	// The characters can only appear in string literals,
   196  	// so just scan the string one byte at a time.
   197  	start := 0
   198  	for i, c := range src {
   199  		if c == '<' || c == '>' || c == '&' {
   200  			if start < i {
   201  				dst.Write(src[start:i])
   202  			}
   203  			dst.WriteString(`\u00`)
   204  			dst.WriteByte(hex[c>>4])
   205  			dst.WriteByte(hex[c&0xF])
   206  			start = i + 1
   207  		}
   208  		// Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
   209  		if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
   210  			if start < i {
   211  				dst.Write(src[start:i])
   212  			}
   213  			dst.WriteString(`\u202`)
   214  			dst.WriteByte(hex[src[i+2]&0xF])
   215  			start = i + 3
   216  		}
   217  	}
   218  	if start < len(src) {
   219  		dst.Write(src[start:])
   220  	}
   221  }
   222  
   223  // Marshaler is the interface implemented by types that
   224  // can marshal themselves into valid JSON.
   225  type Marshaler interface {
   226  	MarshalJSON() ([]byte, error)
   227  }
   228  
   229  // An UnsupportedTypeError is returned by Marshal when attempting
   230  // to encode an unsupported value type.
   231  type UnsupportedTypeError struct {
   232  	Type reflect.Type
   233  }
   234  
   235  func (e *UnsupportedTypeError) Error() string {
   236  	return "json: unsupported type: " + e.Type.String()
   237  }
   238  
   239  type UnsupportedValueError struct {
   240  	Value reflect.Value
   241  	Str   string
   242  }
   243  
   244  func (e *UnsupportedValueError) Error() string {
   245  	return "json: unsupported value: " + e.Str
   246  }
   247  
   248  // Before Go 1.2, an InvalidUTF8Error was returned by Marshal when
   249  // attempting to encode a string value with invalid UTF-8 sequences.
   250  // As of Go 1.2, Marshal instead coerces the string to valid UTF-8 by
   251  // replacing invalid bytes with the Unicode replacement rune U+FFFD.
   252  //
   253  // Deprecated: No longer used; kept for compatibility.
   254  type InvalidUTF8Error struct {
   255  	S string // the whole string value that caused the error
   256  }
   257  
   258  func (e *InvalidUTF8Error) Error() string {
   259  	return "json: invalid UTF-8 in string: " + strconv.Quote(e.S)
   260  }
   261  
   262  // A MarshalerError represents an error from calling a MarshalJSON or MarshalText method.
   263  type MarshalerError struct {
   264  	Type       reflect.Type
   265  	Err        error
   266  	sourceFunc string
   267  }
   268  
   269  func (e *MarshalerError) Error() string {
   270  	srcFunc := e.sourceFunc
   271  	if srcFunc == "" {
   272  		srcFunc = "MarshalJSON"
   273  	}
   274  	return "json: error calling " + srcFunc +
   275  		" for type " + e.Type.String() +
   276  		": " + e.Err.Error()
   277  }
   278  
   279  // Unwrap returns the underlying error.
   280  func (e *MarshalerError) Unwrap() error { return e.Err }
   281  
   282  var hex = "0123456789abcdef"
   283  
   284  // An encodeState encodes JSON into a bytes.Buffer.
   285  type encodeState struct {
   286  	bytes.Buffer // accumulated output
   287  	scratch      [64]byte
   288  
   289  	// Keep track of what pointers we've seen in the current recursive call
   290  	// path, to avoid cycles that could lead to a stack overflow. Only do
   291  	// the relatively expensive map operations if ptrLevel is larger than
   292  	// startDetectingCyclesAfter, so that we skip the work if we're within a
   293  	// reasonable amount of nested pointers deep.
   294  	ptrLevel uint
   295  	ptrSeen  map[interface{}]struct{}
   296  }
   297  
   298  const startDetectingCyclesAfter = 1000
   299  
   300  var encodeStatePool sync.Pool
   301  
   302  func newEncodeState() *encodeState {
   303  	if v := encodeStatePool.Get(); v != nil {
   304  		e := v.(*encodeState)
   305  		e.Reset()
   306  		if len(e.ptrSeen) > 0 {
   307  			panic("ptrEncoder.encode should have emptied ptrSeen via defers")
   308  		}
   309  		e.ptrLevel = 0
   310  		return e
   311  	}
   312  	return &encodeState{ptrSeen: make(map[interface{}]struct{})}
   313  }
   314  
   315  // jsonError is an error wrapper type for internal use only.
   316  // Panics with errors are wrapped in jsonError so that the top-level recover
   317  // can distinguish intentional panics from this package.
   318  type jsonError struct{ error }
   319  
   320  func (e *encodeState) marshal(v interface{}, opts encOpts) (err error) {
   321  	defer func() {
   322  		if r := recover(); r != nil {
   323  			if je, ok := r.(jsonError); ok {
   324  				err = je.error
   325  			} else {
   326  				panic(r)
   327  			}
   328  		}
   329  	}()
   330  	e.reflectValue(reflect.ValueOf(v), opts)
   331  	return nil
   332  }
   333  
   334  // error aborts the encoding by panicking with err wrapped in jsonError.
   335  func (e *encodeState) error(err error) {
   336  	panic(jsonError{err})
   337  }
   338  
   339  func isEmptyValue(v reflect.Value) bool {
   340  	switch v.Kind() {
   341  	case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
   342  		return v.Len() == 0
   343  	case reflect.Bool:
   344  		return !v.Bool()
   345  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   346  		return v.Int() == 0
   347  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   348  		return v.Uint() == 0
   349  	case reflect.Float32, reflect.Float64:
   350  		return v.Float() == 0
   351  	case reflect.Interface, reflect.Ptr:
   352  		return v.IsNil()
   353  	}
   354  	return false
   355  }
   356  
   357  func (e *encodeState) reflectValue(v reflect.Value, opts encOpts) {
   358  	valueEncoder(v)(e, v, opts)
   359  }
   360  
   361  type encOpts struct {
   362  	// quoted causes primitive fields to be encoded inside JSON strings.
   363  	quoted bool
   364  	// escapeHTML causes '<', '>', and '&' to be escaped in JSON strings.
   365  	escapeHTML bool
   366  }
   367  
   368  type encoderFunc func(e *encodeState, v reflect.Value, opts encOpts)
   369  
   370  var encoderCache sync.Map // map[reflect.Type]encoderFunc
   371  
   372  func valueEncoder(v reflect.Value) encoderFunc {
   373  	if !v.IsValid() {
   374  		return invalidValueEncoder
   375  	}
   376  	return typeEncoder(v.Type())
   377  }
   378  
   379  func typeEncoder(t reflect.Type) encoderFunc {
   380  	if fi, ok := encoderCache.Load(t); ok {
   381  		return fi.(encoderFunc)
   382  	}
   383  
   384  	// To deal with recursive types, populate the map with an
   385  	// indirect func before we build it. This type waits on the
   386  	// real func (f) to be ready and then calls it. This indirect
   387  	// func is only used for recursive types.
   388  	var (
   389  		wg sync.WaitGroup
   390  		f  encoderFunc
   391  	)
   392  	wg.Add(1)
   393  	fi, loaded := encoderCache.LoadOrStore(t, encoderFunc(func(e *encodeState, v reflect.Value, opts encOpts) {
   394  		wg.Wait()
   395  		f(e, v, opts)
   396  	}))
   397  	if loaded {
   398  		return fi.(encoderFunc)
   399  	}
   400  
   401  	// Compute the real encoder and replace the indirect func with it.
   402  	f = newTypeEncoder(t, true)
   403  	wg.Done()
   404  	encoderCache.Store(t, f)
   405  	return f
   406  }
   407  
   408  var (
   409  	marshalerType     = reflect.TypeOf((*Marshaler)(nil)).Elem()
   410  	textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
   411  )
   412  
   413  // newTypeEncoder constructs an encoderFunc for a type.
   414  // The returned encoder only checks CanAddr when allowAddr is true.
   415  func newTypeEncoder(t reflect.Type, allowAddr bool) encoderFunc {
   416  	// If we have a non-pointer value whose type implements
   417  	// Marshaler with a value receiver, then we're better off taking
   418  	// the address of the value - otherwise we end up with an
   419  	// allocation as we cast the value to an interface.
   420  	if t.Kind() != reflect.Ptr && allowAddr && reflect.PtrTo(t).Implements(marshalerType) {
   421  		return newCondAddrEncoder(addrMarshalerEncoder, newTypeEncoder(t, false))
   422  	}
   423  	if t.Implements(marshalerType) {
   424  		return marshalerEncoder
   425  	}
   426  	if t.Kind() != reflect.Ptr && allowAddr && reflect.PtrTo(t).Implements(textMarshalerType) {
   427  		return newCondAddrEncoder(addrTextMarshalerEncoder, newTypeEncoder(t, false))
   428  	}
   429  	if t.Implements(textMarshalerType) {
   430  		return textMarshalerEncoder
   431  	}
   432  
   433  	switch t.Kind() {
   434  	case reflect.Bool:
   435  		return boolEncoder
   436  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   437  		return intEncoder
   438  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   439  		return uintEncoder
   440  	case reflect.Float32:
   441  		return float32Encoder
   442  	case reflect.Float64:
   443  		return float64Encoder
   444  	case reflect.String:
   445  		return stringEncoder
   446  	case reflect.Interface:
   447  		return interfaceEncoder
   448  	case reflect.Struct:
   449  		return newStructEncoder(t)
   450  	case reflect.Map:
   451  		return newMapEncoder(t)
   452  	case reflect.Slice:
   453  		return newSliceEncoder(t)
   454  	case reflect.Array:
   455  		return newArrayEncoder(t)
   456  	case reflect.Ptr:
   457  		return newPtrEncoder(t)
   458  	default:
   459  		return unsupportedTypeEncoder
   460  	}
   461  }
   462  
   463  func invalidValueEncoder(e *encodeState, v reflect.Value, _ encOpts) {
   464  	e.WriteString("null")
   465  }
   466  
   467  func marshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   468  	if v.Kind() == reflect.Ptr && v.IsNil() {
   469  		e.WriteString("null")
   470  		return
   471  	}
   472  	m, ok := v.Interface().(Marshaler)
   473  	if !ok {
   474  		e.WriteString("null")
   475  		return
   476  	}
   477  	b, err := m.MarshalJSON()
   478  	if err == nil {
   479  		// copy JSON into buffer, checking validity.
   480  		err = compact(&e.Buffer, b, opts.escapeHTML)
   481  	}
   482  	if err != nil {
   483  		e.error(&MarshalerError{v.Type(), err, "MarshalJSON"})
   484  	}
   485  }
   486  
   487  func addrMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   488  	va := v.Addr()
   489  	if va.IsNil() {
   490  		e.WriteString("null")
   491  		return
   492  	}
   493  	m := va.Interface().(Marshaler)
   494  	b, err := m.MarshalJSON()
   495  	if err == nil {
   496  		// copy JSON into buffer, checking validity.
   497  		err = compact(&e.Buffer, b, opts.escapeHTML)
   498  	}
   499  	if err != nil {
   500  		e.error(&MarshalerError{v.Type(), err, "MarshalJSON"})
   501  	}
   502  }
   503  
   504  func textMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   505  	if v.Kind() == reflect.Ptr && v.IsNil() {
   506  		e.WriteString("null")
   507  		return
   508  	}
   509  	m, ok := v.Interface().(encoding.TextMarshaler)
   510  	if !ok {
   511  		e.WriteString("null")
   512  		return
   513  	}
   514  	b, err := m.MarshalText()
   515  	if err != nil {
   516  		e.error(&MarshalerError{v.Type(), err, "MarshalText"})
   517  	}
   518  	e.stringBytes(b, opts.escapeHTML)
   519  }
   520  
   521  func addrTextMarshalerEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   522  	va := v.Addr()
   523  	if va.IsNil() {
   524  		e.WriteString("null")
   525  		return
   526  	}
   527  	m := va.Interface().(encoding.TextMarshaler)
   528  	b, err := m.MarshalText()
   529  	if err != nil {
   530  		e.error(&MarshalerError{v.Type(), err, "MarshalText"})
   531  	}
   532  	e.stringBytes(b, opts.escapeHTML)
   533  }
   534  
   535  func boolEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   536  	if opts.quoted {
   537  		e.WriteByte('"')
   538  	}
   539  	if v.Bool() {
   540  		e.WriteString("true")
   541  	} else {
   542  		e.WriteString("false")
   543  	}
   544  	if opts.quoted {
   545  		e.WriteByte('"')
   546  	}
   547  }
   548  
   549  func intEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   550  	b := strconv.AppendInt(e.scratch[:0], v.Int(), 10)
   551  	if opts.quoted {
   552  		e.WriteByte('"')
   553  	}
   554  	e.Write(b)
   555  	if opts.quoted {
   556  		e.WriteByte('"')
   557  	}
   558  }
   559  
   560  func uintEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   561  	b := strconv.AppendUint(e.scratch[:0], v.Uint(), 10)
   562  	if opts.quoted {
   563  		e.WriteByte('"')
   564  	}
   565  	e.Write(b)
   566  	if opts.quoted {
   567  		e.WriteByte('"')
   568  	}
   569  }
   570  
   571  type floatEncoder int // number of bits
   572  
   573  func (bits floatEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   574  	f := v.Float()
   575  	if math.IsInf(f, 0) || math.IsNaN(f) {
   576  		e.error(&UnsupportedValueError{v, strconv.FormatFloat(f, 'g', -1, int(bits))})
   577  	}
   578  
   579  	// Convert as if by ES6 number to string conversion.
   580  	// This matches most other JSON generators.
   581  	// See golang.org/issue/6384 and golang.org/issue/14135.
   582  	// Like fmt %g, but the exponent cutoffs are different
   583  	// and exponents themselves are not padded to two digits.
   584  	b := e.scratch[:0]
   585  	abs := math.Abs(f)
   586  	fmt := byte('f')
   587  	// Note: Must use float32 comparisons for underlying float32 value to get precise cutoffs right.
   588  	if abs != 0 {
   589  		if bits == 64 && (abs < 1e-6 || abs >= 1e21) || bits == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) {
   590  			fmt = 'e'
   591  		}
   592  	}
   593  	b = strconv.AppendFloat(b, f, fmt, -1, int(bits))
   594  	if fmt == 'e' {
   595  		// clean up e-09 to e-9
   596  		n := len(b)
   597  		if n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' {
   598  			b[n-2] = b[n-1]
   599  			b = b[:n-1]
   600  		}
   601  	}
   602  
   603  	if opts.quoted {
   604  		e.WriteByte('"')
   605  	}
   606  	e.Write(b)
   607  	if opts.quoted {
   608  		e.WriteByte('"')
   609  	}
   610  }
   611  
   612  var (
   613  	float32Encoder = (floatEncoder(32)).encode
   614  	float64Encoder = (floatEncoder(64)).encode
   615  )
   616  
   617  func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   618  	if v.Type() == numberType {
   619  		numStr := v.String()
   620  		// In Go1.5 the empty string encodes to "0", while this is not a valid number literal
   621  		// we keep compatibility so check validity after this.
   622  		if numStr == "" {
   623  			numStr = "0" // Number's zero-val
   624  		}
   625  		if !isValidNumber(numStr) {
   626  			e.error(fmt.Errorf("json: invalid number literal %q", numStr))
   627  		}
   628  		if opts.quoted {
   629  			e.WriteByte('"')
   630  		}
   631  		e.WriteString(numStr)
   632  		if opts.quoted {
   633  			e.WriteByte('"')
   634  		}
   635  		return
   636  	}
   637  	if opts.quoted {
   638  		e2 := newEncodeState()
   639  		// Since we encode the string twice, we only need to escape HTML
   640  		// the first time.
   641  		e2.string(v.String(), opts.escapeHTML)
   642  		e.stringBytes(e2.Bytes(), false)
   643  		encodeStatePool.Put(e2)
   644  	} else {
   645  		e.string(v.String(), opts.escapeHTML)
   646  	}
   647  }
   648  
   649  // isValidNumber reports whether s is a valid JSON number literal.
   650  func isValidNumber(s string) bool {
   651  	// This function implements the JSON numbers grammar.
   652  	// See https://tools.ietf.org/html/rfc7159#section-6
   653  	// and https://www.json.org/img/number.png
   654  
   655  	if s == "" {
   656  		return false
   657  	}
   658  
   659  	// Optional -
   660  	if s[0] == '-' {
   661  		s = s[1:]
   662  		if s == "" {
   663  			return false
   664  		}
   665  	}
   666  
   667  	// Digits
   668  	switch {
   669  	default:
   670  		return false
   671  
   672  	case s[0] == '0':
   673  		s = s[1:]
   674  
   675  	case '1' <= s[0] && s[0] <= '9':
   676  		s = s[1:]
   677  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   678  			s = s[1:]
   679  		}
   680  	}
   681  
   682  	// . followed by 1 or more digits.
   683  	if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' {
   684  		s = s[2:]
   685  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   686  			s = s[1:]
   687  		}
   688  	}
   689  
   690  	// e or E followed by an optional - or + and
   691  	// 1 or more digits.
   692  	if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') {
   693  		s = s[1:]
   694  		if s[0] == '+' || s[0] == '-' {
   695  			s = s[1:]
   696  			if s == "" {
   697  				return false
   698  			}
   699  		}
   700  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   701  			s = s[1:]
   702  		}
   703  	}
   704  
   705  	// Make sure we are at the end.
   706  	return s == ""
   707  }
   708  
   709  func interfaceEncoder(e *encodeState, v reflect.Value, opts encOpts) {
   710  	if v.IsNil() {
   711  		e.WriteString("null")
   712  		return
   713  	}
   714  	e.reflectValue(v.Elem(), opts)
   715  }
   716  
   717  func unsupportedTypeEncoder(e *encodeState, v reflect.Value, _ encOpts) {
   718  	e.error(&UnsupportedTypeError{v.Type()})
   719  }
   720  
   721  type structEncoder struct {
   722  	fields structFields
   723  }
   724  
   725  type structFields struct {
   726  	list      []field
   727  	nameIndex map[string]int
   728  }
   729  
   730  func (se structEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   731  	next := byte('{')
   732  FieldLoop:
   733  	for i := range se.fields.list {
   734  		f := &se.fields.list[i]
   735  
   736  		// Find the nested struct field by following f.index.
   737  		fv := v
   738  		for _, i := range f.index {
   739  			if fv.Kind() == reflect.Ptr {
   740  				if fv.IsNil() {
   741  					continue FieldLoop
   742  				}
   743  				fv = fv.Elem()
   744  			}
   745  			fv = fv.Field(i)
   746  		}
   747  
   748  		if f.omitEmpty && isEmptyValue(fv) {
   749  			continue
   750  		}
   751  		e.WriteByte(next)
   752  		next = ','
   753  		if opts.escapeHTML {
   754  			e.WriteString(f.nameEscHTML)
   755  		} else {
   756  			e.WriteString(f.nameNonEsc)
   757  		}
   758  		opts.quoted = f.quoted
   759  		f.encoder(e, fv, opts)
   760  	}
   761  	if next == '{' {
   762  		e.WriteString("{}")
   763  	} else {
   764  		e.WriteByte('}')
   765  	}
   766  }
   767  
   768  func newStructEncoder(t reflect.Type) encoderFunc {
   769  	se := structEncoder{fields: cachedTypeFields(t)}
   770  	return se.encode
   771  }
   772  
   773  type mapEncoder struct {
   774  	elemEnc encoderFunc
   775  }
   776  
   777  func (me mapEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   778  	if v.IsNil() {
   779  		e.WriteString("null")
   780  		return
   781  	}
   782  	e.WriteByte('{')
   783  
   784  	// Extract and sort the keys.
   785  	keys := v.MapKeys()
   786  	sv := make([]reflectWithString, len(keys))
   787  	for i, v := range keys {
   788  		sv[i].v = v
   789  		if err := sv[i].resolve(); err != nil {
   790  			e.error(fmt.Errorf("json: encoding error for type %q: %q", v.Type().String(), err.Error()))
   791  		}
   792  	}
   793  	sort.Slice(sv, func(i, j int) bool { return sv[i].s < sv[j].s })
   794  
   795  	for i, kv := range sv {
   796  		if i > 0 {
   797  			e.WriteByte(',')
   798  		}
   799  		e.string(kv.s, opts.escapeHTML)
   800  		e.WriteByte(':')
   801  		me.elemEnc(e, v.MapIndex(kv.v), opts)
   802  	}
   803  	e.WriteByte('}')
   804  }
   805  
   806  func newMapEncoder(t reflect.Type) encoderFunc {
   807  	switch t.Key().Kind() {
   808  	case reflect.String,
   809  		reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   810  		reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   811  	default:
   812  		if !t.Key().Implements(textMarshalerType) {
   813  			return unsupportedTypeEncoder
   814  		}
   815  	}
   816  	me := mapEncoder{typeEncoder(t.Elem())}
   817  	return me.encode
   818  }
   819  
   820  func encodeByteSlice(e *encodeState, v reflect.Value, _ encOpts) {
   821  	if v.IsNil() {
   822  		e.WriteString("null")
   823  		return
   824  	}
   825  	s := v.Bytes()
   826  	e.WriteByte('"')
   827  	encodedLen := base64.StdEncoding.EncodedLen(len(s))
   828  	if encodedLen <= len(e.scratch) {
   829  		// If the encoded bytes fit in e.scratch, avoid an extra
   830  		// allocation and use the cheaper Encoding.Encode.
   831  		dst := e.scratch[:encodedLen]
   832  		base64.StdEncoding.Encode(dst, s)
   833  		e.Write(dst)
   834  	} else if encodedLen <= 1024 {
   835  		// The encoded bytes are short enough to allocate for, and
   836  		// Encoding.Encode is still cheaper.
   837  		dst := make([]byte, encodedLen)
   838  		base64.StdEncoding.Encode(dst, s)
   839  		e.Write(dst)
   840  	} else {
   841  		// The encoded bytes are too long to cheaply allocate, and
   842  		// Encoding.Encode is no longer noticeably cheaper.
   843  		enc := base64.NewEncoder(base64.StdEncoding, e)
   844  		enc.Write(s)
   845  		enc.Close()
   846  	}
   847  	e.WriteByte('"')
   848  }
   849  
   850  // sliceEncoder just wraps an arrayEncoder, checking to make sure the value isn't nil.
   851  type sliceEncoder struct {
   852  	arrayEnc encoderFunc
   853  }
   854  
   855  func (se sliceEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   856  	if v.IsNil() {
   857  		e.WriteString("null")
   858  		return
   859  	}
   860  	se.arrayEnc(e, v, opts)
   861  }
   862  
   863  func newSliceEncoder(t reflect.Type) encoderFunc {
   864  	// Byte slices get special treatment; arrays don't.
   865  	if t.Elem().Kind() == reflect.Uint8 {
   866  		p := reflect.PtrTo(t.Elem())
   867  		if !p.Implements(marshalerType) && !p.Implements(textMarshalerType) {
   868  			return encodeByteSlice
   869  		}
   870  	}
   871  	enc := sliceEncoder{newArrayEncoder(t)}
   872  	return enc.encode
   873  }
   874  
   875  type arrayEncoder struct {
   876  	elemEnc encoderFunc
   877  }
   878  
   879  func (ae arrayEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   880  	e.WriteByte('[')
   881  	n := v.Len()
   882  	for i := 0; i < n; i++ {
   883  		if i > 0 {
   884  			e.WriteByte(',')
   885  		}
   886  		ae.elemEnc(e, v.Index(i), opts)
   887  	}
   888  	e.WriteByte(']')
   889  }
   890  
   891  func newArrayEncoder(t reflect.Type) encoderFunc {
   892  	enc := arrayEncoder{typeEncoder(t.Elem())}
   893  	return enc.encode
   894  }
   895  
   896  type ptrEncoder struct {
   897  	elemEnc encoderFunc
   898  }
   899  
   900  func (pe ptrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   901  	if v.IsNil() {
   902  		e.WriteString("null")
   903  		return
   904  	}
   905  	if e.ptrLevel++; e.ptrLevel > startDetectingCyclesAfter {
   906  		// We're a large number of nested ptrEncoder.encode calls deep;
   907  		// start checking if we've run into a pointer cycle.
   908  		ptr := v.Interface()
   909  		if _, ok := e.ptrSeen[ptr]; ok {
   910  			e.error(&UnsupportedValueError{v, fmt.Sprintf("encountered a cycle via %s", v.Type())})
   911  		}
   912  		e.ptrSeen[ptr] = struct{}{}
   913  		defer delete(e.ptrSeen, ptr)
   914  	}
   915  	pe.elemEnc(e, v.Elem(), opts)
   916  	e.ptrLevel--
   917  }
   918  
   919  func newPtrEncoder(t reflect.Type) encoderFunc {
   920  	enc := ptrEncoder{typeEncoder(t.Elem())}
   921  	return enc.encode
   922  }
   923  
   924  type condAddrEncoder struct {
   925  	canAddrEnc, elseEnc encoderFunc
   926  }
   927  
   928  func (ce condAddrEncoder) encode(e *encodeState, v reflect.Value, opts encOpts) {
   929  	if v.CanAddr() {
   930  		ce.canAddrEnc(e, v, opts)
   931  	} else {
   932  		ce.elseEnc(e, v, opts)
   933  	}
   934  }
   935  
   936  // newCondAddrEncoder returns an encoder that checks whether its value
   937  // CanAddr and delegates to canAddrEnc if so, else to elseEnc.
   938  func newCondAddrEncoder(canAddrEnc, elseEnc encoderFunc) encoderFunc {
   939  	enc := condAddrEncoder{canAddrEnc: canAddrEnc, elseEnc: elseEnc}
   940  	return enc.encode
   941  }
   942  
   943  func isValidTag(s string) bool {
   944  	if s == "" {
   945  		return false
   946  	}
   947  	for _, c := range s {
   948  		switch {
   949  		case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
   950  			// Backslash and quote chars are reserved, but
   951  			// otherwise any punctuation chars are allowed
   952  			// in a tag name.
   953  		case !unicode.IsLetter(c) && !unicode.IsDigit(c):
   954  			return false
   955  		}
   956  	}
   957  	return true
   958  }
   959  
   960  func typeByIndex(t reflect.Type, index []int) reflect.Type {
   961  	for _, i := range index {
   962  		if t.Kind() == reflect.Ptr {
   963  			t = t.Elem()
   964  		}
   965  		t = t.Field(i).Type
   966  	}
   967  	return t
   968  }
   969  
   970  type reflectWithString struct {
   971  	v reflect.Value
   972  	s string
   973  }
   974  
   975  func (w *reflectWithString) resolve() error {
   976  	if w.v.Kind() == reflect.String {
   977  		w.s = w.v.String()
   978  		return nil
   979  	}
   980  	if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok {
   981  		if w.v.Kind() == reflect.Ptr && w.v.IsNil() {
   982  			return nil
   983  		}
   984  		buf, err := tm.MarshalText()
   985  		w.s = string(buf)
   986  		return err
   987  	}
   988  	switch w.v.Kind() {
   989  	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   990  		w.s = strconv.FormatInt(w.v.Int(), 10)
   991  		return nil
   992  	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   993  		w.s = strconv.FormatUint(w.v.Uint(), 10)
   994  		return nil
   995  	}
   996  	panic("unexpected map key type")
   997  }
   998  
   999  // NOTE: keep in sync with stringBytes below.
  1000  func (e *encodeState) string(s string, escapeHTML bool) {
  1001  	e.WriteByte('"')
  1002  	start := 0
  1003  	for i := 0; i < len(s); {
  1004  		if b := s[i]; b < utf8.RuneSelf {
  1005  			if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) {
  1006  				i++
  1007  				continue
  1008  			}
  1009  			if start < i {
  1010  				e.WriteString(s[start:i])
  1011  			}
  1012  			e.WriteByte('\\')
  1013  			switch b {
  1014  			case '\\', '"':
  1015  				e.WriteByte(b)
  1016  			case '\n':
  1017  				e.WriteByte('n')
  1018  			case '\r':
  1019  				e.WriteByte('r')
  1020  			case '\t':
  1021  				e.WriteByte('t')
  1022  			default:
  1023  				// This encodes bytes < 0x20 except for \t, \n and \r.
  1024  				// If escapeHTML is set, it also escapes <, >, and &
  1025  				// because they can lead to security holes when
  1026  				// user-controlled strings are rendered into JSON
  1027  				// and served to some browsers.
  1028  				e.WriteString(`u00`)
  1029  				e.WriteByte(hex[b>>4])
  1030  				e.WriteByte(hex[b&0xF])
  1031  			}
  1032  			i++
  1033  			start = i
  1034  			continue
  1035  		}
  1036  		c, size := utf8.DecodeRuneInString(s[i:])
  1037  		if c == utf8.RuneError && size == 1 {
  1038  			if start < i {
  1039  				e.WriteString(s[start:i])
  1040  			}
  1041  			e.WriteString(`\ufffd`)
  1042  			i += size
  1043  			start = i
  1044  			continue
  1045  		}
  1046  		// U+2028 is LINE SEPARATOR.
  1047  		// U+2029 is PARAGRAPH SEPARATOR.
  1048  		// They are both technically valid characters in JSON strings,
  1049  		// but don't work in JSONP, which has to be evaluated as JavaScript,
  1050  		// and can lead to security holes there. It is valid JSON to
  1051  		// escape them, so we do so unconditionally.
  1052  		// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
  1053  		if c == '\u2028' || c == '\u2029' {
  1054  			if start < i {
  1055  				e.WriteString(s[start:i])
  1056  			}
  1057  			e.WriteString(`\u202`)
  1058  			e.WriteByte(hex[c&0xF])
  1059  			i += size
  1060  			start = i
  1061  			continue
  1062  		}
  1063  		i += size
  1064  	}
  1065  	if start < len(s) {
  1066  		e.WriteString(s[start:])
  1067  	}
  1068  	e.WriteByte('"')
  1069  }
  1070  
  1071  // NOTE: keep in sync with string above.
  1072  func (e *encodeState) stringBytes(s []byte, escapeHTML bool) {
  1073  	e.WriteByte('"')
  1074  	start := 0
  1075  	for i := 0; i < len(s); {
  1076  		if b := s[i]; b < utf8.RuneSelf {
  1077  			if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) {
  1078  				i++
  1079  				continue
  1080  			}
  1081  			if start < i {
  1082  				e.Write(s[start:i])
  1083  			}
  1084  			e.WriteByte('\\')
  1085  			switch b {
  1086  			case '\\', '"':
  1087  				e.WriteByte(b)
  1088  			case '\n':
  1089  				e.WriteByte('n')
  1090  			case '\r':
  1091  				e.WriteByte('r')
  1092  			case '\t':
  1093  				e.WriteByte('t')
  1094  			default:
  1095  				// This encodes bytes < 0x20 except for \t, \n and \r.
  1096  				// If escapeHTML is set, it also escapes <, >, and &
  1097  				// because they can lead to security holes when
  1098  				// user-controlled strings are rendered into JSON
  1099  				// and served to some browsers.
  1100  				e.WriteString(`u00`)
  1101  				e.WriteByte(hex[b>>4])
  1102  				e.WriteByte(hex[b&0xF])
  1103  			}
  1104  			i++
  1105  			start = i
  1106  			continue
  1107  		}
  1108  		c, size := utf8.DecodeRune(s[i:])
  1109  		if c == utf8.RuneError && size == 1 {
  1110  			if start < i {
  1111  				e.Write(s[start:i])
  1112  			}
  1113  			e.WriteString(`\ufffd`)
  1114  			i += size
  1115  			start = i
  1116  			continue
  1117  		}
  1118  		// U+2028 is LINE SEPARATOR.
  1119  		// U+2029 is PARAGRAPH SEPARATOR.
  1120  		// They are both technically valid characters in JSON strings,
  1121  		// but don't work in JSONP, which has to be evaluated as JavaScript,
  1122  		// and can lead to security holes there. It is valid JSON to
  1123  		// escape them, so we do so unconditionally.
  1124  		// See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
  1125  		if c == '\u2028' || c == '\u2029' {
  1126  			if start < i {
  1127  				e.Write(s[start:i])
  1128  			}
  1129  			e.WriteString(`\u202`)
  1130  			e.WriteByte(hex[c&0xF])
  1131  			i += size
  1132  			start = i
  1133  			continue
  1134  		}
  1135  		i += size
  1136  	}
  1137  	if start < len(s) {
  1138  		e.Write(s[start:])
  1139  	}
  1140  	e.WriteByte('"')
  1141  }
  1142  
  1143  // A field represents a single field found in a struct.
  1144  type field struct {
  1145  	name      string
  1146  	nameBytes []byte                 // []byte(name)
  1147  	equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
  1148  
  1149  	nameNonEsc  string // `"` + name + `":`
  1150  	nameEscHTML string // `"` + HTMLEscape(name) + `":`
  1151  
  1152  	tag       bool
  1153  	index     []int
  1154  	typ       reflect.Type
  1155  	omitEmpty bool
  1156  	quoted    bool
  1157  
  1158  	encoder encoderFunc
  1159  }
  1160  
  1161  // byIndex sorts field by index sequence.
  1162  type byIndex []field
  1163  
  1164  func (x byIndex) Len() int { return len(x) }
  1165  
  1166  func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  1167  
  1168  func (x byIndex) Less(i, j int) bool {
  1169  	for k, xik := range x[i].index {
  1170  		if k >= len(x[j].index) {
  1171  			return false
  1172  		}
  1173  		if xik != x[j].index[k] {
  1174  			return xik < x[j].index[k]
  1175  		}
  1176  	}
  1177  	return len(x[i].index) < len(x[j].index)
  1178  }
  1179  
  1180  // typeFields returns a list of fields that JSON should recognize for the given type.
  1181  // The algorithm is breadth-first search over the set of structs to include - the top struct
  1182  // and then any reachable anonymous structs.
  1183  func typeFields(t reflect.Type) structFields {
  1184  	// Anonymous fields to explore at the current level and the next.
  1185  	current := []field{}
  1186  	next := []field{{typ: t}}
  1187  
  1188  	// Count of queued names for current level and the next.
  1189  	var count, nextCount map[reflect.Type]int
  1190  
  1191  	// Types already visited at an earlier level.
  1192  	visited := map[reflect.Type]bool{}
  1193  
  1194  	// Fields found.
  1195  	var fields []field
  1196  
  1197  	// Buffer to run HTMLEscape on field names.
  1198  	var nameEscBuf bytes.Buffer
  1199  
  1200  	for len(next) > 0 {
  1201  		current, next = next, current[:0]
  1202  		count, nextCount = nextCount, map[reflect.Type]int{}
  1203  
  1204  		for _, f := range current {
  1205  			if visited[f.typ] {
  1206  				continue
  1207  			}
  1208  			visited[f.typ] = true
  1209  
  1210  			// Scan f.typ for fields to include.
  1211  			for i := 0; i < f.typ.NumField(); i++ {
  1212  				sf := f.typ.Field(i)
  1213  				isUnexported := sf.PkgPath != ""
  1214  				if sf.Anonymous {
  1215  					t := sf.Type
  1216  					if t.Kind() == reflect.Ptr {
  1217  						t = t.Elem()
  1218  					}
  1219  					if isUnexported && t.Kind() != reflect.Struct {
  1220  						// Ignore embedded fields of unexported non-struct types.
  1221  						continue
  1222  					}
  1223  					// Do not ignore embedded fields of unexported struct types
  1224  					// since they may have exported fields.
  1225  				} else if isUnexported {
  1226  					// Ignore unexported non-embedded fields.
  1227  					continue
  1228  				}
  1229  				tag := sf.Tag.Get("json")
  1230  				if tag == "-" {
  1231  					continue
  1232  				}
  1233  				name, opts := parseTag(tag)
  1234  				if !isValidTag(name) {
  1235  					name = ""
  1236  				}
  1237  				index := make([]int, len(f.index)+1)
  1238  				copy(index, f.index)
  1239  				index[len(f.index)] = i
  1240  
  1241  				ft := sf.Type
  1242  				if ft.Name() == "" && ft.Kind() == reflect.Ptr {
  1243  					// Follow pointer.
  1244  					ft = ft.Elem()
  1245  				}
  1246  
  1247  				// Only strings, floats, integers, and booleans can be quoted.
  1248  				quoted := false
  1249  				if opts.Contains("string") {
  1250  					switch ft.Kind() {
  1251  					case reflect.Bool,
  1252  						reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  1253  						reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
  1254  						reflect.Float32, reflect.Float64,
  1255  						reflect.String:
  1256  						quoted = true
  1257  					}
  1258  				}
  1259  
  1260  				// Record found field and index sequence.
  1261  				if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
  1262  					tagged := name != ""
  1263  					if name == "" {
  1264  						name = sf.Name
  1265  					}
  1266  					field := field{
  1267  						name:      name,
  1268  						tag:       tagged,
  1269  						index:     index,
  1270  						typ:       ft,
  1271  						omitEmpty: opts.Contains("omitempty"),
  1272  						quoted:    quoted,
  1273  					}
  1274  					field.nameBytes = []byte(field.name)
  1275  					field.equalFold = foldFunc(field.nameBytes)
  1276  
  1277  					// Build nameEscHTML and nameNonEsc ahead of time.
  1278  					nameEscBuf.Reset()
  1279  					nameEscBuf.WriteString(`"`)
  1280  					HTMLEscape(&nameEscBuf, field.nameBytes)
  1281  					nameEscBuf.WriteString(`":`)
  1282  					field.nameEscHTML = nameEscBuf.String()
  1283  					field.nameNonEsc = `"` + field.name + `":`
  1284  
  1285  					fields = append(fields, field)
  1286  					if count[f.typ] > 1 {
  1287  						// If there were multiple instances, add a second,
  1288  						// so that the annihilation code will see a duplicate.
  1289  						// It only cares about the distinction between 1 or 2,
  1290  						// so don't bother generating any more copies.
  1291  						fields = append(fields, fields[len(fields)-1])
  1292  					}
  1293  					continue
  1294  				}
  1295  
  1296  				// Record new anonymous struct to explore in next round.
  1297  				nextCount[ft]++
  1298  				if nextCount[ft] == 1 {
  1299  					next = append(next, field{name: ft.Name(), index: index, typ: ft})
  1300  				}
  1301  			}
  1302  		}
  1303  	}
  1304  
  1305  	sort.Slice(fields, func(i, j int) bool {
  1306  		x := fields
  1307  		// sort field by name, breaking ties with depth, then
  1308  		// breaking ties with "name came from json tag", then
  1309  		// breaking ties with index sequence.
  1310  		if x[i].name != x[j].name {
  1311  			return x[i].name < x[j].name
  1312  		}
  1313  		if len(x[i].index) != len(x[j].index) {
  1314  			return len(x[i].index) < len(x[j].index)
  1315  		}
  1316  		if x[i].tag != x[j].tag {
  1317  			return x[i].tag
  1318  		}
  1319  		return byIndex(x).Less(i, j)
  1320  	})
  1321  
  1322  	// Delete all fields that are hidden by the Go rules for embedded fields,
  1323  	// except that fields with JSON tags are promoted.
  1324  
  1325  	// The fields are sorted in primary order of name, secondary order
  1326  	// of field index length. Loop over names; for each name, delete
  1327  	// hidden fields by choosing the one dominant field that survives.
  1328  	out := fields[:0]
  1329  	for advance, i := 0, 0; i < len(fields); i += advance {
  1330  		// One iteration per name.
  1331  		// Find the sequence of fields with the name of this first field.
  1332  		fi := fields[i]
  1333  		name := fi.name
  1334  		for advance = 1; i+advance < len(fields); advance++ {
  1335  			fj := fields[i+advance]
  1336  			if fj.name != name {
  1337  				break
  1338  			}
  1339  		}
  1340  		if advance == 1 { // Only one field with this name
  1341  			out = append(out, fi)
  1342  			continue
  1343  		}
  1344  		dominant, ok := dominantField(fields[i : i+advance])
  1345  		if ok {
  1346  			out = append(out, dominant)
  1347  		}
  1348  	}
  1349  
  1350  	fields = out
  1351  	sort.Sort(byIndex(fields))
  1352  
  1353  	for i := range fields {
  1354  		f := &fields[i]
  1355  		f.encoder = typeEncoder(typeByIndex(t, f.index))
  1356  	}
  1357  	nameIndex := make(map[string]int, len(fields))
  1358  	for i, field := range fields {
  1359  		nameIndex[field.name] = i
  1360  	}
  1361  	return structFields{fields, nameIndex}
  1362  }
  1363  
  1364  // dominantField looks through the fields, all of which are known to
  1365  // have the same name, to find the single field that dominates the
  1366  // others using Go's embedding rules, modified by the presence of
  1367  // JSON tags. If there are multiple top-level fields, the boolean
  1368  // will be false: This condition is an error in Go and we skip all
  1369  // the fields.
  1370  func dominantField(fields []field) (field, bool) {
  1371  	// The fields are sorted in increasing index-length order, then by presence of tag.
  1372  	// That means that the first field is the dominant one. We need only check
  1373  	// for error cases: two fields at top level, either both tagged or neither tagged.
  1374  	if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tag == fields[1].tag {
  1375  		return field{}, false
  1376  	}
  1377  	return fields[0], true
  1378  }
  1379  
  1380  var fieldCache sync.Map // map[reflect.Type]structFields
  1381  
  1382  // cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
  1383  func cachedTypeFields(t reflect.Type) structFields {
  1384  	if f, ok := fieldCache.Load(t); ok {
  1385  		return f.(structFields)
  1386  	}
  1387  	f, _ := fieldCache.LoadOrStore(t, typeFields(t))
  1388  	return f.(structFields)
  1389  }
  1390  

View as plain text