...

Source file src/gopkg.in/square/go-jose.v2/json/decode.go

Documentation: gopkg.in/square/go-jose.v2/json

     1  // Copyright 2010 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Represents JSON data structure using native Go types: booleans, floats,
     6  // strings, arrays, and maps.
     7  
     8  package json
     9  
    10  import (
    11  	"bytes"
    12  	"encoding"
    13  	"encoding/base64"
    14  	"errors"
    15  	"fmt"
    16  	"math"
    17  	"reflect"
    18  	"runtime"
    19  	"strconv"
    20  	"unicode"
    21  	"unicode/utf16"
    22  	"unicode/utf8"
    23  )
    24  
    25  // Unmarshal parses the JSON-encoded data and stores the result
    26  // in the value pointed to by v.
    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 struct, Unmarshal matches incoming object
    39  // keys to the keys used by Marshal (either the struct field name or its tag),
    40  // preferring an exact match but also accepting a case-insensitive match.
    41  // Unmarshal will only set exported fields of the struct.
    42  //
    43  // To unmarshal JSON into an interface value,
    44  // Unmarshal stores one of these in the interface value:
    45  //
    46  //	bool, for JSON booleans
    47  //	float64, for JSON numbers
    48  //	string, for JSON strings
    49  //	[]interface{}, for JSON arrays
    50  //	map[string]interface{}, for JSON objects
    51  //	nil for JSON null
    52  //
    53  // To unmarshal a JSON array into a slice, Unmarshal resets the slice length
    54  // to zero and then appends each element to the slice.
    55  // As a special case, to unmarshal an empty JSON array into a slice,
    56  // Unmarshal replaces the slice with a new empty slice.
    57  //
    58  // To unmarshal a JSON array into a Go array, Unmarshal decodes
    59  // JSON array elements into corresponding Go array elements.
    60  // If the Go array is smaller than the JSON array,
    61  // the additional JSON array elements are discarded.
    62  // If the JSON array is smaller than the Go array,
    63  // the additional Go array elements are set to zero values.
    64  //
    65  // To unmarshal a JSON object into a string-keyed map, Unmarshal first
    66  // establishes a map to use, If the map is nil, Unmarshal allocates a new map.
    67  // Otherwise Unmarshal reuses the existing map, keeping existing entries.
    68  // Unmarshal then stores key-value pairs from the JSON object into the map.
    69  //
    70  // If a JSON value is not appropriate for a given target type,
    71  // or if a JSON number overflows the target type, Unmarshal
    72  // skips that field and completes the unmarshaling as best it can.
    73  // If no more serious errors are encountered, Unmarshal returns
    74  // an UnmarshalTypeError describing the earliest such error.
    75  //
    76  // The JSON null value unmarshals into an interface, map, pointer, or slice
    77  // by setting that Go value to nil. Because null is often used in JSON to mean
    78  // ``not present,'' unmarshaling a JSON null into any other Go type has no effect
    79  // on the value and produces no error.
    80  //
    81  // When unmarshaling quoted strings, invalid UTF-8 or
    82  // invalid UTF-16 surrogate pairs are not treated as an error.
    83  // Instead, they are replaced by the Unicode replacement
    84  // character U+FFFD.
    85  //
    86  func Unmarshal(data []byte, v interface{}) error {
    87  	// Check for well-formedness.
    88  	// Avoids filling out half a data structure
    89  	// before discovering a JSON syntax error.
    90  	var d decodeState
    91  	err := checkValid(data, &d.scan)
    92  	if err != nil {
    93  		return err
    94  	}
    95  
    96  	d.init(data)
    97  	return d.unmarshal(v)
    98  }
    99  
   100  // Unmarshaler is the interface implemented by objects
   101  // that can unmarshal a JSON description of themselves.
   102  // The input can be assumed to be a valid encoding of
   103  // a JSON value. UnmarshalJSON must copy the JSON data
   104  // if it wishes to retain the data after returning.
   105  type Unmarshaler interface {
   106  	UnmarshalJSON([]byte) error
   107  }
   108  
   109  // An UnmarshalTypeError describes a JSON value that was
   110  // not appropriate for a value of a specific Go type.
   111  type UnmarshalTypeError struct {
   112  	Value  string       // description of JSON value - "bool", "array", "number -5"
   113  	Type   reflect.Type // type of Go value it could not be assigned to
   114  	Offset int64        // error occurred after reading Offset bytes
   115  }
   116  
   117  func (e *UnmarshalTypeError) Error() string {
   118  	return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
   119  }
   120  
   121  // An UnmarshalFieldError describes a JSON object key that
   122  // led to an unexported (and therefore unwritable) struct field.
   123  // (No longer used; kept for compatibility.)
   124  type UnmarshalFieldError struct {
   125  	Key   string
   126  	Type  reflect.Type
   127  	Field reflect.StructField
   128  }
   129  
   130  func (e *UnmarshalFieldError) Error() string {
   131  	return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
   132  }
   133  
   134  // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
   135  // (The argument to Unmarshal must be a non-nil pointer.)
   136  type InvalidUnmarshalError struct {
   137  	Type reflect.Type
   138  }
   139  
   140  func (e *InvalidUnmarshalError) Error() string {
   141  	if e.Type == nil {
   142  		return "json: Unmarshal(nil)"
   143  	}
   144  
   145  	if e.Type.Kind() != reflect.Ptr {
   146  		return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
   147  	}
   148  	return "json: Unmarshal(nil " + e.Type.String() + ")"
   149  }
   150  
   151  func (d *decodeState) unmarshal(v interface{}) (err error) {
   152  	defer func() {
   153  		if r := recover(); r != nil {
   154  			if _, ok := r.(runtime.Error); ok {
   155  				panic(r)
   156  			}
   157  			err = r.(error)
   158  		}
   159  	}()
   160  
   161  	rv := reflect.ValueOf(v)
   162  	if rv.Kind() != reflect.Ptr || rv.IsNil() {
   163  		return &InvalidUnmarshalError{reflect.TypeOf(v)}
   164  	}
   165  
   166  	d.scan.reset()
   167  	// We decode rv not rv.Elem because the Unmarshaler interface
   168  	// test must be applied at the top level of the value.
   169  	d.value(rv)
   170  	return d.savedError
   171  }
   172  
   173  // A Number represents a JSON number literal.
   174  type Number string
   175  
   176  // String returns the literal text of the number.
   177  func (n Number) String() string { return string(n) }
   178  
   179  // Float64 returns the number as a float64.
   180  func (n Number) Float64() (float64, error) {
   181  	return strconv.ParseFloat(string(n), 64)
   182  }
   183  
   184  // Int64 returns the number as an int64.
   185  func (n Number) Int64() (int64, error) {
   186  	return strconv.ParseInt(string(n), 10, 64)
   187  }
   188  
   189  // isValidNumber reports whether s is a valid JSON number literal.
   190  func isValidNumber(s string) bool {
   191  	// This function implements the JSON numbers grammar.
   192  	// See https://tools.ietf.org/html/rfc7159#section-6
   193  	// and http://json.org/number.gif
   194  
   195  	if s == "" {
   196  		return false
   197  	}
   198  
   199  	// Optional -
   200  	if s[0] == '-' {
   201  		s = s[1:]
   202  		if s == "" {
   203  			return false
   204  		}
   205  	}
   206  
   207  	// Digits
   208  	switch {
   209  	default:
   210  		return false
   211  
   212  	case s[0] == '0':
   213  		s = s[1:]
   214  
   215  	case '1' <= s[0] && s[0] <= '9':
   216  		s = s[1:]
   217  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   218  			s = s[1:]
   219  		}
   220  	}
   221  
   222  	// . followed by 1 or more digits.
   223  	if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' {
   224  		s = s[2:]
   225  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   226  			s = s[1:]
   227  		}
   228  	}
   229  
   230  	// e or E followed by an optional - or + and
   231  	// 1 or more digits.
   232  	if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') {
   233  		s = s[1:]
   234  		if s[0] == '+' || s[0] == '-' {
   235  			s = s[1:]
   236  			if s == "" {
   237  				return false
   238  			}
   239  		}
   240  		for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
   241  			s = s[1:]
   242  		}
   243  	}
   244  
   245  	// Make sure we are at the end.
   246  	return s == ""
   247  }
   248  
   249  type NumberUnmarshalType int
   250  
   251  const (
   252  	// unmarshal a JSON number into an interface{} as a float64
   253  	UnmarshalFloat NumberUnmarshalType = iota
   254  	// unmarshal a JSON number into an interface{} as a `json.Number`
   255  	UnmarshalJSONNumber
   256  	// unmarshal a JSON number into an interface{} as a int64
   257  	// if value is an integer otherwise float64
   258  	UnmarshalIntOrFloat
   259  )
   260  
   261  // decodeState represents the state while decoding a JSON value.
   262  type decodeState struct {
   263  	data       []byte
   264  	off        int // read offset in data
   265  	scan       scanner
   266  	nextscan   scanner // for calls to nextValue
   267  	savedError error
   268  	numberType NumberUnmarshalType
   269  }
   270  
   271  // errPhase is used for errors that should not happen unless
   272  // there is a bug in the JSON decoder or something is editing
   273  // the data slice while the decoder executes.
   274  var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?")
   275  
   276  func (d *decodeState) init(data []byte) *decodeState {
   277  	d.data = data
   278  	d.off = 0
   279  	d.savedError = nil
   280  	return d
   281  }
   282  
   283  // error aborts the decoding by panicking with err.
   284  func (d *decodeState) error(err error) {
   285  	panic(err)
   286  }
   287  
   288  // saveError saves the first err it is called with,
   289  // for reporting at the end of the unmarshal.
   290  func (d *decodeState) saveError(err error) {
   291  	if d.savedError == nil {
   292  		d.savedError = err
   293  	}
   294  }
   295  
   296  // next cuts off and returns the next full JSON value in d.data[d.off:].
   297  // The next value is known to be an object or array, not a literal.
   298  func (d *decodeState) next() []byte {
   299  	c := d.data[d.off]
   300  	item, rest, err := nextValue(d.data[d.off:], &d.nextscan)
   301  	if err != nil {
   302  		d.error(err)
   303  	}
   304  	d.off = len(d.data) - len(rest)
   305  
   306  	// Our scanner has seen the opening brace/bracket
   307  	// and thinks we're still in the middle of the object.
   308  	// invent a closing brace/bracket to get it out.
   309  	if c == '{' {
   310  		d.scan.step(&d.scan, '}')
   311  	} else {
   312  		d.scan.step(&d.scan, ']')
   313  	}
   314  
   315  	return item
   316  }
   317  
   318  // scanWhile processes bytes in d.data[d.off:] until it
   319  // receives a scan code not equal to op.
   320  // It updates d.off and returns the new scan code.
   321  func (d *decodeState) scanWhile(op int) int {
   322  	var newOp int
   323  	for {
   324  		if d.off >= len(d.data) {
   325  			newOp = d.scan.eof()
   326  			d.off = len(d.data) + 1 // mark processed EOF with len+1
   327  		} else {
   328  			c := d.data[d.off]
   329  			d.off++
   330  			newOp = d.scan.step(&d.scan, c)
   331  		}
   332  		if newOp != op {
   333  			break
   334  		}
   335  	}
   336  	return newOp
   337  }
   338  
   339  // value decodes a JSON value from d.data[d.off:] into the value.
   340  // it updates d.off to point past the decoded value.
   341  func (d *decodeState) value(v reflect.Value) {
   342  	if !v.IsValid() {
   343  		_, rest, err := nextValue(d.data[d.off:], &d.nextscan)
   344  		if err != nil {
   345  			d.error(err)
   346  		}
   347  		d.off = len(d.data) - len(rest)
   348  
   349  		// d.scan thinks we're still at the beginning of the item.
   350  		// Feed in an empty string - the shortest, simplest value -
   351  		// so that it knows we got to the end of the value.
   352  		if d.scan.redo {
   353  			// rewind.
   354  			d.scan.redo = false
   355  			d.scan.step = stateBeginValue
   356  		}
   357  		d.scan.step(&d.scan, '"')
   358  		d.scan.step(&d.scan, '"')
   359  
   360  		n := len(d.scan.parseState)
   361  		if n > 0 && d.scan.parseState[n-1] == parseObjectKey {
   362  			// d.scan thinks we just read an object key; finish the object
   363  			d.scan.step(&d.scan, ':')
   364  			d.scan.step(&d.scan, '"')
   365  			d.scan.step(&d.scan, '"')
   366  			d.scan.step(&d.scan, '}')
   367  		}
   368  
   369  		return
   370  	}
   371  
   372  	switch op := d.scanWhile(scanSkipSpace); op {
   373  	default:
   374  		d.error(errPhase)
   375  
   376  	case scanBeginArray:
   377  		d.array(v)
   378  
   379  	case scanBeginObject:
   380  		d.object(v)
   381  
   382  	case scanBeginLiteral:
   383  		d.literal(v)
   384  	}
   385  }
   386  
   387  type unquotedValue struct{}
   388  
   389  // valueQuoted is like value but decodes a
   390  // quoted string literal or literal null into an interface value.
   391  // If it finds anything other than a quoted string literal or null,
   392  // valueQuoted returns unquotedValue{}.
   393  func (d *decodeState) valueQuoted() interface{} {
   394  	switch op := d.scanWhile(scanSkipSpace); op {
   395  	default:
   396  		d.error(errPhase)
   397  
   398  	case scanBeginArray:
   399  		d.array(reflect.Value{})
   400  
   401  	case scanBeginObject:
   402  		d.object(reflect.Value{})
   403  
   404  	case scanBeginLiteral:
   405  		switch v := d.literalInterface().(type) {
   406  		case nil, string:
   407  			return v
   408  		}
   409  	}
   410  	return unquotedValue{}
   411  }
   412  
   413  // indirect walks down v allocating pointers as needed,
   414  // until it gets to a non-pointer.
   415  // if it encounters an Unmarshaler, indirect stops and returns that.
   416  // if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
   417  func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
   418  	// If v is a named type and is addressable,
   419  	// start with its address, so that if the type has pointer methods,
   420  	// we find them.
   421  	if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
   422  		v = v.Addr()
   423  	}
   424  	for {
   425  		// Load value from interface, but only if the result will be
   426  		// usefully addressable.
   427  		if v.Kind() == reflect.Interface && !v.IsNil() {
   428  			e := v.Elem()
   429  			if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
   430  				v = e
   431  				continue
   432  			}
   433  		}
   434  
   435  		if v.Kind() != reflect.Ptr {
   436  			break
   437  		}
   438  
   439  		if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
   440  			break
   441  		}
   442  		if v.IsNil() {
   443  			v.Set(reflect.New(v.Type().Elem()))
   444  		}
   445  		if v.Type().NumMethod() > 0 {
   446  			if u, ok := v.Interface().(Unmarshaler); ok {
   447  				return u, nil, reflect.Value{}
   448  			}
   449  			if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
   450  				return nil, u, reflect.Value{}
   451  			}
   452  		}
   453  		v = v.Elem()
   454  	}
   455  	return nil, nil, v
   456  }
   457  
   458  // array consumes an array from d.data[d.off-1:], decoding into the value v.
   459  // the first byte of the array ('[') has been read already.
   460  func (d *decodeState) array(v reflect.Value) {
   461  	// Check for unmarshaler.
   462  	u, ut, pv := d.indirect(v, false)
   463  	if u != nil {
   464  		d.off--
   465  		err := u.UnmarshalJSON(d.next())
   466  		if err != nil {
   467  			d.error(err)
   468  		}
   469  		return
   470  	}
   471  	if ut != nil {
   472  		d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)})
   473  		d.off--
   474  		d.next()
   475  		return
   476  	}
   477  
   478  	v = pv
   479  
   480  	// Check type of target.
   481  	switch v.Kind() {
   482  	case reflect.Interface:
   483  		if v.NumMethod() == 0 {
   484  			// Decoding into nil interface?  Switch to non-reflect code.
   485  			v.Set(reflect.ValueOf(d.arrayInterface()))
   486  			return
   487  		}
   488  		// Otherwise it's invalid.
   489  		fallthrough
   490  	default:
   491  		d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)})
   492  		d.off--
   493  		d.next()
   494  		return
   495  	case reflect.Array:
   496  	case reflect.Slice:
   497  		break
   498  	}
   499  
   500  	i := 0
   501  	for {
   502  		// Look ahead for ] - can only happen on first iteration.
   503  		op := d.scanWhile(scanSkipSpace)
   504  		if op == scanEndArray {
   505  			break
   506  		}
   507  
   508  		// Back up so d.value can have the byte we just read.
   509  		d.off--
   510  		d.scan.undo(op)
   511  
   512  		// Get element of array, growing if necessary.
   513  		if v.Kind() == reflect.Slice {
   514  			// Grow slice if necessary
   515  			if i >= v.Cap() {
   516  				newcap := v.Cap() + v.Cap()/2
   517  				if newcap < 4 {
   518  					newcap = 4
   519  				}
   520  				newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
   521  				reflect.Copy(newv, v)
   522  				v.Set(newv)
   523  			}
   524  			if i >= v.Len() {
   525  				v.SetLen(i + 1)
   526  			}
   527  		}
   528  
   529  		if i < v.Len() {
   530  			// Decode into element.
   531  			d.value(v.Index(i))
   532  		} else {
   533  			// Ran out of fixed array: skip.
   534  			d.value(reflect.Value{})
   535  		}
   536  		i++
   537  
   538  		// Next token must be , or ].
   539  		op = d.scanWhile(scanSkipSpace)
   540  		if op == scanEndArray {
   541  			break
   542  		}
   543  		if op != scanArrayValue {
   544  			d.error(errPhase)
   545  		}
   546  	}
   547  
   548  	if i < v.Len() {
   549  		if v.Kind() == reflect.Array {
   550  			// Array.  Zero the rest.
   551  			z := reflect.Zero(v.Type().Elem())
   552  			for ; i < v.Len(); i++ {
   553  				v.Index(i).Set(z)
   554  			}
   555  		} else {
   556  			v.SetLen(i)
   557  		}
   558  	}
   559  	if i == 0 && v.Kind() == reflect.Slice {
   560  		v.Set(reflect.MakeSlice(v.Type(), 0, 0))
   561  	}
   562  }
   563  
   564  var nullLiteral = []byte("null")
   565  
   566  // object consumes an object from d.data[d.off-1:], decoding into the value v.
   567  // the first byte ('{') of the object has been read already.
   568  func (d *decodeState) object(v reflect.Value) {
   569  	// Check for unmarshaler.
   570  	u, ut, pv := d.indirect(v, false)
   571  	if u != nil {
   572  		d.off--
   573  		err := u.UnmarshalJSON(d.next())
   574  		if err != nil {
   575  			d.error(err)
   576  		}
   577  		return
   578  	}
   579  	if ut != nil {
   580  		d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
   581  		d.off--
   582  		d.next() // skip over { } in input
   583  		return
   584  	}
   585  	v = pv
   586  
   587  	// Decoding into nil interface?  Switch to non-reflect code.
   588  	if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
   589  		v.Set(reflect.ValueOf(d.objectInterface()))
   590  		return
   591  	}
   592  
   593  	// Check type of target: struct or map[string]T
   594  	switch v.Kind() {
   595  	case reflect.Map:
   596  		// map must have string kind
   597  		t := v.Type()
   598  		if t.Key().Kind() != reflect.String {
   599  			d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
   600  			d.off--
   601  			d.next() // skip over { } in input
   602  			return
   603  		}
   604  		if v.IsNil() {
   605  			v.Set(reflect.MakeMap(t))
   606  		}
   607  	case reflect.Struct:
   608  
   609  	default:
   610  		d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
   611  		d.off--
   612  		d.next() // skip over { } in input
   613  		return
   614  	}
   615  
   616  	var mapElem reflect.Value
   617  	keys := map[string]bool{}
   618  
   619  	for {
   620  		// Read opening " of string key or closing }.
   621  		op := d.scanWhile(scanSkipSpace)
   622  		if op == scanEndObject {
   623  			// closing } - can only happen on first iteration.
   624  			break
   625  		}
   626  		if op != scanBeginLiteral {
   627  			d.error(errPhase)
   628  		}
   629  
   630  		// Read key.
   631  		start := d.off - 1
   632  		op = d.scanWhile(scanContinue)
   633  		item := d.data[start : d.off-1]
   634  		key, ok := unquote(item)
   635  		if !ok {
   636  			d.error(errPhase)
   637  		}
   638  
   639  		// Check for duplicate keys.
   640  		_, ok = keys[key]
   641  		if !ok {
   642  			keys[key] = true
   643  		} else {
   644  			d.error(fmt.Errorf("json: duplicate key '%s' in object", key))
   645  		}
   646  
   647  		// Figure out field corresponding to key.
   648  		var subv reflect.Value
   649  		destring := false // whether the value is wrapped in a string to be decoded first
   650  
   651  		if v.Kind() == reflect.Map {
   652  			elemType := v.Type().Elem()
   653  			if !mapElem.IsValid() {
   654  				mapElem = reflect.New(elemType).Elem()
   655  			} else {
   656  				mapElem.Set(reflect.Zero(elemType))
   657  			}
   658  			subv = mapElem
   659  		} else {
   660  			var f *field
   661  			fields := cachedTypeFields(v.Type())
   662  			for i := range fields {
   663  				ff := &fields[i]
   664  				if bytes.Equal(ff.nameBytes, []byte(key)) {
   665  					f = ff
   666  					break
   667  				}
   668  			}
   669  			if f != nil {
   670  				subv = v
   671  				destring = f.quoted
   672  				for _, i := range f.index {
   673  					if subv.Kind() == reflect.Ptr {
   674  						if subv.IsNil() {
   675  							subv.Set(reflect.New(subv.Type().Elem()))
   676  						}
   677  						subv = subv.Elem()
   678  					}
   679  					subv = subv.Field(i)
   680  				}
   681  			}
   682  		}
   683  
   684  		// Read : before value.
   685  		if op == scanSkipSpace {
   686  			op = d.scanWhile(scanSkipSpace)
   687  		}
   688  		if op != scanObjectKey {
   689  			d.error(errPhase)
   690  		}
   691  
   692  		// Read value.
   693  		if destring {
   694  			switch qv := d.valueQuoted().(type) {
   695  			case nil:
   696  				d.literalStore(nullLiteral, subv, false)
   697  			case string:
   698  				d.literalStore([]byte(qv), subv, true)
   699  			default:
   700  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
   701  			}
   702  		} else {
   703  			d.value(subv)
   704  		}
   705  
   706  		// Write value back to map;
   707  		// if using struct, subv points into struct already.
   708  		if v.Kind() == reflect.Map {
   709  			kv := reflect.ValueOf(key).Convert(v.Type().Key())
   710  			v.SetMapIndex(kv, subv)
   711  		}
   712  
   713  		// Next token must be , or }.
   714  		op = d.scanWhile(scanSkipSpace)
   715  		if op == scanEndObject {
   716  			break
   717  		}
   718  		if op != scanObjectValue {
   719  			d.error(errPhase)
   720  		}
   721  	}
   722  }
   723  
   724  // literal consumes a literal from d.data[d.off-1:], decoding into the value v.
   725  // The first byte of the literal has been read already
   726  // (that's how the caller knows it's a literal).
   727  func (d *decodeState) literal(v reflect.Value) {
   728  	// All bytes inside literal return scanContinue op code.
   729  	start := d.off - 1
   730  	op := d.scanWhile(scanContinue)
   731  
   732  	// Scan read one byte too far; back up.
   733  	d.off--
   734  	d.scan.undo(op)
   735  
   736  	d.literalStore(d.data[start:d.off], v, false)
   737  }
   738  
   739  // convertNumber converts the number literal s to a float64, int64 or a Number
   740  // depending on d.numberDecodeType.
   741  func (d *decodeState) convertNumber(s string) (interface{}, error) {
   742  	switch d.numberType {
   743  
   744  	case UnmarshalJSONNumber:
   745  		return Number(s), nil
   746  	case UnmarshalIntOrFloat:
   747  		v, err := strconv.ParseInt(s, 10, 64)
   748  		if err == nil {
   749  			return v, nil
   750  		}
   751  
   752  		// tries to parse integer number in scientific notation
   753  		f, err := strconv.ParseFloat(s, 64)
   754  		if err != nil {
   755  			return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.off)}
   756  		}
   757  
   758  		// if it has no decimal value use int64
   759  		if fi, fd := math.Modf(f); fd == 0.0 {
   760  			return int64(fi), nil
   761  		}
   762  		return f, nil
   763  	default:
   764  		f, err := strconv.ParseFloat(s, 64)
   765  		if err != nil {
   766  			return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.off)}
   767  		}
   768  		return f, nil
   769  	}
   770  
   771  }
   772  
   773  var numberType = reflect.TypeOf(Number(""))
   774  
   775  // literalStore decodes a literal stored in item into v.
   776  //
   777  // fromQuoted indicates whether this literal came from unwrapping a
   778  // string from the ",string" struct tag option. this is used only to
   779  // produce more helpful error messages.
   780  func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) {
   781  	// Check for unmarshaler.
   782  	if len(item) == 0 {
   783  		//Empty string given
   784  		d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   785  		return
   786  	}
   787  	wantptr := item[0] == 'n' // null
   788  	u, ut, pv := d.indirect(v, wantptr)
   789  	if u != nil {
   790  		err := u.UnmarshalJSON(item)
   791  		if err != nil {
   792  			d.error(err)
   793  		}
   794  		return
   795  	}
   796  	if ut != nil {
   797  		if item[0] != '"' {
   798  			if fromQuoted {
   799  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   800  			} else {
   801  				d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
   802  			}
   803  			return
   804  		}
   805  		s, ok := unquoteBytes(item)
   806  		if !ok {
   807  			if fromQuoted {
   808  				d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   809  			} else {
   810  				d.error(errPhase)
   811  			}
   812  		}
   813  		err := ut.UnmarshalText(s)
   814  		if err != nil {
   815  			d.error(err)
   816  		}
   817  		return
   818  	}
   819  
   820  	v = pv
   821  
   822  	switch c := item[0]; c {
   823  	case 'n': // null
   824  		switch v.Kind() {
   825  		case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice:
   826  			v.Set(reflect.Zero(v.Type()))
   827  			// otherwise, ignore null for primitives/string
   828  		}
   829  	case 't', 'f': // true, false
   830  		value := c == 't'
   831  		switch v.Kind() {
   832  		default:
   833  			if fromQuoted {
   834  				d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   835  			} else {
   836  				d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)})
   837  			}
   838  		case reflect.Bool:
   839  			v.SetBool(value)
   840  		case reflect.Interface:
   841  			if v.NumMethod() == 0 {
   842  				v.Set(reflect.ValueOf(value))
   843  			} else {
   844  				d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)})
   845  			}
   846  		}
   847  
   848  	case '"': // string
   849  		s, ok := unquoteBytes(item)
   850  		if !ok {
   851  			if fromQuoted {
   852  				d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   853  			} else {
   854  				d.error(errPhase)
   855  			}
   856  		}
   857  		switch v.Kind() {
   858  		default:
   859  			d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
   860  		case reflect.Slice:
   861  			if v.Type().Elem().Kind() != reflect.Uint8 {
   862  				d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
   863  				break
   864  			}
   865  			b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
   866  			n, err := base64.StdEncoding.Decode(b, s)
   867  			if err != nil {
   868  				d.saveError(err)
   869  				break
   870  			}
   871  			v.SetBytes(b[:n])
   872  		case reflect.String:
   873  			v.SetString(string(s))
   874  		case reflect.Interface:
   875  			if v.NumMethod() == 0 {
   876  				v.Set(reflect.ValueOf(string(s)))
   877  			} else {
   878  				d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
   879  			}
   880  		}
   881  
   882  	default: // number
   883  		if c != '-' && (c < '0' || c > '9') {
   884  			if fromQuoted {
   885  				d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   886  			} else {
   887  				d.error(errPhase)
   888  			}
   889  		}
   890  		s := string(item)
   891  		switch v.Kind() {
   892  		default:
   893  			if v.Kind() == reflect.String && v.Type() == numberType {
   894  				v.SetString(s)
   895  				if !isValidNumber(s) {
   896  					d.error(fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item))
   897  				}
   898  				break
   899  			}
   900  			if fromQuoted {
   901  				d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
   902  			} else {
   903  				d.error(&UnmarshalTypeError{"number", v.Type(), int64(d.off)})
   904  			}
   905  		case reflect.Interface:
   906  			n, err := d.convertNumber(s)
   907  			if err != nil {
   908  				d.saveError(err)
   909  				break
   910  			}
   911  			if v.NumMethod() != 0 {
   912  				d.saveError(&UnmarshalTypeError{"number", v.Type(), int64(d.off)})
   913  				break
   914  			}
   915  			v.Set(reflect.ValueOf(n))
   916  
   917  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   918  			n, err := strconv.ParseInt(s, 10, 64)
   919  			if err != nil || v.OverflowInt(n) {
   920  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)})
   921  				break
   922  			}
   923  			v.SetInt(n)
   924  
   925  		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   926  			n, err := strconv.ParseUint(s, 10, 64)
   927  			if err != nil || v.OverflowUint(n) {
   928  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)})
   929  				break
   930  			}
   931  			v.SetUint(n)
   932  
   933  		case reflect.Float32, reflect.Float64:
   934  			n, err := strconv.ParseFloat(s, v.Type().Bits())
   935  			if err != nil || v.OverflowFloat(n) {
   936  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)})
   937  				break
   938  			}
   939  			v.SetFloat(n)
   940  		}
   941  	}
   942  }
   943  
   944  // The xxxInterface routines build up a value to be stored
   945  // in an empty interface.  They are not strictly necessary,
   946  // but they avoid the weight of reflection in this common case.
   947  
   948  // valueInterface is like value but returns interface{}
   949  func (d *decodeState) valueInterface() interface{} {
   950  	switch d.scanWhile(scanSkipSpace) {
   951  	default:
   952  		d.error(errPhase)
   953  		panic("unreachable")
   954  	case scanBeginArray:
   955  		return d.arrayInterface()
   956  	case scanBeginObject:
   957  		return d.objectInterface()
   958  	case scanBeginLiteral:
   959  		return d.literalInterface()
   960  	}
   961  }
   962  
   963  // arrayInterface is like array but returns []interface{}.
   964  func (d *decodeState) arrayInterface() []interface{} {
   965  	var v = make([]interface{}, 0)
   966  	for {
   967  		// Look ahead for ] - can only happen on first iteration.
   968  		op := d.scanWhile(scanSkipSpace)
   969  		if op == scanEndArray {
   970  			break
   971  		}
   972  
   973  		// Back up so d.value can have the byte we just read.
   974  		d.off--
   975  		d.scan.undo(op)
   976  
   977  		v = append(v, d.valueInterface())
   978  
   979  		// Next token must be , or ].
   980  		op = d.scanWhile(scanSkipSpace)
   981  		if op == scanEndArray {
   982  			break
   983  		}
   984  		if op != scanArrayValue {
   985  			d.error(errPhase)
   986  		}
   987  	}
   988  	return v
   989  }
   990  
   991  // objectInterface is like object but returns map[string]interface{}.
   992  func (d *decodeState) objectInterface() map[string]interface{} {
   993  	m := make(map[string]interface{})
   994  	keys := map[string]bool{}
   995  
   996  	for {
   997  		// Read opening " of string key or closing }.
   998  		op := d.scanWhile(scanSkipSpace)
   999  		if op == scanEndObject {
  1000  			// closing } - can only happen on first iteration.
  1001  			break
  1002  		}
  1003  		if op != scanBeginLiteral {
  1004  			d.error(errPhase)
  1005  		}
  1006  
  1007  		// Read string key.
  1008  		start := d.off - 1
  1009  		op = d.scanWhile(scanContinue)
  1010  		item := d.data[start : d.off-1]
  1011  		key, ok := unquote(item)
  1012  		if !ok {
  1013  			d.error(errPhase)
  1014  		}
  1015  
  1016  		// Check for duplicate keys.
  1017  		_, ok = keys[key]
  1018  		if !ok {
  1019  			keys[key] = true
  1020  		} else {
  1021  			d.error(fmt.Errorf("json: duplicate key '%s' in object", key))
  1022  		}
  1023  
  1024  		// Read : before value.
  1025  		if op == scanSkipSpace {
  1026  			op = d.scanWhile(scanSkipSpace)
  1027  		}
  1028  		if op != scanObjectKey {
  1029  			d.error(errPhase)
  1030  		}
  1031  
  1032  		// Read value.
  1033  		m[key] = d.valueInterface()
  1034  
  1035  		// Next token must be , or }.
  1036  		op = d.scanWhile(scanSkipSpace)
  1037  		if op == scanEndObject {
  1038  			break
  1039  		}
  1040  		if op != scanObjectValue {
  1041  			d.error(errPhase)
  1042  		}
  1043  	}
  1044  	return m
  1045  }
  1046  
  1047  // literalInterface is like literal but returns an interface value.
  1048  func (d *decodeState) literalInterface() interface{} {
  1049  	// All bytes inside literal return scanContinue op code.
  1050  	start := d.off - 1
  1051  	op := d.scanWhile(scanContinue)
  1052  
  1053  	// Scan read one byte too far; back up.
  1054  	d.off--
  1055  	d.scan.undo(op)
  1056  	item := d.data[start:d.off]
  1057  
  1058  	switch c := item[0]; c {
  1059  	case 'n': // null
  1060  		return nil
  1061  
  1062  	case 't', 'f': // true, false
  1063  		return c == 't'
  1064  
  1065  	case '"': // string
  1066  		s, ok := unquote(item)
  1067  		if !ok {
  1068  			d.error(errPhase)
  1069  		}
  1070  		return s
  1071  
  1072  	default: // number
  1073  		if c != '-' && (c < '0' || c > '9') {
  1074  			d.error(errPhase)
  1075  		}
  1076  		n, err := d.convertNumber(string(item))
  1077  		if err != nil {
  1078  			d.saveError(err)
  1079  		}
  1080  		return n
  1081  	}
  1082  }
  1083  
  1084  // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
  1085  // or it returns -1.
  1086  func getu4(s []byte) rune {
  1087  	if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
  1088  		return -1
  1089  	}
  1090  	r, err := strconv.ParseUint(string(s[2:6]), 16, 64)
  1091  	if err != nil {
  1092  		return -1
  1093  	}
  1094  	return rune(r)
  1095  }
  1096  
  1097  // unquote converts a quoted JSON string literal s into an actual string t.
  1098  // The rules are different than for Go, so cannot use strconv.Unquote.
  1099  func unquote(s []byte) (t string, ok bool) {
  1100  	s, ok = unquoteBytes(s)
  1101  	t = string(s)
  1102  	return
  1103  }
  1104  
  1105  func unquoteBytes(s []byte) (t []byte, ok bool) {
  1106  	if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
  1107  		return
  1108  	}
  1109  	s = s[1 : len(s)-1]
  1110  
  1111  	// Check for unusual characters. If there are none,
  1112  	// then no unquoting is needed, so return a slice of the
  1113  	// original bytes.
  1114  	r := 0
  1115  	for r < len(s) {
  1116  		c := s[r]
  1117  		if c == '\\' || c == '"' || c < ' ' {
  1118  			break
  1119  		}
  1120  		if c < utf8.RuneSelf {
  1121  			r++
  1122  			continue
  1123  		}
  1124  		rr, size := utf8.DecodeRune(s[r:])
  1125  		if rr == utf8.RuneError && size == 1 {
  1126  			break
  1127  		}
  1128  		r += size
  1129  	}
  1130  	if r == len(s) {
  1131  		return s, true
  1132  	}
  1133  
  1134  	b := make([]byte, len(s)+2*utf8.UTFMax)
  1135  	w := copy(b, s[0:r])
  1136  	for r < len(s) {
  1137  		// Out of room?  Can only happen if s is full of
  1138  		// malformed UTF-8 and we're replacing each
  1139  		// byte with RuneError.
  1140  		if w >= len(b)-2*utf8.UTFMax {
  1141  			nb := make([]byte, (len(b)+utf8.UTFMax)*2)
  1142  			copy(nb, b[0:w])
  1143  			b = nb
  1144  		}
  1145  		switch c := s[r]; {
  1146  		case c == '\\':
  1147  			r++
  1148  			if r >= len(s) {
  1149  				return
  1150  			}
  1151  			switch s[r] {
  1152  			default:
  1153  				return
  1154  			case '"', '\\', '/', '\'':
  1155  				b[w] = s[r]
  1156  				r++
  1157  				w++
  1158  			case 'b':
  1159  				b[w] = '\b'
  1160  				r++
  1161  				w++
  1162  			case 'f':
  1163  				b[w] = '\f'
  1164  				r++
  1165  				w++
  1166  			case 'n':
  1167  				b[w] = '\n'
  1168  				r++
  1169  				w++
  1170  			case 'r':
  1171  				b[w] = '\r'
  1172  				r++
  1173  				w++
  1174  			case 't':
  1175  				b[w] = '\t'
  1176  				r++
  1177  				w++
  1178  			case 'u':
  1179  				r--
  1180  				rr := getu4(s[r:])
  1181  				if rr < 0 {
  1182  					return
  1183  				}
  1184  				r += 6
  1185  				if utf16.IsSurrogate(rr) {
  1186  					rr1 := getu4(s[r:])
  1187  					if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
  1188  						// A valid pair; consume.
  1189  						r += 6
  1190  						w += utf8.EncodeRune(b[w:], dec)
  1191  						break
  1192  					}
  1193  					// Invalid surrogate; fall back to replacement rune.
  1194  					rr = unicode.ReplacementChar
  1195  				}
  1196  				w += utf8.EncodeRune(b[w:], rr)
  1197  			}
  1198  
  1199  		// Quote, control characters are invalid.
  1200  		case c == '"', c < ' ':
  1201  			return
  1202  
  1203  		// ASCII
  1204  		case c < utf8.RuneSelf:
  1205  			b[w] = c
  1206  			r++
  1207  			w++
  1208  
  1209  		// Coerce to well-formed UTF-8.
  1210  		default:
  1211  			rr, size := utf8.DecodeRune(s[r:])
  1212  			r += size
  1213  			w += utf8.EncodeRune(b[w:], rr)
  1214  		}
  1215  	}
  1216  	return b[0:w], true
  1217  }
  1218  

View as plain text