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

View as plain text