...

Source file src/github.com/evanphx/json-patch/v5/internal/json/decode.go

Documentation: github.com/evanphx/json-patch/v5/internal/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  // Represents JSON data structure using native Go types: booleans, floats,
     6  // strings, arrays, and maps.
     7  
     8  package json
     9  
    10  import (
    11  	"encoding"
    12  	"encoding/base64"
    13  	"fmt"
    14  	"reflect"
    15  	"strconv"
    16  	"strings"
    17  	"sync"
    18  	"unicode"
    19  	"unicode/utf16"
    20  	"unicode/utf8"
    21  )
    22  
    23  // Unmarshal parses the JSON-encoded data and stores the result
    24  // in the value pointed to by v. If v is nil or not a pointer,
    25  // Unmarshal returns an InvalidUnmarshalError.
    26  //
    27  // Unmarshal uses the inverse of the encodings that
    28  // Marshal uses, allocating maps, slices, and pointers as necessary,
    29  // with the following additional rules:
    30  //
    31  // To unmarshal JSON into a pointer, Unmarshal first handles the case of
    32  // the JSON being the JSON literal null. In that case, Unmarshal sets
    33  // the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into
    34  // the value pointed at by the pointer. If the pointer is nil, Unmarshal
    35  // allocates a new value for it to point to.
    36  //
    37  // To unmarshal JSON into a value implementing the Unmarshaler interface,
    38  // Unmarshal calls that value's UnmarshalJSON method, including
    39  // when the input is a JSON null.
    40  // Otherwise, if the value implements encoding.TextUnmarshaler
    41  // and the input is a JSON quoted string, Unmarshal calls that value's
    42  // UnmarshalText method with the unquoted form of the string.
    43  //
    44  // To unmarshal JSON into a struct, Unmarshal matches incoming object
    45  // keys to the keys used by Marshal (either the struct field name or its tag),
    46  // preferring an exact match but also accepting a case-insensitive match. By
    47  // default, object keys which don't have a corresponding struct field are
    48  // ignored (see Decoder.DisallowUnknownFields for an alternative).
    49  //
    50  // To unmarshal JSON into an interface value,
    51  // Unmarshal stores one of these in the interface value:
    52  //
    53  //	bool, for JSON booleans
    54  //	float64, for JSON numbers
    55  //	string, for JSON strings
    56  //	[]interface{}, for JSON arrays
    57  //	map[string]interface{}, for JSON objects
    58  //	nil for JSON null
    59  //
    60  // To unmarshal a JSON array into a slice, Unmarshal resets the slice length
    61  // to zero and then appends each element to the slice.
    62  // As a special case, to unmarshal an empty JSON array into a slice,
    63  // Unmarshal replaces the slice with a new empty slice.
    64  //
    65  // To unmarshal a JSON array into a Go array, Unmarshal decodes
    66  // JSON array elements into corresponding Go array elements.
    67  // If the Go array is smaller than the JSON array,
    68  // the additional JSON array elements are discarded.
    69  // If the JSON array is smaller than the Go array,
    70  // the additional Go array elements are set to zero values.
    71  //
    72  // To unmarshal a JSON object into a map, Unmarshal first establishes a map to
    73  // use. If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
    74  // reuses the existing map, keeping existing entries. Unmarshal then stores
    75  // key-value pairs from the JSON object into the map. The map's key type must
    76  // either be any string type, an integer, implement json.Unmarshaler, or
    77  // implement encoding.TextUnmarshaler.
    78  //
    79  // If the JSON-encoded data contain a syntax error, Unmarshal returns a SyntaxError.
    80  //
    81  // If a JSON value is not appropriate for a given target type,
    82  // or if a JSON number overflows the target type, Unmarshal
    83  // skips that field and completes the unmarshaling as best it can.
    84  // If no more serious errors are encountered, Unmarshal returns
    85  // an UnmarshalTypeError describing the earliest such error. In any
    86  // case, it's not guaranteed that all the remaining fields following
    87  // the problematic one will be unmarshaled into the target object.
    88  //
    89  // The JSON null value unmarshals into an interface, map, pointer, or slice
    90  // by setting that Go value to nil. Because null is often used in JSON to mean
    91  // “not present,” unmarshaling a JSON null into any other Go type has no effect
    92  // on the value and produces no error.
    93  //
    94  // When unmarshaling quoted strings, invalid UTF-8 or
    95  // invalid UTF-16 surrogate pairs are not treated as an error.
    96  // Instead, they are replaced by the Unicode replacement
    97  // character U+FFFD.
    98  func Unmarshal(data []byte, v any) error {
    99  	// Check for well-formedness.
   100  	// Avoids filling out half a data structure
   101  	// before discovering a JSON syntax error.
   102  	d := ds.Get().(*decodeState)
   103  	defer ds.Put(d)
   104  	//var d decodeState
   105  	d.useNumber = true
   106  	err := checkValid(data, &d.scan)
   107  	if err != nil {
   108  		return err
   109  	}
   110  
   111  	d.init(data)
   112  	return d.unmarshal(v)
   113  }
   114  
   115  var ds = sync.Pool{
   116  	New: func() any {
   117  		return new(decodeState)
   118  	},
   119  }
   120  
   121  func UnmarshalWithKeys(data []byte, v any) ([]string, error) {
   122  	// Check for well-formedness.
   123  	// Avoids filling out half a data structure
   124  	// before discovering a JSON syntax error.
   125  
   126  	d := ds.Get().(*decodeState)
   127  	defer ds.Put(d)
   128  	//var d decodeState
   129  	d.useNumber = true
   130  	err := checkValid(data, &d.scan)
   131  	if err != nil {
   132  		return nil, err
   133  	}
   134  
   135  	d.init(data)
   136  	err = d.unmarshal(v)
   137  	if err != nil {
   138  		return nil, err
   139  	}
   140  
   141  	return d.lastKeys, nil
   142  }
   143  
   144  func UnmarshalValid(data []byte, v any) error {
   145  	// Check for well-formedness.
   146  	// Avoids filling out half a data structure
   147  	// before discovering a JSON syntax error.
   148  	d := ds.Get().(*decodeState)
   149  	defer ds.Put(d)
   150  	//var d decodeState
   151  	d.useNumber = true
   152  
   153  	d.init(data)
   154  	return d.unmarshal(v)
   155  }
   156  
   157  func UnmarshalValidWithKeys(data []byte, v any) ([]string, error) {
   158  	// Check for well-formedness.
   159  	// Avoids filling out half a data structure
   160  	// before discovering a JSON syntax error.
   161  
   162  	d := ds.Get().(*decodeState)
   163  	defer ds.Put(d)
   164  	//var d decodeState
   165  	d.useNumber = true
   166  
   167  	d.init(data)
   168  	err := d.unmarshal(v)
   169  	if err != nil {
   170  		return nil, err
   171  	}
   172  
   173  	return d.lastKeys, nil
   174  }
   175  
   176  // Unmarshaler is the interface implemented by types
   177  // that can unmarshal a JSON description of themselves.
   178  // The input can be assumed to be a valid encoding of
   179  // a JSON value. UnmarshalJSON must copy the JSON data
   180  // if it wishes to retain the data after returning.
   181  //
   182  // By convention, to approximate the behavior of Unmarshal itself,
   183  // Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
   184  type Unmarshaler interface {
   185  	UnmarshalJSON([]byte) error
   186  }
   187  
   188  // An UnmarshalTypeError describes a JSON value that was
   189  // not appropriate for a value of a specific Go type.
   190  type UnmarshalTypeError struct {
   191  	Value  string       // description of JSON value - "bool", "array", "number -5"
   192  	Type   reflect.Type // type of Go value it could not be assigned to
   193  	Offset int64        // error occurred after reading Offset bytes
   194  	Struct string       // name of the struct type containing the field
   195  	Field  string       // the full path from root node to the field
   196  }
   197  
   198  func (e *UnmarshalTypeError) Error() string {
   199  	if e.Struct != "" || e.Field != "" {
   200  		return "json: cannot unmarshal " + e.Value + " into Go struct field " + e.Struct + "." + e.Field + " of type " + e.Type.String()
   201  	}
   202  	return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
   203  }
   204  
   205  // An UnmarshalFieldError describes a JSON object key that
   206  // led to an unexported (and therefore unwritable) struct field.
   207  //
   208  // Deprecated: No longer used; kept for compatibility.
   209  type UnmarshalFieldError struct {
   210  	Key   string
   211  	Type  reflect.Type
   212  	Field reflect.StructField
   213  }
   214  
   215  func (e *UnmarshalFieldError) Error() string {
   216  	return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
   217  }
   218  
   219  // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
   220  // (The argument to Unmarshal must be a non-nil pointer.)
   221  type InvalidUnmarshalError struct {
   222  	Type reflect.Type
   223  }
   224  
   225  func (e *InvalidUnmarshalError) Error() string {
   226  	if e.Type == nil {
   227  		return "json: Unmarshal(nil)"
   228  	}
   229  
   230  	if e.Type.Kind() != reflect.Pointer {
   231  		return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
   232  	}
   233  	return "json: Unmarshal(nil " + e.Type.String() + ")"
   234  }
   235  
   236  func (d *decodeState) unmarshal(v any) error {
   237  	rv := reflect.ValueOf(v)
   238  	if rv.Kind() != reflect.Pointer || rv.IsNil() {
   239  		return &InvalidUnmarshalError{reflect.TypeOf(v)}
   240  	}
   241  
   242  	d.scan.reset()
   243  	d.scanWhile(scanSkipSpace)
   244  	// We decode rv not rv.Elem because the Unmarshaler interface
   245  	// test must be applied at the top level of the value.
   246  	err := d.value(rv)
   247  	if err != nil {
   248  		return d.addErrorContext(err)
   249  	}
   250  	return d.savedError
   251  }
   252  
   253  // A Number represents a JSON number literal.
   254  type Number string
   255  
   256  // String returns the literal text of the number.
   257  func (n Number) String() string { return string(n) }
   258  
   259  // Float64 returns the number as a float64.
   260  func (n Number) Float64() (float64, error) {
   261  	return strconv.ParseFloat(string(n), 64)
   262  }
   263  
   264  // Int64 returns the number as an int64.
   265  func (n Number) Int64() (int64, error) {
   266  	return strconv.ParseInt(string(n), 10, 64)
   267  }
   268  
   269  // An errorContext provides context for type errors during decoding.
   270  type errorContext struct {
   271  	Struct     reflect.Type
   272  	FieldStack []string
   273  }
   274  
   275  // decodeState represents the state while decoding a JSON value.
   276  type decodeState struct {
   277  	data                  []byte
   278  	off                   int // next read offset in data
   279  	opcode                int // last read result
   280  	scan                  scanner
   281  	errorContext          *errorContext
   282  	savedError            error
   283  	useNumber             bool
   284  	disallowUnknownFields bool
   285  	lastKeys              []string
   286  }
   287  
   288  // readIndex returns the position of the last byte read.
   289  func (d *decodeState) readIndex() int {
   290  	return d.off - 1
   291  }
   292  
   293  // phasePanicMsg is used as a panic message when we end up with something that
   294  // shouldn't happen. It can indicate a bug in the JSON decoder, or that
   295  // something is editing the data slice while the decoder executes.
   296  const phasePanicMsg = "JSON decoder out of sync - data changing underfoot?"
   297  
   298  func (d *decodeState) init(data []byte) *decodeState {
   299  	d.data = data
   300  	d.off = 0
   301  	d.savedError = nil
   302  	if d.errorContext != nil {
   303  		d.errorContext.Struct = nil
   304  		// Reuse the allocated space for the FieldStack slice.
   305  		d.errorContext.FieldStack = d.errorContext.FieldStack[:0]
   306  	}
   307  	return d
   308  }
   309  
   310  // saveError saves the first err it is called with,
   311  // for reporting at the end of the unmarshal.
   312  func (d *decodeState) saveError(err error) {
   313  	if d.savedError == nil {
   314  		d.savedError = d.addErrorContext(err)
   315  	}
   316  }
   317  
   318  // addErrorContext returns a new error enhanced with information from d.errorContext
   319  func (d *decodeState) addErrorContext(err error) error {
   320  	if d.errorContext != nil && (d.errorContext.Struct != nil || len(d.errorContext.FieldStack) > 0) {
   321  		switch err := err.(type) {
   322  		case *UnmarshalTypeError:
   323  			err.Struct = d.errorContext.Struct.Name()
   324  			err.Field = strings.Join(d.errorContext.FieldStack, ".")
   325  		}
   326  	}
   327  	return err
   328  }
   329  
   330  // skip scans to the end of what was started.
   331  func (d *decodeState) skip() {
   332  	s, data, i := &d.scan, d.data, d.off
   333  	depth := len(s.parseState)
   334  	for {
   335  		op := s.step(s, data[i])
   336  		i++
   337  		if len(s.parseState) < depth {
   338  			d.off = i
   339  			d.opcode = op
   340  			return
   341  		}
   342  	}
   343  }
   344  
   345  // scanNext processes the byte at d.data[d.off].
   346  func (d *decodeState) scanNext() {
   347  	if d.off < len(d.data) {
   348  		d.opcode = d.scan.step(&d.scan, d.data[d.off])
   349  		d.off++
   350  	} else {
   351  		d.opcode = d.scan.eof()
   352  		d.off = len(d.data) + 1 // mark processed EOF with len+1
   353  	}
   354  }
   355  
   356  // scanWhile processes bytes in d.data[d.off:] until it
   357  // receives a scan code not equal to op.
   358  func (d *decodeState) scanWhile(op int) {
   359  	s, data, i := &d.scan, d.data, d.off
   360  	for i < len(data) {
   361  		newOp := s.step(s, data[i])
   362  		i++
   363  		if newOp != op {
   364  			d.opcode = newOp
   365  			d.off = i
   366  			return
   367  		}
   368  	}
   369  
   370  	d.off = len(data) + 1 // mark processed EOF with len+1
   371  	d.opcode = d.scan.eof()
   372  }
   373  
   374  // rescanLiteral is similar to scanWhile(scanContinue), but it specialises the
   375  // common case where we're decoding a literal. The decoder scans the input
   376  // twice, once for syntax errors and to check the length of the value, and the
   377  // second to perform the decoding.
   378  //
   379  // Only in the second step do we use decodeState to tokenize literals, so we
   380  // know there aren't any syntax errors. We can take advantage of that knowledge,
   381  // and scan a literal's bytes much more quickly.
   382  func (d *decodeState) rescanLiteral() {
   383  	data, i := d.data, d.off
   384  Switch:
   385  	switch data[i-1] {
   386  	case '"': // string
   387  		for ; i < len(data); i++ {
   388  			switch data[i] {
   389  			case '\\':
   390  				i++ // escaped char
   391  			case '"':
   392  				i++ // tokenize the closing quote too
   393  				break Switch
   394  			}
   395  		}
   396  	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-': // number
   397  		for ; i < len(data); i++ {
   398  			switch data[i] {
   399  			case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
   400  				'.', 'e', 'E', '+', '-':
   401  			default:
   402  				break Switch
   403  			}
   404  		}
   405  	case 't': // true
   406  		i += len("rue")
   407  	case 'f': // false
   408  		i += len("alse")
   409  	case 'n': // null
   410  		i += len("ull")
   411  	}
   412  	if i < len(data) {
   413  		d.opcode = stateEndValue(&d.scan, data[i])
   414  	} else {
   415  		d.opcode = scanEnd
   416  	}
   417  	d.off = i + 1
   418  }
   419  
   420  // value consumes a JSON value from d.data[d.off-1:], decoding into v, and
   421  // reads the following byte ahead. If v is invalid, the value is discarded.
   422  // The first byte of the value has been read already.
   423  func (d *decodeState) value(v reflect.Value) error {
   424  	switch d.opcode {
   425  	default:
   426  		panic(phasePanicMsg)
   427  
   428  	case scanBeginArray:
   429  		if v.IsValid() {
   430  			if err := d.array(v); err != nil {
   431  				return err
   432  			}
   433  		} else {
   434  			d.skip()
   435  		}
   436  		d.scanNext()
   437  
   438  	case scanBeginObject:
   439  		if v.IsValid() {
   440  			if err := d.object(v); err != nil {
   441  				return err
   442  			}
   443  		} else {
   444  			d.skip()
   445  		}
   446  		d.scanNext()
   447  
   448  	case scanBeginLiteral:
   449  		// All bytes inside literal return scanContinue op code.
   450  		start := d.readIndex()
   451  		d.rescanLiteral()
   452  
   453  		if v.IsValid() {
   454  			if err := d.literalStore(d.data[start:d.readIndex()], v, false); err != nil {
   455  				return err
   456  			}
   457  		}
   458  	}
   459  	return nil
   460  }
   461  
   462  type unquotedValue struct{}
   463  
   464  // valueQuoted is like value but decodes a
   465  // quoted string literal or literal null into an interface value.
   466  // If it finds anything other than a quoted string literal or null,
   467  // valueQuoted returns unquotedValue{}.
   468  func (d *decodeState) valueQuoted() any {
   469  	switch d.opcode {
   470  	default:
   471  		panic(phasePanicMsg)
   472  
   473  	case scanBeginArray, scanBeginObject:
   474  		d.skip()
   475  		d.scanNext()
   476  
   477  	case scanBeginLiteral:
   478  		v := d.literalInterface()
   479  		switch v.(type) {
   480  		case nil, string:
   481  			return v
   482  		}
   483  	}
   484  	return unquotedValue{}
   485  }
   486  
   487  // indirect walks down v allocating pointers as needed,
   488  // until it gets to a non-pointer.
   489  // If it encounters an Unmarshaler, indirect stops and returns that.
   490  // If decodingNull is true, indirect stops at the first settable pointer so it
   491  // can be set to nil.
   492  func indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
   493  	// Issue #24153 indicates that it is generally not a guaranteed property
   494  	// that you may round-trip a reflect.Value by calling Value.Addr().Elem()
   495  	// and expect the value to still be settable for values derived from
   496  	// unexported embedded struct fields.
   497  	//
   498  	// The logic below effectively does this when it first addresses the value
   499  	// (to satisfy possible pointer methods) and continues to dereference
   500  	// subsequent pointers as necessary.
   501  	//
   502  	// After the first round-trip, we set v back to the original value to
   503  	// preserve the original RW flags contained in reflect.Value.
   504  	v0 := v
   505  	haveAddr := false
   506  
   507  	// If v is a named type and is addressable,
   508  	// start with its address, so that if the type has pointer methods,
   509  	// we find them.
   510  	if v.Kind() != reflect.Pointer && v.Type().Name() != "" && v.CanAddr() {
   511  		haveAddr = true
   512  		v = v.Addr()
   513  	}
   514  	for {
   515  		// Load value from interface, but only if the result will be
   516  		// usefully addressable.
   517  		if v.Kind() == reflect.Interface && !v.IsNil() {
   518  			e := v.Elem()
   519  			if e.Kind() == reflect.Pointer && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Pointer) {
   520  				haveAddr = false
   521  				v = e
   522  				continue
   523  			}
   524  		}
   525  
   526  		if v.Kind() != reflect.Pointer {
   527  			break
   528  		}
   529  
   530  		if decodingNull && v.CanSet() {
   531  			break
   532  		}
   533  
   534  		// Prevent infinite loop if v is an interface pointing to its own address:
   535  		//     var v interface{}
   536  		//     v = &v
   537  		if v.Elem().Kind() == reflect.Interface && v.Elem().Elem() == v {
   538  			v = v.Elem()
   539  			break
   540  		}
   541  		if v.IsNil() {
   542  			v.Set(reflect.New(v.Type().Elem()))
   543  		}
   544  		if v.Type().NumMethod() > 0 && v.CanInterface() {
   545  			if u, ok := v.Interface().(Unmarshaler); ok {
   546  				return u, nil, reflect.Value{}
   547  			}
   548  			if !decodingNull {
   549  				if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
   550  					return nil, u, reflect.Value{}
   551  				}
   552  			}
   553  		}
   554  
   555  		if haveAddr {
   556  			v = v0 // restore original value after round-trip Value.Addr().Elem()
   557  			haveAddr = false
   558  		} else {
   559  			v = v.Elem()
   560  		}
   561  	}
   562  	return nil, nil, v
   563  }
   564  
   565  // array consumes an array from d.data[d.off-1:], decoding into v.
   566  // The first byte of the array ('[') has been read already.
   567  func (d *decodeState) array(v reflect.Value) error {
   568  	// Check for unmarshaler.
   569  	u, ut, pv := indirect(v, false)
   570  	if u != nil {
   571  		start := d.readIndex()
   572  		d.skip()
   573  		return u.UnmarshalJSON(d.data[start:d.off])
   574  	}
   575  	if ut != nil {
   576  		d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
   577  		d.skip()
   578  		return nil
   579  	}
   580  	v = pv
   581  
   582  	// Check type of target.
   583  	switch v.Kind() {
   584  	case reflect.Interface:
   585  		if v.NumMethod() == 0 {
   586  			// Decoding into nil interface? Switch to non-reflect code.
   587  			ai := d.arrayInterface()
   588  			v.Set(reflect.ValueOf(ai))
   589  			return nil
   590  		}
   591  		// Otherwise it's invalid.
   592  		fallthrough
   593  	default:
   594  		d.saveError(&UnmarshalTypeError{Value: "array", Type: v.Type(), Offset: int64(d.off)})
   595  		d.skip()
   596  		return nil
   597  	case reflect.Array, reflect.Slice:
   598  		break
   599  	}
   600  
   601  	i := 0
   602  	for {
   603  		// Look ahead for ] - can only happen on first iteration.
   604  		d.scanWhile(scanSkipSpace)
   605  		if d.opcode == scanEndArray {
   606  			break
   607  		}
   608  
   609  		// Get element of array, growing if necessary.
   610  		if v.Kind() == reflect.Slice {
   611  			// Grow slice if necessary
   612  			if i >= v.Cap() {
   613  				newcap := v.Cap() + v.Cap()/2
   614  				if newcap < 4 {
   615  					newcap = 4
   616  				}
   617  				newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
   618  				reflect.Copy(newv, v)
   619  				v.Set(newv)
   620  			}
   621  			if i >= v.Len() {
   622  				v.SetLen(i + 1)
   623  			}
   624  		}
   625  
   626  		if i < v.Len() {
   627  			// Decode into element.
   628  			if err := d.value(v.Index(i)); err != nil {
   629  				return err
   630  			}
   631  		} else {
   632  			// Ran out of fixed array: skip.
   633  			if err := d.value(reflect.Value{}); err != nil {
   634  				return err
   635  			}
   636  		}
   637  		i++
   638  
   639  		// Next token must be , or ].
   640  		if d.opcode == scanSkipSpace {
   641  			d.scanWhile(scanSkipSpace)
   642  		}
   643  		if d.opcode == scanEndArray {
   644  			break
   645  		}
   646  		if d.opcode != scanArrayValue {
   647  			panic(phasePanicMsg)
   648  		}
   649  	}
   650  
   651  	if i < v.Len() {
   652  		if v.Kind() == reflect.Array {
   653  			// Array. Zero the rest.
   654  			z := reflect.Zero(v.Type().Elem())
   655  			for ; i < v.Len(); i++ {
   656  				v.Index(i).Set(z)
   657  			}
   658  		} else {
   659  			v.SetLen(i)
   660  		}
   661  	}
   662  	if i == 0 && v.Kind() == reflect.Slice {
   663  		v.Set(reflect.MakeSlice(v.Type(), 0, 0))
   664  	}
   665  	return nil
   666  }
   667  
   668  var nullLiteral = []byte("null")
   669  var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
   670  
   671  // object consumes an object from d.data[d.off-1:], decoding into v.
   672  // The first byte ('{') of the object has been read already.
   673  func (d *decodeState) object(v reflect.Value) error {
   674  	// Check for unmarshaler.
   675  	u, ut, pv := indirect(v, false)
   676  	if u != nil {
   677  		start := d.readIndex()
   678  		d.skip()
   679  		return u.UnmarshalJSON(d.data[start:d.off])
   680  	}
   681  	if ut != nil {
   682  		d.saveError(&UnmarshalTypeError{Value: "object", Type: v.Type(), Offset: int64(d.off)})
   683  		d.skip()
   684  		return nil
   685  	}
   686  	v = pv
   687  	t := v.Type()
   688  
   689  	// Decoding into nil interface? Switch to non-reflect code.
   690  	if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
   691  		oi := d.objectInterface()
   692  		v.Set(reflect.ValueOf(oi))
   693  		return nil
   694  	}
   695  
   696  	var fields structFields
   697  
   698  	// Check type of target:
   699  	//   struct or
   700  	//   map[T1]T2 where T1 is string, an integer type,
   701  	//             or an encoding.TextUnmarshaler
   702  	switch v.Kind() {
   703  	case reflect.Map:
   704  		// Map key must either have string kind, have an integer kind,
   705  		// or be an encoding.TextUnmarshaler.
   706  		switch t.Key().Kind() {
   707  		case reflect.String,
   708  			reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
   709  			reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   710  		default:
   711  			if !reflect.PointerTo(t.Key()).Implements(textUnmarshalerType) {
   712  				d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)})
   713  				d.skip()
   714  				return nil
   715  			}
   716  		}
   717  		if v.IsNil() {
   718  			v.Set(reflect.MakeMap(t))
   719  		}
   720  	case reflect.Struct:
   721  		fields = cachedTypeFields(t)
   722  		// ok
   723  	default:
   724  		d.saveError(&UnmarshalTypeError{Value: "object", Type: t, Offset: int64(d.off)})
   725  		d.skip()
   726  		return nil
   727  	}
   728  
   729  	var mapElem reflect.Value
   730  	var origErrorContext errorContext
   731  	if d.errorContext != nil {
   732  		origErrorContext = *d.errorContext
   733  	}
   734  
   735  	var keys []string
   736  
   737  	for {
   738  		// Read opening " of string key or closing }.
   739  		d.scanWhile(scanSkipSpace)
   740  		if d.opcode == scanEndObject {
   741  			// closing } - can only happen on first iteration.
   742  			break
   743  		}
   744  		if d.opcode != scanBeginLiteral {
   745  			panic(phasePanicMsg)
   746  		}
   747  
   748  		// Read key.
   749  		start := d.readIndex()
   750  		d.rescanLiteral()
   751  		item := d.data[start:d.readIndex()]
   752  		key, ok := unquoteBytes(item)
   753  		if !ok {
   754  			panic(phasePanicMsg)
   755  		}
   756  
   757  		keys = append(keys, string(key))
   758  
   759  		// Figure out field corresponding to key.
   760  		var subv reflect.Value
   761  		destring := false // whether the value is wrapped in a string to be decoded first
   762  
   763  		if v.Kind() == reflect.Map {
   764  			elemType := t.Elem()
   765  			if !mapElem.IsValid() {
   766  				mapElem = reflect.New(elemType).Elem()
   767  			} else {
   768  				mapElem.Set(reflect.Zero(elemType))
   769  			}
   770  			subv = mapElem
   771  		} else {
   772  			var f *field
   773  			if i, ok := fields.nameIndex[string(key)]; ok {
   774  				// Found an exact name match.
   775  				f = &fields.list[i]
   776  			} else {
   777  				// Fall back to the expensive case-insensitive
   778  				// linear search.
   779  				for i := range fields.list {
   780  					ff := &fields.list[i]
   781  					if ff.equalFold(ff.nameBytes, key) {
   782  						f = ff
   783  						break
   784  					}
   785  				}
   786  			}
   787  			if f != nil {
   788  				subv = v
   789  				destring = f.quoted
   790  				for _, i := range f.index {
   791  					if subv.Kind() == reflect.Pointer {
   792  						if subv.IsNil() {
   793  							// If a struct embeds a pointer to an unexported type,
   794  							// it is not possible to set a newly allocated value
   795  							// since the field is unexported.
   796  							//
   797  							// See https://golang.org/issue/21357
   798  							if !subv.CanSet() {
   799  								d.saveError(fmt.Errorf("json: cannot set embedded pointer to unexported struct: %v", subv.Type().Elem()))
   800  								// Invalidate subv to ensure d.value(subv) skips over
   801  								// the JSON value without assigning it to subv.
   802  								subv = reflect.Value{}
   803  								destring = false
   804  								break
   805  							}
   806  							subv.Set(reflect.New(subv.Type().Elem()))
   807  						}
   808  						subv = subv.Elem()
   809  					}
   810  					subv = subv.Field(i)
   811  				}
   812  				if d.errorContext == nil {
   813  					d.errorContext = new(errorContext)
   814  				}
   815  				d.errorContext.FieldStack = append(d.errorContext.FieldStack, f.name)
   816  				d.errorContext.Struct = t
   817  			} else if d.disallowUnknownFields {
   818  				d.saveError(fmt.Errorf("json: unknown field %q", key))
   819  			}
   820  		}
   821  
   822  		// Read : before value.
   823  		if d.opcode == scanSkipSpace {
   824  			d.scanWhile(scanSkipSpace)
   825  		}
   826  		if d.opcode != scanObjectKey {
   827  			panic(phasePanicMsg)
   828  		}
   829  		d.scanWhile(scanSkipSpace)
   830  
   831  		if destring {
   832  			switch qv := d.valueQuoted().(type) {
   833  			case nil:
   834  				if err := d.literalStore(nullLiteral, subv, false); err != nil {
   835  					return err
   836  				}
   837  			case string:
   838  				if err := d.literalStore([]byte(qv), subv, true); err != nil {
   839  					return err
   840  				}
   841  			default:
   842  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
   843  			}
   844  		} else {
   845  			if err := d.value(subv); err != nil {
   846  				return err
   847  			}
   848  		}
   849  
   850  		// Write value back to map;
   851  		// if using struct, subv points into struct already.
   852  		if v.Kind() == reflect.Map {
   853  			kt := t.Key()
   854  			var kv reflect.Value
   855  			switch {
   856  			case reflect.PointerTo(kt).Implements(textUnmarshalerType):
   857  				kv = reflect.New(kt)
   858  				if err := d.literalStore(item, kv, true); err != nil {
   859  					return err
   860  				}
   861  				kv = kv.Elem()
   862  			case kt.Kind() == reflect.String:
   863  				kv = reflect.ValueOf(key).Convert(kt)
   864  			default:
   865  				switch kt.Kind() {
   866  				case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   867  					s := string(key)
   868  					n, err := strconv.ParseInt(s, 10, 64)
   869  					if err != nil || reflect.Zero(kt).OverflowInt(n) {
   870  						d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
   871  						break
   872  					}
   873  					kv = reflect.ValueOf(n).Convert(kt)
   874  				case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   875  					s := string(key)
   876  					n, err := strconv.ParseUint(s, 10, 64)
   877  					if err != nil || reflect.Zero(kt).OverflowUint(n) {
   878  						d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: kt, Offset: int64(start + 1)})
   879  						break
   880  					}
   881  					kv = reflect.ValueOf(n).Convert(kt)
   882  				default:
   883  					panic("json: Unexpected key type") // should never occur
   884  				}
   885  			}
   886  			if kv.IsValid() {
   887  				v.SetMapIndex(kv, subv)
   888  			}
   889  		}
   890  
   891  		// Next token must be , or }.
   892  		if d.opcode == scanSkipSpace {
   893  			d.scanWhile(scanSkipSpace)
   894  		}
   895  		if d.errorContext != nil {
   896  			// Reset errorContext to its original state.
   897  			// Keep the same underlying array for FieldStack, to reuse the
   898  			// space and avoid unnecessary allocs.
   899  			d.errorContext.FieldStack = d.errorContext.FieldStack[:len(origErrorContext.FieldStack)]
   900  			d.errorContext.Struct = origErrorContext.Struct
   901  		}
   902  		if d.opcode == scanEndObject {
   903  			break
   904  		}
   905  		if d.opcode != scanObjectValue {
   906  			panic(phasePanicMsg)
   907  		}
   908  	}
   909  
   910  	if v.Kind() == reflect.Map {
   911  		d.lastKeys = keys
   912  	}
   913  	return nil
   914  }
   915  
   916  // convertNumber converts the number literal s to a float64 or a Number
   917  // depending on the setting of d.useNumber.
   918  func (d *decodeState) convertNumber(s string) (any, error) {
   919  	if d.useNumber {
   920  		return Number(s), nil
   921  	}
   922  	f, err := strconv.ParseFloat(s, 64)
   923  	if err != nil {
   924  		return nil, &UnmarshalTypeError{Value: "number " + s, Type: reflect.TypeOf(0.0), Offset: int64(d.off)}
   925  	}
   926  	return f, nil
   927  }
   928  
   929  var numberType = reflect.TypeOf(Number(""))
   930  
   931  // literalStore decodes a literal stored in item into v.
   932  //
   933  // fromQuoted indicates whether this literal came from unwrapping a
   934  // string from the ",string" struct tag option. this is used only to
   935  // produce more helpful error messages.
   936  func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) error {
   937  	// Check for unmarshaler.
   938  	if len(item) == 0 {
   939  		//Empty string given
   940  		d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   941  		return nil
   942  	}
   943  	isNull := item[0] == 'n' // null
   944  	u, ut, pv := indirect(v, isNull)
   945  	if u != nil {
   946  		return u.UnmarshalJSON(item)
   947  	}
   948  	if ut != nil {
   949  		if item[0] != '"' {
   950  			if fromQuoted {
   951  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   952  				return nil
   953  			}
   954  			val := "number"
   955  			switch item[0] {
   956  			case 'n':
   957  				val = "null"
   958  			case 't', 'f':
   959  				val = "bool"
   960  			}
   961  			d.saveError(&UnmarshalTypeError{Value: val, Type: v.Type(), Offset: int64(d.readIndex())})
   962  			return nil
   963  		}
   964  		s, ok := unquoteBytes(item)
   965  		if !ok {
   966  			if fromQuoted {
   967  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
   968  			}
   969  			panic(phasePanicMsg)
   970  		}
   971  		return ut.UnmarshalText(s)
   972  	}
   973  
   974  	v = pv
   975  
   976  	switch c := item[0]; c {
   977  	case 'n': // null
   978  		// The main parser checks that only true and false can reach here,
   979  		// but if this was a quoted string input, it could be anything.
   980  		if fromQuoted && string(item) != "null" {
   981  			d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   982  			break
   983  		}
   984  		switch v.Kind() {
   985  		case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice:
   986  			v.Set(reflect.Zero(v.Type()))
   987  			// otherwise, ignore null for primitives/string
   988  		}
   989  	case 't', 'f': // true, false
   990  		value := item[0] == 't'
   991  		// The main parser checks that only true and false can reach here,
   992  		// but if this was a quoted string input, it could be anything.
   993  		if fromQuoted && string(item) != "true" && string(item) != "false" {
   994  			d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   995  			break
   996  		}
   997  		switch v.Kind() {
   998  		default:
   999  			if fromQuoted {
  1000  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
  1001  			} else {
  1002  				d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
  1003  			}
  1004  		case reflect.Bool:
  1005  			v.SetBool(value)
  1006  		case reflect.Interface:
  1007  			if v.NumMethod() == 0 {
  1008  				v.Set(reflect.ValueOf(value))
  1009  			} else {
  1010  				d.saveError(&UnmarshalTypeError{Value: "bool", Type: v.Type(), Offset: int64(d.readIndex())})
  1011  			}
  1012  		}
  1013  
  1014  	case '"': // string
  1015  		s, ok := unquoteBytes(item)
  1016  		if !ok {
  1017  			if fromQuoted {
  1018  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
  1019  			}
  1020  			panic(phasePanicMsg)
  1021  		}
  1022  		switch v.Kind() {
  1023  		default:
  1024  			d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
  1025  		case reflect.Slice:
  1026  			if v.Type().Elem().Kind() != reflect.Uint8 {
  1027  				d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
  1028  				break
  1029  			}
  1030  			b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
  1031  			n, err := base64.StdEncoding.Decode(b, s)
  1032  			if err != nil {
  1033  				d.saveError(err)
  1034  				break
  1035  			}
  1036  			v.SetBytes(b[:n])
  1037  		case reflect.String:
  1038  			if v.Type() == numberType && !isValidNumber(string(s)) {
  1039  				return fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item)
  1040  			}
  1041  			v.SetString(string(s))
  1042  		case reflect.Interface:
  1043  			if v.NumMethod() == 0 {
  1044  				v.Set(reflect.ValueOf(string(s)))
  1045  			} else {
  1046  				d.saveError(&UnmarshalTypeError{Value: "string", Type: v.Type(), Offset: int64(d.readIndex())})
  1047  			}
  1048  		}
  1049  
  1050  	default: // number
  1051  		if c != '-' && (c < '0' || c > '9') {
  1052  			if fromQuoted {
  1053  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
  1054  			}
  1055  			panic(phasePanicMsg)
  1056  		}
  1057  		s := string(item)
  1058  		switch v.Kind() {
  1059  		default:
  1060  			if v.Kind() == reflect.String && v.Type() == numberType {
  1061  				// s must be a valid number, because it's
  1062  				// already been tokenized.
  1063  				v.SetString(s)
  1064  				break
  1065  			}
  1066  			if fromQuoted {
  1067  				return fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())
  1068  			}
  1069  			d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
  1070  		case reflect.Interface:
  1071  			n, err := d.convertNumber(s)
  1072  			if err != nil {
  1073  				d.saveError(err)
  1074  				break
  1075  			}
  1076  			if v.NumMethod() != 0 {
  1077  				d.saveError(&UnmarshalTypeError{Value: "number", Type: v.Type(), Offset: int64(d.readIndex())})
  1078  				break
  1079  			}
  1080  			v.Set(reflect.ValueOf(n))
  1081  
  1082  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1083  			n, err := strconv.ParseInt(s, 10, 64)
  1084  			if err != nil || v.OverflowInt(n) {
  1085  				d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())})
  1086  				break
  1087  			}
  1088  			v.SetInt(n)
  1089  
  1090  		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1091  			n, err := strconv.ParseUint(s, 10, 64)
  1092  			if err != nil || v.OverflowUint(n) {
  1093  				d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())})
  1094  				break
  1095  			}
  1096  			v.SetUint(n)
  1097  
  1098  		case reflect.Float32, reflect.Float64:
  1099  			n, err := strconv.ParseFloat(s, v.Type().Bits())
  1100  			if err != nil || v.OverflowFloat(n) {
  1101  				d.saveError(&UnmarshalTypeError{Value: "number " + s, Type: v.Type(), Offset: int64(d.readIndex())})
  1102  				break
  1103  			}
  1104  			v.SetFloat(n)
  1105  		}
  1106  	}
  1107  	return nil
  1108  }
  1109  
  1110  // The xxxInterface routines build up a value to be stored
  1111  // in an empty interface. They are not strictly necessary,
  1112  // but they avoid the weight of reflection in this common case.
  1113  
  1114  // valueInterface is like value but returns interface{}
  1115  func (d *decodeState) valueInterface() (val any) {
  1116  	switch d.opcode {
  1117  	default:
  1118  		panic(phasePanicMsg)
  1119  	case scanBeginArray:
  1120  		val = d.arrayInterface()
  1121  		d.scanNext()
  1122  	case scanBeginObject:
  1123  		val = d.objectInterface()
  1124  		d.scanNext()
  1125  	case scanBeginLiteral:
  1126  		val = d.literalInterface()
  1127  	}
  1128  	return
  1129  }
  1130  
  1131  // arrayInterface is like array but returns []interface{}.
  1132  func (d *decodeState) arrayInterface() []any {
  1133  	var v = make([]any, 0)
  1134  	for {
  1135  		// Look ahead for ] - can only happen on first iteration.
  1136  		d.scanWhile(scanSkipSpace)
  1137  		if d.opcode == scanEndArray {
  1138  			break
  1139  		}
  1140  
  1141  		v = append(v, d.valueInterface())
  1142  
  1143  		// Next token must be , or ].
  1144  		if d.opcode == scanSkipSpace {
  1145  			d.scanWhile(scanSkipSpace)
  1146  		}
  1147  		if d.opcode == scanEndArray {
  1148  			break
  1149  		}
  1150  		if d.opcode != scanArrayValue {
  1151  			panic(phasePanicMsg)
  1152  		}
  1153  	}
  1154  	return v
  1155  }
  1156  
  1157  // objectInterface is like object but returns map[string]interface{}.
  1158  func (d *decodeState) objectInterface() map[string]any {
  1159  	m := make(map[string]any)
  1160  	for {
  1161  		// Read opening " of string key or closing }.
  1162  		d.scanWhile(scanSkipSpace)
  1163  		if d.opcode == scanEndObject {
  1164  			// closing } - can only happen on first iteration.
  1165  			break
  1166  		}
  1167  		if d.opcode != scanBeginLiteral {
  1168  			panic(phasePanicMsg)
  1169  		}
  1170  
  1171  		// Read string key.
  1172  		start := d.readIndex()
  1173  		d.rescanLiteral()
  1174  		item := d.data[start:d.readIndex()]
  1175  		key, ok := unquote(item)
  1176  		if !ok {
  1177  			panic(phasePanicMsg)
  1178  		}
  1179  
  1180  		// Read : before value.
  1181  		if d.opcode == scanSkipSpace {
  1182  			d.scanWhile(scanSkipSpace)
  1183  		}
  1184  		if d.opcode != scanObjectKey {
  1185  			panic(phasePanicMsg)
  1186  		}
  1187  		d.scanWhile(scanSkipSpace)
  1188  
  1189  		// Read value.
  1190  		m[key] = d.valueInterface()
  1191  
  1192  		// Next token must be , or }.
  1193  		if d.opcode == scanSkipSpace {
  1194  			d.scanWhile(scanSkipSpace)
  1195  		}
  1196  		if d.opcode == scanEndObject {
  1197  			break
  1198  		}
  1199  		if d.opcode != scanObjectValue {
  1200  			panic(phasePanicMsg)
  1201  		}
  1202  	}
  1203  	return m
  1204  }
  1205  
  1206  // literalInterface consumes and returns a literal from d.data[d.off-1:] and
  1207  // it reads the following byte ahead. The first byte of the literal has been
  1208  // read already (that's how the caller knows it's a literal).
  1209  func (d *decodeState) literalInterface() any {
  1210  	// All bytes inside literal return scanContinue op code.
  1211  	start := d.readIndex()
  1212  	d.rescanLiteral()
  1213  
  1214  	item := d.data[start:d.readIndex()]
  1215  
  1216  	switch c := item[0]; c {
  1217  	case 'n': // null
  1218  		return nil
  1219  
  1220  	case 't', 'f': // true, false
  1221  		return c == 't'
  1222  
  1223  	case '"': // string
  1224  		s, ok := unquote(item)
  1225  		if !ok {
  1226  			panic(phasePanicMsg)
  1227  		}
  1228  		return s
  1229  
  1230  	default: // number
  1231  		if c != '-' && (c < '0' || c > '9') {
  1232  			panic(phasePanicMsg)
  1233  		}
  1234  		n, err := d.convertNumber(string(item))
  1235  		if err != nil {
  1236  			d.saveError(err)
  1237  		}
  1238  		return n
  1239  	}
  1240  }
  1241  
  1242  // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
  1243  // or it returns -1.
  1244  func getu4(s []byte) rune {
  1245  	if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
  1246  		return -1
  1247  	}
  1248  	var r rune
  1249  	for _, c := range s[2:6] {
  1250  		switch {
  1251  		case '0' <= c && c <= '9':
  1252  			c = c - '0'
  1253  		case 'a' <= c && c <= 'f':
  1254  			c = c - 'a' + 10
  1255  		case 'A' <= c && c <= 'F':
  1256  			c = c - 'A' + 10
  1257  		default:
  1258  			return -1
  1259  		}
  1260  		r = r*16 + rune(c)
  1261  	}
  1262  	return r
  1263  }
  1264  
  1265  // unquote converts a quoted JSON string literal s into an actual string t.
  1266  // The rules are different than for Go, so cannot use strconv.Unquote.
  1267  func unquote(s []byte) (t string, ok bool) {
  1268  	s, ok = unquoteBytes(s)
  1269  	t = string(s)
  1270  	return
  1271  }
  1272  
  1273  func unquoteBytes(s []byte) (t []byte, ok bool) {
  1274  	if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
  1275  		return
  1276  	}
  1277  	s = s[1 : len(s)-1]
  1278  
  1279  	// Check for unusual characters. If there are none,
  1280  	// then no unquoting is needed, so return a slice of the
  1281  	// original bytes.
  1282  	r := 0
  1283  	for r < len(s) {
  1284  		c := s[r]
  1285  		if c == '\\' || c == '"' || c < ' ' {
  1286  			break
  1287  		}
  1288  		if c < utf8.RuneSelf {
  1289  			r++
  1290  			continue
  1291  		}
  1292  		rr, size := utf8.DecodeRune(s[r:])
  1293  		if rr == utf8.RuneError && size == 1 {
  1294  			break
  1295  		}
  1296  		r += size
  1297  	}
  1298  	if r == len(s) {
  1299  		return s, true
  1300  	}
  1301  
  1302  	b := make([]byte, len(s)+2*utf8.UTFMax)
  1303  	w := copy(b, s[0:r])
  1304  	for r < len(s) {
  1305  		// Out of room? Can only happen if s is full of
  1306  		// malformed UTF-8 and we're replacing each
  1307  		// byte with RuneError.
  1308  		if w >= len(b)-2*utf8.UTFMax {
  1309  			nb := make([]byte, (len(b)+utf8.UTFMax)*2)
  1310  			copy(nb, b[0:w])
  1311  			b = nb
  1312  		}
  1313  		switch c := s[r]; {
  1314  		case c == '\\':
  1315  			r++
  1316  			if r >= len(s) {
  1317  				return
  1318  			}
  1319  			switch s[r] {
  1320  			default:
  1321  				return
  1322  			case '"', '\\', '/', '\'':
  1323  				b[w] = s[r]
  1324  				r++
  1325  				w++
  1326  			case 'b':
  1327  				b[w] = '\b'
  1328  				r++
  1329  				w++
  1330  			case 'f':
  1331  				b[w] = '\f'
  1332  				r++
  1333  				w++
  1334  			case 'n':
  1335  				b[w] = '\n'
  1336  				r++
  1337  				w++
  1338  			case 'r':
  1339  				b[w] = '\r'
  1340  				r++
  1341  				w++
  1342  			case 't':
  1343  				b[w] = '\t'
  1344  				r++
  1345  				w++
  1346  			case 'u':
  1347  				r--
  1348  				rr := getu4(s[r:])
  1349  				if rr < 0 {
  1350  					return
  1351  				}
  1352  				r += 6
  1353  				if utf16.IsSurrogate(rr) {
  1354  					rr1 := getu4(s[r:])
  1355  					if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
  1356  						// A valid pair; consume.
  1357  						r += 6
  1358  						w += utf8.EncodeRune(b[w:], dec)
  1359  						break
  1360  					}
  1361  					// Invalid surrogate; fall back to replacement rune.
  1362  					rr = unicode.ReplacementChar
  1363  				}
  1364  				w += utf8.EncodeRune(b[w:], rr)
  1365  			}
  1366  
  1367  		// Quote, control characters are invalid.
  1368  		case c == '"', c < ' ':
  1369  			return
  1370  
  1371  		// ASCII
  1372  		case c < utf8.RuneSelf:
  1373  			b[w] = c
  1374  			r++
  1375  			w++
  1376  
  1377  		// Coerce to well-formed UTF-8.
  1378  		default:
  1379  			rr, size := utf8.DecodeRune(s[r:])
  1380  			r += size
  1381  			w += utf8.EncodeRune(b[w:], rr)
  1382  		}
  1383  	}
  1384  	return b[0:w], true
  1385  }
  1386  

View as plain text