github.com/neilotoole/jsoncolor@v0.7.2-0.20231115150201-1637fae69be1/decode.go (about)

     1  package jsoncolor
     2  
     3  import (
     4  	"bytes"
     5  	"encoding"
     6  	"encoding/base64"
     7  	"encoding/json"
     8  	"errors"
     9  	"fmt"
    10  	"math"
    11  	"reflect"
    12  	"strconv"
    13  	"time"
    14  	"unsafe"
    15  )
    16  
    17  func (d decoder) decodeNull(b []byte, _ unsafe.Pointer) ([]byte, error) {
    18  	if hasNullPrefix(b) {
    19  		return b[4:], nil
    20  	}
    21  	return inputError(b, nullType)
    22  }
    23  
    24  func (d decoder) decodeBool(b []byte, p unsafe.Pointer) ([]byte, error) {
    25  	switch {
    26  	case hasTruePrefix(b):
    27  		*(*bool)(p) = true
    28  		return b[4:], nil
    29  
    30  	case hasFalsePrefix(b):
    31  		*(*bool)(p) = false
    32  		return b[5:], nil
    33  
    34  	case hasNullPrefix(b):
    35  		return b[4:], nil
    36  
    37  	default:
    38  		return inputError(b, boolType)
    39  	}
    40  }
    41  
    42  func (d decoder) decodeInt(b []byte, p unsafe.Pointer) ([]byte, error) {
    43  	if hasNullPrefix(b) {
    44  		return b[4:], nil
    45  	}
    46  
    47  	v, r, err := parseInt(b, intType)
    48  	if err != nil {
    49  		return r, err
    50  	}
    51  
    52  	*(*int)(p) = int(v)
    53  	return r, nil
    54  }
    55  
    56  func (d decoder) decodeInt8(b []byte, p unsafe.Pointer) ([]byte, error) {
    57  	if hasNullPrefix(b) {
    58  		return b[4:], nil
    59  	}
    60  
    61  	v, r, err := parseInt(b, int8Type)
    62  	if err != nil {
    63  		return r, err
    64  	}
    65  
    66  	if v < math.MinInt8 || v > math.MaxInt8 {
    67  		return r, unmarshalOverflow(b[:len(b)-len(r)], int8Type)
    68  	}
    69  
    70  	*(*int8)(p) = int8(v)
    71  	return r, nil
    72  }
    73  
    74  func (d decoder) decodeInt16(b []byte, p unsafe.Pointer) ([]byte, error) {
    75  	if hasNullPrefix(b) {
    76  		return b[4:], nil
    77  	}
    78  
    79  	v, r, err := parseInt(b, int16Type)
    80  	if err != nil {
    81  		return r, err
    82  	}
    83  
    84  	if v < math.MinInt16 || v > math.MaxInt16 {
    85  		return r, unmarshalOverflow(b[:len(b)-len(r)], int16Type)
    86  	}
    87  
    88  	*(*int16)(p) = int16(v)
    89  	return r, nil
    90  }
    91  
    92  func (d decoder) decodeInt32(b []byte, p unsafe.Pointer) ([]byte, error) {
    93  	if hasNullPrefix(b) {
    94  		return b[4:], nil
    95  	}
    96  
    97  	v, r, err := parseInt(b, int32Type)
    98  	if err != nil {
    99  		return r, err
   100  	}
   101  
   102  	if v < math.MinInt32 || v > math.MaxInt32 {
   103  		return r, unmarshalOverflow(b[:len(b)-len(r)], int32Type)
   104  	}
   105  
   106  	*(*int32)(p) = int32(v)
   107  	return r, nil
   108  }
   109  
   110  func (d decoder) decodeInt64(b []byte, p unsafe.Pointer) ([]byte, error) {
   111  	if hasNullPrefix(b) {
   112  		return b[4:], nil
   113  	}
   114  
   115  	v, r, err := parseInt(b, int64Type)
   116  	if err != nil {
   117  		return r, err
   118  	}
   119  
   120  	*(*int64)(p) = v
   121  	return r, nil
   122  }
   123  
   124  func (d decoder) decodeUint(b []byte, p unsafe.Pointer) ([]byte, error) {
   125  	if hasNullPrefix(b) {
   126  		return b[4:], nil
   127  	}
   128  
   129  	v, r, err := parseUint(b, uintType)
   130  	if err != nil {
   131  		return r, err
   132  	}
   133  
   134  	*(*uint)(p) = uint(v)
   135  	return r, nil
   136  }
   137  
   138  func (d decoder) decodeUintptr(b []byte, p unsafe.Pointer) ([]byte, error) {
   139  	if hasNullPrefix(b) {
   140  		return b[4:], nil
   141  	}
   142  
   143  	v, r, err := parseUint(b, uintptrType)
   144  	if err != nil {
   145  		return r, err
   146  	}
   147  
   148  	*(*uintptr)(p) = uintptr(v)
   149  	return r, nil
   150  }
   151  
   152  func (d decoder) decodeUint8(b []byte, p unsafe.Pointer) ([]byte, error) {
   153  	if hasNullPrefix(b) {
   154  		return b[4:], nil
   155  	}
   156  
   157  	v, r, err := parseUint(b, uint8Type)
   158  	if err != nil {
   159  		return r, err
   160  	}
   161  
   162  	if v > math.MaxUint8 {
   163  		return r, unmarshalOverflow(b[:len(b)-len(r)], uint8Type)
   164  	}
   165  
   166  	*(*uint8)(p) = uint8(v)
   167  	return r, nil
   168  }
   169  
   170  func (d decoder) decodeUint16(b []byte, p unsafe.Pointer) ([]byte, error) {
   171  	if hasNullPrefix(b) {
   172  		return b[4:], nil
   173  	}
   174  
   175  	v, r, err := parseUint(b, uint16Type)
   176  	if err != nil {
   177  		return r, err
   178  	}
   179  
   180  	if v > math.MaxUint16 {
   181  		return r, unmarshalOverflow(b[:len(b)-len(r)], uint16Type)
   182  	}
   183  
   184  	*(*uint16)(p) = uint16(v)
   185  	return r, nil
   186  }
   187  
   188  func (d decoder) decodeUint32(b []byte, p unsafe.Pointer) ([]byte, error) {
   189  	if hasNullPrefix(b) {
   190  		return b[4:], nil
   191  	}
   192  
   193  	v, r, err := parseUint(b, uint32Type)
   194  	if err != nil {
   195  		return r, err
   196  	}
   197  
   198  	if v > math.MaxUint32 {
   199  		return r, unmarshalOverflow(b[:len(b)-len(r)], uint32Type)
   200  	}
   201  
   202  	*(*uint32)(p) = uint32(v)
   203  	return r, nil
   204  }
   205  
   206  func (d decoder) decodeUint64(b []byte, p unsafe.Pointer) ([]byte, error) {
   207  	if hasNullPrefix(b) {
   208  		return b[4:], nil
   209  	}
   210  
   211  	v, r, err := parseUint(b, uint64Type)
   212  	if err != nil {
   213  		return r, err
   214  	}
   215  
   216  	*(*uint64)(p) = v
   217  	return r, nil
   218  }
   219  
   220  func (d decoder) decodeFloat32(b []byte, p unsafe.Pointer) ([]byte, error) {
   221  	if hasNullPrefix(b) {
   222  		return b[4:], nil
   223  	}
   224  
   225  	v, r, err := parseNumber(b)
   226  	if err != nil {
   227  		return inputError(b, float32Type)
   228  	}
   229  
   230  	f, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&v)), 32)
   231  	if err != nil {
   232  		return inputError(b, float32Type)
   233  	}
   234  
   235  	*(*float32)(p) = float32(f)
   236  	return r, nil
   237  }
   238  
   239  func (d decoder) decodeFloat64(b []byte, p unsafe.Pointer) ([]byte, error) {
   240  	if hasNullPrefix(b) {
   241  		return b[4:], nil
   242  	}
   243  
   244  	v, r, err := parseNumber(b)
   245  	if err != nil {
   246  		return inputError(b, float64Type)
   247  	}
   248  
   249  	f, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&v)), 64)
   250  	if err != nil {
   251  		return inputError(b, float64Type)
   252  	}
   253  
   254  	*(*float64)(p) = f
   255  	return r, nil
   256  }
   257  
   258  func (d decoder) decodeNumber(b []byte, p unsafe.Pointer) ([]byte, error) {
   259  	if hasNullPrefix(b) {
   260  		return b[4:], nil
   261  	}
   262  
   263  	v, r, err := parseNumber(b)
   264  	if err != nil {
   265  		return inputError(b, numberType)
   266  	}
   267  
   268  	if (d.flags & DontCopyNumber) != 0 {
   269  		*(*Number)(p) = *(*Number)(unsafe.Pointer(&v))
   270  	} else {
   271  		*(*Number)(p) = Number(v)
   272  	}
   273  
   274  	return r, nil
   275  }
   276  
   277  func (d decoder) decodeString(b []byte, p unsafe.Pointer) ([]byte, error) {
   278  	if hasNullPrefix(b) {
   279  		return b[4:], nil
   280  	}
   281  
   282  	s, r, isNew, err := parseStringUnquote(b, nil)
   283  	if err != nil {
   284  		if len(b) == 0 || b[0] != '"' {
   285  			return inputError(b, stringType)
   286  		}
   287  		return r, err
   288  	}
   289  
   290  	if isNew || (d.flags&DontCopyString) != 0 {
   291  		*(*string)(p) = *(*string)(unsafe.Pointer(&s))
   292  	} else {
   293  		*(*string)(p) = string(s)
   294  	}
   295  
   296  	return r, nil
   297  }
   298  
   299  func (d decoder) decodeFromString(b []byte, p unsafe.Pointer, decode decodeFunc) ([]byte, error) {
   300  	if hasNullPrefix(b) {
   301  		return decode(d, b, p)
   302  	}
   303  
   304  	v, b, _, err := parseStringUnquote(b, nil)
   305  	if err != nil {
   306  		return inputError(v, stringType)
   307  	}
   308  
   309  	if v, err = decode(d, v, p); err != nil {
   310  		return b, err
   311  	}
   312  
   313  	if v = skipSpaces(v); len(v) != 0 {
   314  		return b, syntaxError(v, "unexpected trailing tokens after string value")
   315  	}
   316  
   317  	return b, nil
   318  }
   319  
   320  func (d decoder) decodeFromStringToInt(b []byte, p unsafe.Pointer, t reflect.Type, decode decodeFunc) ([]byte, error) {
   321  	if hasPrefix(b, "null") {
   322  		return decode(d, b, p)
   323  	}
   324  
   325  	if len(b) > 0 && b[0] != '"' {
   326  		v, r, err := parseNumber(b)
   327  		if err == nil {
   328  			// The encoding/json package will return a *json.UnmarshalTypeError if
   329  			// the input was a floating point number representation, even tho a
   330  			// string is expected here.
   331  			isFloat := true
   332  			switch {
   333  			case bytes.IndexByte(v, '.') >= 0:
   334  			case bytes.IndexByte(v, 'e') >= 0:
   335  			case bytes.IndexByte(v, 'E') >= 0:
   336  			default:
   337  				isFloat = false
   338  			}
   339  			if isFloat {
   340  				_, err := strconv.ParseFloat(*(*string)(unsafe.Pointer(&v)), 64)
   341  				if err != nil {
   342  					return r, unmarshalTypeError(v, t)
   343  				}
   344  			}
   345  		}
   346  		return r, fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into int")
   347  	}
   348  
   349  	if len(b) > 1 && b[0] == '"' && b[1] == '"' {
   350  		return b, fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal \"\" into int")
   351  	}
   352  
   353  	v, b, _, err := parseStringUnquote(b, nil)
   354  	if err != nil {
   355  		return inputError(v, t)
   356  	}
   357  
   358  	if hasLeadingZeroes(v) {
   359  		// In this context the encoding/json package accepts leading zeroes because
   360  		// it is not constrained by the JSON syntax, remove them so the parsing
   361  		// functions don't return syntax errors.
   362  		u := make([]byte, 0, len(v))
   363  		i := 0
   364  
   365  		if i < len(v) && v[i] == '-' || v[i] == '+' {
   366  			u = append(u, v[i])
   367  			i++
   368  		}
   369  
   370  		for (i+1) < len(v) && v[i] == '0' && '0' <= v[i+1] && v[i+1] <= '9' {
   371  			i++
   372  		}
   373  
   374  		v = append(u, v[i:]...)
   375  	}
   376  
   377  	var r []byte
   378  	if r, err = decode(d, v, p); err != nil {
   379  		var e *SyntaxError
   380  		if errors.As(err, &e) {
   381  			if hasPrefix(v, "-") {
   382  				// The standard library interprets sequences of '-' characters
   383  				// as numbers but still returns type errors in this case...
   384  				return b, unmarshalTypeError(v, t)
   385  			}
   386  			return b, fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into int", prefix(v))
   387  		}
   388  		// When the input value was a valid number representation we retain the
   389  		// error returned by the decoder.
   390  		if _, _, err2 := parseNumber(v); err2 != nil {
   391  			// When the input value valid JSON we mirror the behavior of the
   392  			// encoding/json package and return a generic error.
   393  			if _, _, err2 = parseValue(v); err2 == nil {
   394  				return b, fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into int", prefix(v))
   395  			}
   396  		}
   397  		return b, err
   398  	} else if len(r) != 0 {
   399  		return r, unmarshalTypeError(v, t)
   400  	}
   401  
   402  	return b, nil
   403  }
   404  
   405  func (d decoder) decodeBytes(b []byte, p unsafe.Pointer) ([]byte, error) {
   406  	if hasNullPrefix(b) {
   407  		*(*[]byte)(p) = nil
   408  		return b[4:], nil
   409  	}
   410  
   411  	if len(b) < 2 {
   412  		return inputError(b, bytesType)
   413  	}
   414  
   415  	if b[0] != '"' {
   416  		// Go 1.7- behavior: bytes slices may be decoded from array of integers.
   417  		if len(b) > 0 && b[0] == '[' {
   418  			return d.decodeSlice(b, p, 1, bytesType, decoder.decodeUint8)
   419  		}
   420  		return inputError(b, bytesType)
   421  	}
   422  
   423  	// The input string contains escaped sequences, we need to parse it before
   424  	// decoding it to match the encoding/json package behvaior.
   425  	src, r, _, err := parseStringUnquote(b, nil)
   426  	if err != nil {
   427  		return inputError(b, bytesType)
   428  	}
   429  
   430  	dst := make([]byte, base64.StdEncoding.DecodedLen(len(src)))
   431  
   432  	n, err := base64.StdEncoding.Decode(dst, src)
   433  	if err != nil {
   434  		return r, err
   435  	}
   436  
   437  	*(*[]byte)(p) = dst[:n]
   438  	return r, nil
   439  }
   440  
   441  func (d decoder) decodeDuration(b []byte, p unsafe.Pointer) ([]byte, error) {
   442  	if hasNullPrefix(b) {
   443  		return b[4:], nil
   444  	}
   445  
   446  	// In order to interoperate with the stdlib, we must be able to interpret
   447  	// durations passed as integer values.  there's some discussion about being
   448  	// flexible on how durations are formatted, but for the time being, it's
   449  	// been punted to go2 at the earliest: https://github.com/golang/go/issues/4712
   450  	if len(b) > 0 && b[0] != '"' {
   451  		v, r, err := parseInt(b, durationType)
   452  		if err != nil {
   453  			return inputError(b, int32Type)
   454  		}
   455  
   456  		*(*time.Duration)(p) = time.Duration(v)
   457  		return r, nil
   458  	}
   459  
   460  	if len(b) < 2 || b[0] != '"' {
   461  		return inputError(b, durationType)
   462  	}
   463  
   464  	i := bytes.IndexByte(b[1:], '"') + 1
   465  	if i <= 0 {
   466  		return inputError(b, durationType)
   467  	}
   468  
   469  	s := b[1:i] // trim quotes
   470  
   471  	v, err := time.ParseDuration(*(*string)(unsafe.Pointer(&s)))
   472  	if err != nil {
   473  		return inputError(b, durationType)
   474  	}
   475  
   476  	*(*time.Duration)(p) = v
   477  	return b[i+1:], nil
   478  }
   479  
   480  func (d decoder) decodeTime(b []byte, p unsafe.Pointer) ([]byte, error) {
   481  	if hasNullPrefix(b) {
   482  		return b[4:], nil
   483  	}
   484  
   485  	if len(b) < 2 || b[0] != '"' {
   486  		return inputError(b, timeType)
   487  	}
   488  
   489  	i := bytes.IndexByte(b[1:], '"') + 1
   490  	if i <= 0 {
   491  		return inputError(b, timeType)
   492  	}
   493  
   494  	s := b[1:i] // trim quotes
   495  
   496  	v, err := time.Parse(time.RFC3339Nano, *(*string)(unsafe.Pointer(&s)))
   497  	if err != nil {
   498  		return inputError(b, timeType)
   499  	}
   500  
   501  	*(*time.Time)(p) = v
   502  	return b[i+1:], nil
   503  }
   504  
   505  func (d decoder) decodeArray(b []byte, p unsafe.Pointer, n int, size uintptr, t reflect.Type, decode decodeFunc) ([]byte, error) {
   506  	if hasNullPrefix(b) {
   507  		return b[4:], nil
   508  	}
   509  
   510  	if len(b) < 2 || b[0] != '[' {
   511  		return inputError(b, t)
   512  	}
   513  	b = b[1:]
   514  
   515  	var err error
   516  	for i := 0; i < n; i++ {
   517  		b = skipSpaces(b)
   518  
   519  		if i != 0 {
   520  			if len(b) == 0 {
   521  				return b, syntaxError(b, "unexpected EOF after array element")
   522  			}
   523  			switch b[0] {
   524  			case ',':
   525  				b = skipSpaces(b[1:])
   526  			case ']':
   527  				return b[1:], nil
   528  			default:
   529  				return b, syntaxError(b, "expected ',' after array element but found '%c'", b[0])
   530  			}
   531  		}
   532  
   533  		b, err = decode(d, b, unsafe.Pointer(uintptr(p)+(uintptr(i)*size)))
   534  		if err != nil {
   535  			var e *UnmarshalTypeError
   536  			if errors.As(err, &e) {
   537  				e.Struct = t.String() + e.Struct
   538  				e.Field = strconv.Itoa(i) + "." + e.Field
   539  			}
   540  			return b, err
   541  		}
   542  	}
   543  
   544  	// The encoding/json package ignores extra elements found when decoding into
   545  	// array types (which have a fixed size).
   546  	for {
   547  		b = skipSpaces(b)
   548  
   549  		if len(b) == 0 {
   550  			return b, syntaxError(b, "missing closing ']' in array value")
   551  		}
   552  
   553  		switch b[0] {
   554  		case ',':
   555  			b = skipSpaces(b[1:])
   556  		case ']':
   557  			return b[1:], nil
   558  		}
   559  
   560  		_, b, err = parseValue(b)
   561  		if err != nil {
   562  			return b, err
   563  		}
   564  	}
   565  }
   566  
   567  // This is a placeholder used to construct non-nil empty slices.
   568  var empty struct{}
   569  
   570  func (d decoder) decodeSlice(b []byte, p unsafe.Pointer, size uintptr, t reflect.Type, decode decodeFunc) ([]byte, error) {
   571  	if hasNullPrefix(b) {
   572  		*(*slice)(p) = slice{}
   573  		return b[4:], nil
   574  	}
   575  
   576  	if len(b) < 2 {
   577  		return inputError(b, t)
   578  	}
   579  
   580  	if b[0] != '[' {
   581  		// Go 1.7- behavior: fallback to decoding as a []byte if the element
   582  		// type is byte; allow conversions from JSON strings even tho the
   583  		// underlying type implemented unmarshaler interfaces.
   584  		if t.Elem().Kind() == reflect.Uint8 {
   585  			return d.decodeBytes(b, p)
   586  		}
   587  		return inputError(b, t)
   588  	}
   589  
   590  	input := b
   591  	b = b[1:]
   592  
   593  	s := (*slice)(p)
   594  	s.len = 0
   595  
   596  	var err error
   597  	for {
   598  		b = skipSpaces(b)
   599  
   600  		if len(b) != 0 && b[0] == ']' {
   601  			if s.data == nil {
   602  				s.data = unsafe.Pointer(&empty)
   603  			}
   604  			return b[1:], nil
   605  		}
   606  
   607  		if s.len != 0 {
   608  			if len(b) == 0 {
   609  				return b, syntaxError(b, "unexpected EOF after array element")
   610  			}
   611  			if b[0] != ',' {
   612  				return b, syntaxError(b, "expected ',' after array element but found '%c'", b[0])
   613  			}
   614  			b = skipSpaces(b[1:])
   615  		}
   616  
   617  		if s.len == s.cap {
   618  			c := s.cap
   619  
   620  			if c == 0 {
   621  				c = 10
   622  			} else {
   623  				c *= 2
   624  			}
   625  
   626  			*s = extendSlice(t, s, c)
   627  		}
   628  
   629  		b, err = decode(d, b, unsafe.Pointer(uintptr(s.data)+(uintptr(s.len)*size)))
   630  		if err != nil {
   631  			_, r, err2 := parseValue(input)
   632  			if err2 != nil {
   633  				return r, err2
   634  			}
   635  			b = r
   636  
   637  			var e *UnmarshalTypeError
   638  			if errors.As(err, &e) {
   639  				e.Struct = t.String() + e.Struct
   640  				e.Field = strconv.Itoa(s.len) + "." + e.Field
   641  			}
   642  			return b, err
   643  		}
   644  
   645  		s.len++
   646  	}
   647  }
   648  
   649  func (d decoder) decodeMap(b []byte, p unsafe.Pointer, t, kt, vt reflect.Type, kz, vz reflect.Value, decodeKey, decodeValue decodeFunc) ([]byte, error) {
   650  	if hasNullPrefix(b) {
   651  		*(*unsafe.Pointer)(p) = nil
   652  		return b[4:], nil
   653  	}
   654  
   655  	if len(b) < 2 || b[0] != '{' {
   656  		return inputError(b, t)
   657  	}
   658  	i := 0
   659  	m := reflect.NewAt(t, p).Elem()
   660  
   661  	k := reflect.New(kt).Elem()
   662  	v := reflect.New(vt).Elem()
   663  
   664  	kptr := (*iface)(unsafe.Pointer(&k)).ptr
   665  	vptr := (*iface)(unsafe.Pointer(&v)).ptr
   666  	input := b
   667  
   668  	if m.IsNil() {
   669  		m = reflect.MakeMap(t)
   670  	}
   671  
   672  	var err error
   673  	b = b[1:]
   674  	for {
   675  		k.Set(kz)
   676  		v.Set(vz)
   677  		b = skipSpaces(b)
   678  
   679  		if len(b) != 0 && b[0] == '}' {
   680  			*(*unsafe.Pointer)(p) = unsafe.Pointer(m.Pointer())
   681  			return b[1:], nil
   682  		}
   683  
   684  		if i != 0 {
   685  			if len(b) == 0 {
   686  				return b, syntaxError(b, "unexpected end of JONS input after object field value")
   687  			}
   688  			if b[0] != ',' {
   689  				return b, syntaxError(b, "expected ',' after object field value but found '%c'", b[0])
   690  			}
   691  			b = skipSpaces(b[1:])
   692  		}
   693  
   694  		if hasPrefix(b, "null") {
   695  			return b, syntaxError(b, "cannot decode object key string from 'null' value")
   696  		}
   697  
   698  		if b, err = decodeKey(d, b, kptr); err != nil {
   699  			return objectKeyError(b, err)
   700  		}
   701  		b = skipSpaces(b)
   702  
   703  		if len(b) == 0 {
   704  			return b, syntaxError(b, "unexpected end of JSON input after object field key")
   705  		}
   706  		if b[0] != ':' {
   707  			return b, syntaxError(b, "expected ':' after object field key but found '%c'", b[0])
   708  		}
   709  		b = skipSpaces(b[1:])
   710  
   711  		if b, err = decodeValue(d, b, vptr); err != nil {
   712  			_, r, err2 := parseValue(input)
   713  			if err2 != nil {
   714  				return r, err2
   715  			}
   716  			b = r
   717  			var e *UnmarshalTypeError
   718  			if errors.As(err, &e) {
   719  				e.Struct = "map[" + kt.String() + "]" + vt.String() + "{" + e.Struct + "}"
   720  				e.Field = fmt.Sprint(k.Interface()) + "." + e.Field
   721  			}
   722  			return b, err
   723  		}
   724  
   725  		m.SetMapIndex(k, v)
   726  		i++
   727  	}
   728  }
   729  
   730  func (d decoder) decodeMapStringInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
   731  	if hasNullPrefix(b) {
   732  		*(*unsafe.Pointer)(p) = nil
   733  		return b[4:], nil
   734  	}
   735  
   736  	if len(b) < 2 || b[0] != '{' {
   737  		return inputError(b, mapStringInterfaceType)
   738  	}
   739  
   740  	m := *(*map[string]interface{})(p)
   741  	if m == nil {
   742  		m = make(map[string]interface{}, 64)
   743  	}
   744  
   745  	input := b
   746  	b = b[1:]
   747  	for i := 0; ; i++ {
   748  		var key string
   749  		var val interface{}
   750  		var err error
   751  
   752  		b = skipSpaces(b)
   753  		if len(b) != 0 && b[0] == '}' {
   754  			*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(unsafe.Pointer(&m))
   755  			return b[1:], nil
   756  		}
   757  
   758  		b, err = d.preprocessInput(i, b, &key)
   759  		if err != nil {
   760  			return b, err
   761  		}
   762  
   763  		b, err = d.decodeInterface(b, unsafe.Pointer(&val))
   764  		if err != nil {
   765  			_, r, err2 := parseValue(input)
   766  			if err2 != nil {
   767  				return r, err2
   768  			}
   769  			b = r
   770  			var e *UnmarshalTypeError
   771  			if errors.As(err, &e) {
   772  				e.Struct = mapStringInterfaceType.String() + e.Struct
   773  				e.Field = key + "." + e.Field
   774  			}
   775  			return b, err
   776  		}
   777  
   778  		m[key] = val
   779  	}
   780  }
   781  
   782  func (d decoder) decodeMapStringRawMessage(b []byte, p unsafe.Pointer) ([]byte, error) {
   783  	if hasNullPrefix(b) {
   784  		*(*unsafe.Pointer)(p) = nil
   785  		return b[4:], nil
   786  	}
   787  
   788  	if len(b) < 2 || b[0] != '{' {
   789  		return inputError(b, mapStringRawMessageType)
   790  	}
   791  
   792  	m := *(*map[string]RawMessage)(p)
   793  	if m == nil {
   794  		m = make(map[string]RawMessage, 64)
   795  	}
   796  
   797  	input := b
   798  	b = b[1:]
   799  	for i := 0; ; i++ {
   800  		var err error
   801  		var key string
   802  		var val RawMessage
   803  
   804  		b = skipSpaces(b)
   805  
   806  		if len(b) != 0 && b[0] == '}' {
   807  			*(*unsafe.Pointer)(p) = *(*unsafe.Pointer)(unsafe.Pointer(&m))
   808  			return b[1:], nil
   809  		}
   810  
   811  		b, err = d.preprocessInput(i, b, &key)
   812  		if err != nil {
   813  			return b, err
   814  		}
   815  
   816  		b, err = d.decodeRawMessage(b, unsafe.Pointer(&val))
   817  		if err != nil {
   818  			_, r, err2 := parseValue(input)
   819  			if err2 != nil {
   820  				return r, err2
   821  			}
   822  			b = r
   823  
   824  			var e *UnmarshalTypeError
   825  			if errors.As(err, &e) {
   826  				e.Struct = mapStringRawMessageType.String() + e.Struct
   827  				e.Field = key + "." + e.Field
   828  			}
   829  			return b, err
   830  		}
   831  
   832  		m[key] = val
   833  	}
   834  }
   835  
   836  func (d decoder) preprocessInput(idx int, b []byte, key *string) ([]byte, error) {
   837  	if idx != 0 {
   838  		if len(b) == 0 {
   839  			return b, syntaxError(b, "unexpected end of JSON input after object field value")
   840  		}
   841  		if b[0] != ',' {
   842  			return b, syntaxError(b, "expected ',' after object field value but found '%c'", b[0])
   843  		}
   844  		b = skipSpaces(b[1:])
   845  	}
   846  
   847  	if hasPrefix(b, "null") {
   848  		return b, syntaxError(b, "cannot decode object key string from 'null' value")
   849  	}
   850  
   851  	b, err := d.decodeString(b, unsafe.Pointer(key))
   852  	if err != nil {
   853  		return objectKeyError(b, err)
   854  	}
   855  	b = skipSpaces(b)
   856  
   857  	if len(b) == 0 {
   858  		return b, syntaxError(b, "unexpected end of JSON input after object field key")
   859  	}
   860  	if b[0] != ':' {
   861  		return b, syntaxError(b, "expected ':' after object field key but found '%c'", b[0])
   862  	}
   863  	b = skipSpaces(b[1:])
   864  
   865  	return b, nil
   866  }
   867  
   868  func (d decoder) decodeStruct(b []byte, p unsafe.Pointer, st *structType) ([]byte, error) {
   869  	if hasNullPrefix(b) {
   870  		return b[4:], nil
   871  	}
   872  
   873  	if len(b) < 2 || b[0] != '{' {
   874  		return inputError(b, st.typ)
   875  	}
   876  
   877  	var err error
   878  	var k []byte
   879  	var i int
   880  
   881  	// memory buffer used to convert short field names to lowercase
   882  	var buf [64]byte
   883  	var key []byte
   884  	input := b
   885  
   886  	b = b[1:]
   887  	for {
   888  		b = skipSpaces(b)
   889  
   890  		if len(b) != 0 && b[0] == '}' {
   891  			return b[1:], nil
   892  		}
   893  
   894  		if i != 0 {
   895  			if len(b) == 0 {
   896  				return b, syntaxError(b, "unexpected end of JSON input after object field value")
   897  			}
   898  			if b[0] != ',' {
   899  				return b, syntaxError(b, "expected ',' after object field value but found '%c'", b[0])
   900  			}
   901  			b = skipSpaces(b[1:])
   902  		}
   903  		i++
   904  
   905  		if hasPrefix(b, "null") {
   906  			return b, syntaxError(b, "cannot decode object key string from 'null' value")
   907  		}
   908  
   909  		k, b, _, err = parseStringUnquote(b, nil)
   910  		if err != nil {
   911  			return objectKeyError(b, err)
   912  		}
   913  		b = skipSpaces(b)
   914  
   915  		if len(b) == 0 {
   916  			return b, syntaxError(b, "unexpected end of JSON input after object field key")
   917  		}
   918  		if b[0] != ':' {
   919  			return b, syntaxError(b, "expected ':' after object field key but found '%c'", b[0])
   920  		}
   921  		b = skipSpaces(b[1:])
   922  
   923  		f := st.fieldsIndex[string(k)]
   924  
   925  		if f == nil && (d.flags&DontMatchCaseInsensitiveStructFields) == 0 {
   926  			key = appendToLower(buf[:0], k)
   927  			f = st.ficaseIndex[string(key)]
   928  		}
   929  
   930  		if f == nil {
   931  			if (d.flags & DisallowUnknownFields) != 0 {
   932  				return b, fmt.Errorf("json: unknown field %q", k)
   933  			}
   934  			if _, b, err = parseValue(b); err != nil {
   935  				return b, err
   936  			}
   937  			continue
   938  		}
   939  
   940  		if b, err = f.codec.decode(d, b, unsafe.Pointer(uintptr(p)+f.offset)); err != nil {
   941  			_, r, err2 := parseValue(input)
   942  			if err2 != nil {
   943  				return r, err2
   944  			}
   945  			b = r
   946  
   947  			var e *UnmarshalTypeError
   948  			if errors.As(err, &e) {
   949  				e.Struct = st.typ.String() + e.Struct
   950  				e.Field = string(k) + "." + e.Field
   951  			}
   952  			return b, err
   953  		}
   954  	}
   955  }
   956  
   957  func (d decoder) decodeEmbeddedStructPointer(b []byte, p unsafe.Pointer, t reflect.Type, unexported bool, offset uintptr, decode decodeFunc) ([]byte, error) {
   958  	v := *(*unsafe.Pointer)(p)
   959  
   960  	if v == nil {
   961  		if unexported {
   962  			return nil, fmt.Errorf("json: cannot set embedded pointer to unexported struct: %s", t)
   963  		}
   964  		v = unsafe.Pointer(reflect.New(t).Pointer())
   965  		*(*unsafe.Pointer)(p) = v
   966  	}
   967  
   968  	return decode(d, b, unsafe.Pointer(uintptr(v)+offset))
   969  }
   970  
   971  func (d decoder) decodePointer(b []byte, p unsafe.Pointer, t reflect.Type, decode decodeFunc) ([]byte, error) {
   972  	if hasNullPrefix(b) {
   973  		pp := *(*unsafe.Pointer)(p)
   974  		if pp != nil && t.Kind() == reflect.Ptr {
   975  			return decode(d, b, pp)
   976  		}
   977  		*(*unsafe.Pointer)(p) = nil
   978  		return b[4:], nil
   979  	}
   980  
   981  	v := *(*unsafe.Pointer)(p)
   982  	if v == nil {
   983  		v = unsafe.Pointer(reflect.New(t).Pointer())
   984  		*(*unsafe.Pointer)(p) = v
   985  	}
   986  
   987  	return decode(d, b, v)
   988  }
   989  
   990  func (d decoder) decodeInterface(b []byte, p unsafe.Pointer) ([]byte, error) {
   991  	val := *(*interface{})(p)
   992  	*(*interface{})(p) = nil
   993  
   994  	if t := reflect.TypeOf(val); t != nil && t.Kind() == reflect.Ptr {
   995  		if v := reflect.ValueOf(val); v.IsNil() || t.Elem().Kind() != reflect.Ptr {
   996  			// If the destination is nil the only value that is OK to decode is
   997  			// `null`, and the encoding/json package always nils the destination
   998  			// interface value in this case.
   999  			if hasNullPrefix(b) {
  1000  				*(*interface{})(p) = nil
  1001  				return b[4:], nil
  1002  			}
  1003  		}
  1004  
  1005  		parsedBytes, err := Parse(b, val, d.flags)
  1006  		if err == nil {
  1007  			*(*interface{})(p) = val
  1008  		}
  1009  		return parsedBytes, err
  1010  	}
  1011  
  1012  	v, b, err := parseValue(b)
  1013  	if err != nil {
  1014  		return b, err
  1015  	}
  1016  
  1017  	switch v[0] {
  1018  	case '{':
  1019  		m := make(map[string]interface{})
  1020  		v, err = d.decodeMapStringInterface(v, unsafe.Pointer(&m))
  1021  		val = m
  1022  
  1023  	case '[':
  1024  		a := make([]interface{}, 0, 10)
  1025  		v, err = d.decodeSlice(v, unsafe.Pointer(&a), unsafe.Sizeof(a[0]), sliceInterfaceType, decoder.decodeInterface)
  1026  		val = a
  1027  
  1028  	case '"':
  1029  		s := ""
  1030  		v, err = d.decodeString(v, unsafe.Pointer(&s))
  1031  		val = s
  1032  
  1033  	case 'n':
  1034  		v, err = d.decodeNull(v, nil)
  1035  		val = nil
  1036  
  1037  	case 't', 'f':
  1038  		x := false
  1039  		v, err = d.decodeBool(v, unsafe.Pointer(&x))
  1040  		val = x
  1041  
  1042  	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  1043  		if (d.flags & UseNumber) != 0 {
  1044  			n := Number("")
  1045  			v, err = d.decodeNumber(v, unsafe.Pointer(&n))
  1046  			val = n
  1047  		} else {
  1048  			f := 0.0
  1049  			v, err = d.decodeFloat64(v, unsafe.Pointer(&f))
  1050  			val = f
  1051  		}
  1052  
  1053  	default:
  1054  		return b, syntaxError(v, "expected token but found '%c'", v[0])
  1055  	}
  1056  
  1057  	if err != nil {
  1058  		return b, err
  1059  	}
  1060  
  1061  	if v = skipSpaces(v); len(v) != 0 {
  1062  		return b, syntaxError(v, "unexpected trailing trailing tokens after json value")
  1063  	}
  1064  
  1065  	*(*interface{})(p) = val
  1066  	return b, nil
  1067  }
  1068  
  1069  func (d decoder) decodeMaybeEmptyInterface(b []byte, p unsafe.Pointer, t reflect.Type) ([]byte, error) {
  1070  	if hasNullPrefix(b) {
  1071  		*(*interface{})(p) = nil
  1072  		return b[4:], nil
  1073  	}
  1074  
  1075  	if x := reflect.NewAt(t, p).Elem(); !x.IsNil() {
  1076  		if e := x.Elem(); e.Kind() == reflect.Ptr {
  1077  			return Parse(b, e.Interface(), d.flags)
  1078  		}
  1079  	} else if t.NumMethod() == 0 { // empty interface
  1080  		return Parse(b, (*interface{})(p), d.flags)
  1081  	}
  1082  
  1083  	return d.decodeUnmarshalTypeError(b, p, t)
  1084  }
  1085  
  1086  func (d decoder) decodeUnmarshalTypeError(b []byte, _ unsafe.Pointer, t reflect.Type) ([]byte, error) {
  1087  	v, b, err := parseValue(b)
  1088  	if err != nil {
  1089  		return b, err
  1090  	}
  1091  	return b, &UnmarshalTypeError{
  1092  		Value: string(v),
  1093  		Type:  t,
  1094  	}
  1095  }
  1096  
  1097  func (d decoder) decodeRawMessage(b []byte, p unsafe.Pointer) ([]byte, error) {
  1098  	v, r, err := parseValue(b)
  1099  	if err != nil {
  1100  		return inputError(b, rawMessageType)
  1101  	}
  1102  
  1103  	if (d.flags & DontCopyRawMessage) == 0 {
  1104  		v = append(make([]byte, 0, len(v)), v...)
  1105  	}
  1106  
  1107  	*(*RawMessage)(p) = json.RawMessage(v)
  1108  	return r, err
  1109  }
  1110  
  1111  func (d decoder) decodeJSONUnmarshaler(b []byte, p unsafe.Pointer, t reflect.Type, pointer bool) ([]byte, error) {
  1112  	v, b, err := parseValue(b)
  1113  	if err != nil {
  1114  		return b, err
  1115  	}
  1116  
  1117  	if len(v) != 0 && v[0] == 'n' { // null
  1118  		return b, nil
  1119  	}
  1120  
  1121  	u := reflect.NewAt(t, p)
  1122  	if !pointer {
  1123  		u = u.Elem()
  1124  		t = t.Elem()
  1125  	}
  1126  	if u.IsNil() {
  1127  		u.Set(reflect.New(t))
  1128  	}
  1129  	return b, u.Interface().(Unmarshaler).UnmarshalJSON(v)
  1130  }
  1131  
  1132  func (d decoder) decodeTextUnmarshaler(b []byte, p unsafe.Pointer, t reflect.Type, pointer bool) ([]byte, error) {
  1133  	var value string
  1134  
  1135  	v, b, err := parseValue(b)
  1136  	if err != nil {
  1137  		return b, err
  1138  	}
  1139  	if len(v) == 0 {
  1140  		return inputError(v, t)
  1141  	}
  1142  
  1143  	switch v[0] {
  1144  	case 'n':
  1145  		_, _, err := parseNull(v)
  1146  		return b, err
  1147  	case '"':
  1148  		s, _, _, err := parseStringUnquote(v, nil)
  1149  		if err != nil {
  1150  			return b, err
  1151  		}
  1152  		u := reflect.NewAt(t, p)
  1153  		if !pointer {
  1154  			u = u.Elem()
  1155  			t = t.Elem()
  1156  		}
  1157  		if u.IsNil() {
  1158  			u.Set(reflect.New(t))
  1159  		}
  1160  		return b, u.Interface().(encoding.TextUnmarshaler).UnmarshalText(s)
  1161  	case '{':
  1162  		value = "object"
  1163  	case '[':
  1164  		value = "array"
  1165  	case 't':
  1166  		value = "true"
  1167  	case 'f':
  1168  		value = "false"
  1169  	case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
  1170  		value = "number"
  1171  	}
  1172  
  1173  	return b, &UnmarshalTypeError{Value: value, Type: reflect.PtrTo(t)}
  1174  }