Source file src/encoding/json/decode.go

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

View as plain text