github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/cmd/fix/testdata/reflect.decode.go.out (about)

     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  	"container/vector"
    12  	"encoding/base64"
    13  	"os"
    14  	"reflect"
    15  	"runtime"
    16  	"strconv"
    17  	"strings"
    18  	"unicode"
    19  	"utf16"
    20  	"utf8"
    21  )
    22  
    23  // Unmarshal parses the JSON-encoded data and stores the result
    24  // in the value pointed to by v.
    25  //
    26  // Unmarshal traverses the value v recursively.
    27  // If an encountered value implements the Unmarshaler interface,
    28  // Unmarshal calls its UnmarshalJSON method with a well-formed
    29  // JSON encoding.
    30  //
    31  // Otherwise, Unmarshal uses the inverse of the encodings that
    32  // Marshal uses, allocating maps, slices, and pointers as necessary,
    33  // with the following additional rules:
    34  //
    35  // To unmarshal a JSON value into a nil interface value, the
    36  // type stored in the interface value is one of:
    37  //
    38  //	bool, for JSON booleans
    39  //	float64, for JSON numbers
    40  //	string, for JSON strings
    41  //	[]interface{}, for JSON arrays
    42  //	map[string]interface{}, for JSON objects
    43  //	nil for JSON null
    44  //
    45  // If a JSON value is not appropriate for a given target type,
    46  // or if a JSON number overflows the target type, Unmarshal
    47  // skips that field and completes the unmarshalling as best it can.
    48  // If no more serious errors are encountered, Unmarshal returns
    49  // an UnmarshalTypeError describing the earliest such error.
    50  //
    51  func Unmarshal(data []byte, v interface{}) os.Error {
    52  	d := new(decodeState).init(data)
    53  
    54  	// Quick check for well-formedness.
    55  	// Avoids filling out half a data structure
    56  	// before discovering a JSON syntax error.
    57  	err := checkValid(data, &d.scan)
    58  	if err != nil {
    59  		return err
    60  	}
    61  
    62  	return d.unmarshal(v)
    63  }
    64  
    65  // Unmarshaler is the interface implemented by objects
    66  // that can unmarshal a JSON description of themselves.
    67  // The input can be assumed to be a valid JSON object
    68  // encoding.  UnmarshalJSON must copy the JSON data
    69  // if it wishes to retain the data after returning.
    70  type Unmarshaler interface {
    71  	UnmarshalJSON([]byte) os.Error
    72  }
    73  
    74  // An UnmarshalTypeError describes a JSON value that was
    75  // not appropriate for a value of a specific Go type.
    76  type UnmarshalTypeError struct {
    77  	Value string       // description of JSON value - "bool", "array", "number -5"
    78  	Type  reflect.Type // type of Go value it could not be assigned to
    79  }
    80  
    81  func (e *UnmarshalTypeError) String() string {
    82  	return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
    83  }
    84  
    85  // An UnmarshalFieldError describes a JSON object key that
    86  // led to an unexported (and therefore unwritable) struct field.
    87  type UnmarshalFieldError struct {
    88  	Key   string
    89  	Type  reflect.Type
    90  	Field reflect.StructField
    91  }
    92  
    93  func (e *UnmarshalFieldError) String() string {
    94  	return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
    95  }
    96  
    97  // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
    98  // (The argument to Unmarshal must be a non-nil pointer.)
    99  type InvalidUnmarshalError struct {
   100  	Type reflect.Type
   101  }
   102  
   103  func (e *InvalidUnmarshalError) String() string {
   104  	if e.Type == nil {
   105  		return "json: Unmarshal(nil)"
   106  	}
   107  
   108  	if e.Type.Kind() != reflect.Ptr {
   109  		return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
   110  	}
   111  	return "json: Unmarshal(nil " + e.Type.String() + ")"
   112  }
   113  
   114  func (d *decodeState) unmarshal(v interface{}) (err os.Error) {
   115  	defer func() {
   116  		if r := recover(); r != nil {
   117  			if _, ok := r.(runtime.Error); ok {
   118  				panic(r)
   119  			}
   120  			err = r.(os.Error)
   121  		}
   122  	}()
   123  
   124  	rv := reflect.ValueOf(v)
   125  	pv := rv
   126  	if pv.Kind() != reflect.Ptr ||
   127  		pv.IsNil() {
   128  		return &InvalidUnmarshalError{reflect.TypeOf(v)}
   129  	}
   130  
   131  	d.scan.reset()
   132  	// We decode rv not pv.Elem because the Unmarshaler interface
   133  	// test must be applied at the top level of the value.
   134  	d.value(rv)
   135  	return d.savedError
   136  }
   137  
   138  // decodeState represents the state while decoding a JSON value.
   139  type decodeState struct {
   140  	data       []byte
   141  	off        int // read offset in data
   142  	scan       scanner
   143  	nextscan   scanner // for calls to nextValue
   144  	savedError os.Error
   145  }
   146  
   147  // errPhase is used for errors that should not happen unless
   148  // there is a bug in the JSON decoder or something is editing
   149  // the data slice while the decoder executes.
   150  var errPhase = os.NewError("JSON decoder out of sync - data changing underfoot?")
   151  
   152  func (d *decodeState) init(data []byte) *decodeState {
   153  	d.data = data
   154  	d.off = 0
   155  	d.savedError = nil
   156  	return d
   157  }
   158  
   159  // error aborts the decoding by panicking with err.
   160  func (d *decodeState) error(err os.Error) {
   161  	panic(err)
   162  }
   163  
   164  // saveError saves the first err it is called with,
   165  // for reporting at the end of the unmarshal.
   166  func (d *decodeState) saveError(err os.Error) {
   167  	if d.savedError == nil {
   168  		d.savedError = err
   169  	}
   170  }
   171  
   172  // next cuts off and returns the next full JSON value in d.data[d.off:].
   173  // The next value is known to be an object or array, not a literal.
   174  func (d *decodeState) next() []byte {
   175  	c := d.data[d.off]
   176  	item, rest, err := nextValue(d.data[d.off:], &d.nextscan)
   177  	if err != nil {
   178  		d.error(err)
   179  	}
   180  	d.off = len(d.data) - len(rest)
   181  
   182  	// Our scanner has seen the opening brace/bracket
   183  	// and thinks we're still in the middle of the object.
   184  	// invent a closing brace/bracket to get it out.
   185  	if c == '{' {
   186  		d.scan.step(&d.scan, '}')
   187  	} else {
   188  		d.scan.step(&d.scan, ']')
   189  	}
   190  
   191  	return item
   192  }
   193  
   194  // scanWhile processes bytes in d.data[d.off:] until it
   195  // receives a scan code not equal to op.
   196  // It updates d.off and returns the new scan code.
   197  func (d *decodeState) scanWhile(op int) int {
   198  	var newOp int
   199  	for {
   200  		if d.off >= len(d.data) {
   201  			newOp = d.scan.eof()
   202  			d.off = len(d.data) + 1 // mark processed EOF with len+1
   203  		} else {
   204  			c := int(d.data[d.off])
   205  			d.off++
   206  			newOp = d.scan.step(&d.scan, c)
   207  		}
   208  		if newOp != op {
   209  			break
   210  		}
   211  	}
   212  	return newOp
   213  }
   214  
   215  // value decodes a JSON value from d.data[d.off:] into the value.
   216  // it updates d.off to point past the decoded value.
   217  func (d *decodeState) value(v reflect.Value) {
   218  	if !v.IsValid() {
   219  		_, rest, err := nextValue(d.data[d.off:], &d.nextscan)
   220  		if err != nil {
   221  			d.error(err)
   222  		}
   223  		d.off = len(d.data) - len(rest)
   224  
   225  		// d.scan thinks we're still at the beginning of the item.
   226  		// Feed in an empty string - the shortest, simplest value -
   227  		// so that it knows we got to the end of the value.
   228  		if d.scan.step == stateRedo {
   229  			panic("redo")
   230  		}
   231  		d.scan.step(&d.scan, '"')
   232  		d.scan.step(&d.scan, '"')
   233  		return
   234  	}
   235  
   236  	switch op := d.scanWhile(scanSkipSpace); op {
   237  	default:
   238  		d.error(errPhase)
   239  
   240  	case scanBeginArray:
   241  		d.array(v)
   242  
   243  	case scanBeginObject:
   244  		d.object(v)
   245  
   246  	case scanBeginLiteral:
   247  		d.literal(v)
   248  	}
   249  }
   250  
   251  // indirect walks down v allocating pointers as needed,
   252  // until it gets to a non-pointer.
   253  // if it encounters an Unmarshaler, indirect stops and returns that.
   254  // if wantptr is true, indirect stops at the last pointer.
   255  func (d *decodeState) indirect(v reflect.Value, wantptr bool) (Unmarshaler, reflect.Value) {
   256  	for {
   257  		var isUnmarshaler bool
   258  		if v.Type().NumMethod() > 0 {
   259  			// Remember that this is an unmarshaler,
   260  			// but wait to return it until after allocating
   261  			// the pointer (if necessary).
   262  			_, isUnmarshaler = v.Interface().(Unmarshaler)
   263  		}
   264  
   265  		if iv := v; iv.Kind() == reflect.Interface && !iv.IsNil() {
   266  			v = iv.Elem()
   267  			continue
   268  		}
   269  		pv := v
   270  		if pv.Kind() != reflect.Ptr {
   271  			break
   272  		}
   273  
   274  		if pv.Elem().Kind() != reflect.Ptr &&
   275  			wantptr && !isUnmarshaler {
   276  			return nil, pv
   277  		}
   278  		if pv.IsNil() {
   279  			pv.Set(reflect.Zero(pv.Type().Elem()).Addr())
   280  		}
   281  		if isUnmarshaler {
   282  			// Using v.Interface().(Unmarshaler)
   283  			// here means that we have to use a pointer
   284  			// as the struct field.  We cannot use a value inside
   285  			// a pointer to a struct, because in that case
   286  			// v.Interface() is the value (x.f) not the pointer (&x.f).
   287  			// This is an unfortunate consequence of reflect.
   288  			// An alternative would be to look up the
   289  			// UnmarshalJSON method and return a FuncValue.
   290  			return v.Interface().(Unmarshaler), reflect.Value{}
   291  		}
   292  		v = pv.Elem()
   293  	}
   294  	return nil, v
   295  }
   296  
   297  // array consumes an array from d.data[d.off-1:], decoding into the value v.
   298  // the first byte of the array ('[') has been read already.
   299  func (d *decodeState) array(v reflect.Value) {
   300  	// Check for unmarshaler.
   301  	unmarshaler, pv := d.indirect(v, false)
   302  	if unmarshaler != nil {
   303  		d.off--
   304  		err := unmarshaler.UnmarshalJSON(d.next())
   305  		if err != nil {
   306  			d.error(err)
   307  		}
   308  		return
   309  	}
   310  	v = pv
   311  
   312  	// Decoding into nil interface?  Switch to non-reflect code.
   313  	iv := v
   314  	ok := iv.Kind() == reflect.Interface
   315  	if ok {
   316  		iv.Set(reflect.ValueOf(d.arrayInterface()))
   317  		return
   318  	}
   319  
   320  	// Check type of target.
   321  	av := v
   322  	if av.Kind() != reflect.Array && av.Kind() != reflect.Slice {
   323  		d.saveError(&UnmarshalTypeError{"array", v.Type()})
   324  		d.off--
   325  		d.next()
   326  		return
   327  	}
   328  
   329  	sv := v
   330  
   331  	i := 0
   332  	for {
   333  		// Look ahead for ] - can only happen on first iteration.
   334  		op := d.scanWhile(scanSkipSpace)
   335  		if op == scanEndArray {
   336  			break
   337  		}
   338  
   339  		// Back up so d.value can have the byte we just read.
   340  		d.off--
   341  		d.scan.undo(op)
   342  
   343  		// Get element of array, growing if necessary.
   344  		if i >= av.Cap() && sv.IsValid() {
   345  			newcap := sv.Cap() + sv.Cap()/2
   346  			if newcap < 4 {
   347  				newcap = 4
   348  			}
   349  			newv := reflect.MakeSlice(sv.Type(), sv.Len(), newcap)
   350  			reflect.Copy(newv, sv)
   351  			sv.Set(newv)
   352  		}
   353  		if i >= av.Len() && sv.IsValid() {
   354  			// Must be slice; gave up on array during i >= av.Cap().
   355  			sv.SetLen(i + 1)
   356  		}
   357  
   358  		// Decode into element.
   359  		if i < av.Len() {
   360  			d.value(av.Index(i))
   361  		} else {
   362  			// Ran out of fixed array: skip.
   363  			d.value(reflect.Value{})
   364  		}
   365  		i++
   366  
   367  		// Next token must be , or ].
   368  		op = d.scanWhile(scanSkipSpace)
   369  		if op == scanEndArray {
   370  			break
   371  		}
   372  		if op != scanArrayValue {
   373  			d.error(errPhase)
   374  		}
   375  	}
   376  	if i < av.Len() {
   377  		if !sv.IsValid() {
   378  			// Array.  Zero the rest.
   379  			z := reflect.Zero(av.Type().Elem())
   380  			for ; i < av.Len(); i++ {
   381  				av.Index(i).Set(z)
   382  			}
   383  		} else {
   384  			sv.SetLen(i)
   385  		}
   386  	}
   387  }
   388  
   389  // matchName returns true if key should be written to a field named name.
   390  func matchName(key, name string) bool {
   391  	return strings.ToLower(key) == strings.ToLower(name)
   392  }
   393  
   394  // object consumes an object from d.data[d.off-1:], decoding into the value v.
   395  // the first byte of the object ('{') has been read already.
   396  func (d *decodeState) object(v reflect.Value) {
   397  	// Check for unmarshaler.
   398  	unmarshaler, pv := d.indirect(v, false)
   399  	if unmarshaler != nil {
   400  		d.off--
   401  		err := unmarshaler.UnmarshalJSON(d.next())
   402  		if err != nil {
   403  			d.error(err)
   404  		}
   405  		return
   406  	}
   407  	v = pv
   408  
   409  	// Decoding into nil interface?  Switch to non-reflect code.
   410  	iv := v
   411  	if iv.Kind() == reflect.Interface {
   412  		iv.Set(reflect.ValueOf(d.objectInterface()))
   413  		return
   414  	}
   415  
   416  	// Check type of target: struct or map[string]T
   417  	var (
   418  		mv reflect.Value
   419  		sv reflect.Value
   420  	)
   421  	switch v.Kind() {
   422  	case reflect.Map:
   423  		// map must have string type
   424  		t := v.Type()
   425  		if t.Key() != reflect.TypeOf("") {
   426  			d.saveError(&UnmarshalTypeError{"object", v.Type()})
   427  			break
   428  		}
   429  		mv = v
   430  		if mv.IsNil() {
   431  			mv.Set(reflect.MakeMap(t))
   432  		}
   433  	case reflect.Struct:
   434  		sv = v
   435  	default:
   436  		d.saveError(&UnmarshalTypeError{"object", v.Type()})
   437  	}
   438  
   439  	if !mv.IsValid() && !sv.IsValid() {
   440  		d.off--
   441  		d.next() // skip over { } in input
   442  		return
   443  	}
   444  
   445  	for {
   446  		// Read opening " of string key or closing }.
   447  		op := d.scanWhile(scanSkipSpace)
   448  		if op == scanEndObject {
   449  			// closing } - can only happen on first iteration.
   450  			break
   451  		}
   452  		if op != scanBeginLiteral {
   453  			d.error(errPhase)
   454  		}
   455  
   456  		// Read string key.
   457  		start := d.off - 1
   458  		op = d.scanWhile(scanContinue)
   459  		item := d.data[start : d.off-1]
   460  		key, ok := unquote(item)
   461  		if !ok {
   462  			d.error(errPhase)
   463  		}
   464  
   465  		// Figure out field corresponding to key.
   466  		var subv reflect.Value
   467  		if mv.IsValid() {
   468  			subv = reflect.Zero(mv.Type().Elem())
   469  		} else {
   470  			var f reflect.StructField
   471  			var ok bool
   472  			st := sv.Type()
   473  			// First try for field with that tag.
   474  			if isValidTag(key) {
   475  				for i := 0; i < sv.NumField(); i++ {
   476  					f = st.Field(i)
   477  					if f.Tag == key {
   478  						ok = true
   479  						break
   480  					}
   481  				}
   482  			}
   483  			if !ok {
   484  				// Second, exact match.
   485  				f, ok = st.FieldByName(key)
   486  			}
   487  			if !ok {
   488  				// Third, case-insensitive match.
   489  				f, ok = st.FieldByNameFunc(func(s string) bool { return matchName(key, s) })
   490  			}
   491  
   492  			// Extract value; name must be exported.
   493  			if ok {
   494  				if f.PkgPath != "" {
   495  					d.saveError(&UnmarshalFieldError{key, st, f})
   496  				} else {
   497  					subv = sv.FieldByIndex(f.Index)
   498  				}
   499  			}
   500  		}
   501  
   502  		// Read : before value.
   503  		if op == scanSkipSpace {
   504  			op = d.scanWhile(scanSkipSpace)
   505  		}
   506  		if op != scanObjectKey {
   507  			d.error(errPhase)
   508  		}
   509  
   510  		// Read value.
   511  		d.value(subv)
   512  
   513  		// Write value back to map;
   514  		// if using struct, subv points into struct already.
   515  		if mv.IsValid() {
   516  			mv.SetMapIndex(reflect.ValueOf(key), subv)
   517  		}
   518  
   519  		// Next token must be , or }.
   520  		op = d.scanWhile(scanSkipSpace)
   521  		if op == scanEndObject {
   522  			break
   523  		}
   524  		if op != scanObjectValue {
   525  			d.error(errPhase)
   526  		}
   527  	}
   528  }
   529  
   530  // literal consumes a literal from d.data[d.off-1:], decoding into the value v.
   531  // The first byte of the literal has been read already
   532  // (that's how the caller knows it's a literal).
   533  func (d *decodeState) literal(v reflect.Value) {
   534  	// All bytes inside literal return scanContinue op code.
   535  	start := d.off - 1
   536  	op := d.scanWhile(scanContinue)
   537  
   538  	// Scan read one byte too far; back up.
   539  	d.off--
   540  	d.scan.undo(op)
   541  	item := d.data[start:d.off]
   542  
   543  	// Check for unmarshaler.
   544  	wantptr := item[0] == 'n' // null
   545  	unmarshaler, pv := d.indirect(v, wantptr)
   546  	if unmarshaler != nil {
   547  		err := unmarshaler.UnmarshalJSON(item)
   548  		if err != nil {
   549  			d.error(err)
   550  		}
   551  		return
   552  	}
   553  	v = pv
   554  
   555  	switch c := item[0]; c {
   556  	case 'n': // null
   557  		switch v.Kind() {
   558  		default:
   559  			d.saveError(&UnmarshalTypeError{"null", v.Type()})
   560  		case reflect.Interface, reflect.Ptr, reflect.Map:
   561  			v.Set(reflect.Zero(v.Type()))
   562  		}
   563  
   564  	case 't', 'f': // true, false
   565  		value := c == 't'
   566  		switch v.Kind() {
   567  		default:
   568  			d.saveError(&UnmarshalTypeError{"bool", v.Type()})
   569  		case reflect.Bool:
   570  			v.SetBool(value)
   571  		case reflect.Interface:
   572  			v.Set(reflect.ValueOf(value))
   573  		}
   574  
   575  	case '"': // string
   576  		s, ok := unquoteBytes(item)
   577  		if !ok {
   578  			d.error(errPhase)
   579  		}
   580  		switch v.Kind() {
   581  		default:
   582  			d.saveError(&UnmarshalTypeError{"string", v.Type()})
   583  		case reflect.Slice:
   584  			if v.Type() != byteSliceType {
   585  				d.saveError(&UnmarshalTypeError{"string", v.Type()})
   586  				break
   587  			}
   588  			b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
   589  			n, err := base64.StdEncoding.Decode(b, s)
   590  			if err != nil {
   591  				d.saveError(err)
   592  				break
   593  			}
   594  			v.Set(reflect.ValueOf(b[0:n]))
   595  		case reflect.String:
   596  			v.SetString(string(s))
   597  		case reflect.Interface:
   598  			v.Set(reflect.ValueOf(string(s)))
   599  		}
   600  
   601  	default: // number
   602  		if c != '-' && (c < '0' || c > '9') {
   603  			d.error(errPhase)
   604  		}
   605  		s := string(item)
   606  		switch v.Kind() {
   607  		default:
   608  			d.error(&UnmarshalTypeError{"number", v.Type()})
   609  		case reflect.Interface:
   610  			n, err := strconv.Atof64(s)
   611  			if err != nil {
   612  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
   613  				break
   614  			}
   615  			v.Set(reflect.ValueOf(n))
   616  
   617  		case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
   618  			n, err := strconv.Atoi64(s)
   619  			if err != nil || v.OverflowInt(n) {
   620  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
   621  				break
   622  			}
   623  			v.SetInt(n)
   624  
   625  		case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
   626  			n, err := strconv.Atoui64(s)
   627  			if err != nil || v.OverflowUint(n) {
   628  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
   629  				break
   630  			}
   631  			v.SetUint(n)
   632  
   633  		case reflect.Float32, reflect.Float64:
   634  			n, err := strconv.AtofN(s, v.Type().Bits())
   635  			if err != nil || v.OverflowFloat(n) {
   636  				d.saveError(&UnmarshalTypeError{"number " + s, v.Type()})
   637  				break
   638  			}
   639  			v.SetFloat(n)
   640  		}
   641  	}
   642  }
   643  
   644  // The xxxInterface routines build up a value to be stored
   645  // in an empty interface.  They are not strictly necessary,
   646  // but they avoid the weight of reflection in this common case.
   647  
   648  // valueInterface is like value but returns interface{}
   649  func (d *decodeState) valueInterface() interface{} {
   650  	switch d.scanWhile(scanSkipSpace) {
   651  	default:
   652  		d.error(errPhase)
   653  	case scanBeginArray:
   654  		return d.arrayInterface()
   655  	case scanBeginObject:
   656  		return d.objectInterface()
   657  	case scanBeginLiteral:
   658  		return d.literalInterface()
   659  	}
   660  	panic("unreachable")
   661  }
   662  
   663  // arrayInterface is like array but returns []interface{}.
   664  func (d *decodeState) arrayInterface() []interface{} {
   665  	var v vector.Vector
   666  	for {
   667  		// Look ahead for ] - can only happen on first iteration.
   668  		op := d.scanWhile(scanSkipSpace)
   669  		if op == scanEndArray {
   670  			break
   671  		}
   672  
   673  		// Back up so d.value can have the byte we just read.
   674  		d.off--
   675  		d.scan.undo(op)
   676  
   677  		v.Push(d.valueInterface())
   678  
   679  		// Next token must be , or ].
   680  		op = d.scanWhile(scanSkipSpace)
   681  		if op == scanEndArray {
   682  			break
   683  		}
   684  		if op != scanArrayValue {
   685  			d.error(errPhase)
   686  		}
   687  	}
   688  	return v
   689  }
   690  
   691  // objectInterface is like object but returns map[string]interface{}.
   692  func (d *decodeState) objectInterface() map[string]interface{} {
   693  	m := make(map[string]interface{})
   694  	for {
   695  		// Read opening " of string key or closing }.
   696  		op := d.scanWhile(scanSkipSpace)
   697  		if op == scanEndObject {
   698  			// closing } - can only happen on first iteration.
   699  			break
   700  		}
   701  		if op != scanBeginLiteral {
   702  			d.error(errPhase)
   703  		}
   704  
   705  		// Read string key.
   706  		start := d.off - 1
   707  		op = d.scanWhile(scanContinue)
   708  		item := d.data[start : d.off-1]
   709  		key, ok := unquote(item)
   710  		if !ok {
   711  			d.error(errPhase)
   712  		}
   713  
   714  		// Read : before value.
   715  		if op == scanSkipSpace {
   716  			op = d.scanWhile(scanSkipSpace)
   717  		}
   718  		if op != scanObjectKey {
   719  			d.error(errPhase)
   720  		}
   721  
   722  		// Read value.
   723  		m[key] = d.valueInterface()
   724  
   725  		// Next token must be , or }.
   726  		op = d.scanWhile(scanSkipSpace)
   727  		if op == scanEndObject {
   728  			break
   729  		}
   730  		if op != scanObjectValue {
   731  			d.error(errPhase)
   732  		}
   733  	}
   734  	return m
   735  }
   736  
   737  // literalInterface is like literal but returns an interface value.
   738  func (d *decodeState) literalInterface() interface{} {
   739  	// All bytes inside literal return scanContinue op code.
   740  	start := d.off - 1
   741  	op := d.scanWhile(scanContinue)
   742  
   743  	// Scan read one byte too far; back up.
   744  	d.off--
   745  	d.scan.undo(op)
   746  	item := d.data[start:d.off]
   747  
   748  	switch c := item[0]; c {
   749  	case 'n': // null
   750  		return nil
   751  
   752  	case 't', 'f': // true, false
   753  		return c == 't'
   754  
   755  	case '"': // string
   756  		s, ok := unquote(item)
   757  		if !ok {
   758  			d.error(errPhase)
   759  		}
   760  		return s
   761  
   762  	default: // number
   763  		if c != '-' && (c < '0' || c > '9') {
   764  			d.error(errPhase)
   765  		}
   766  		n, err := strconv.Atof64(string(item))
   767  		if err != nil {
   768  			d.saveError(&UnmarshalTypeError{"number " + string(item), reflect.TypeOf(0.0)})
   769  		}
   770  		return n
   771  	}
   772  	panic("unreachable")
   773  }
   774  
   775  // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
   776  // or it returns -1.
   777  func getu4(s []byte) int {
   778  	if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
   779  		return -1
   780  	}
   781  	rune, err := strconv.Btoui64(string(s[2:6]), 16)
   782  	if err != nil {
   783  		return -1
   784  	}
   785  	return int(rune)
   786  }
   787  
   788  // unquote converts a quoted JSON string literal s into an actual string t.
   789  // The rules are different than for Go, so cannot use strconv.Unquote.
   790  func unquote(s []byte) (t string, ok bool) {
   791  	s, ok = unquoteBytes(s)
   792  	t = string(s)
   793  	return
   794  }
   795  
   796  func unquoteBytes(s []byte) (t []byte, ok bool) {
   797  	if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
   798  		return
   799  	}
   800  	s = s[1 : len(s)-1]
   801  
   802  	// Check for unusual characters. If there are none,
   803  	// then no unquoting is needed, so return a slice of the
   804  	// original bytes.
   805  	r := 0
   806  	for r < len(s) {
   807  		c := s[r]
   808  		if c == '\\' || c == '"' || c < ' ' {
   809  			break
   810  		}
   811  		if c < utf8.RuneSelf {
   812  			r++
   813  			continue
   814  		}
   815  		rune, size := utf8.DecodeRune(s[r:])
   816  		if rune == utf8.RuneError && size == 1 {
   817  			break
   818  		}
   819  		r += size
   820  	}
   821  	if r == len(s) {
   822  		return s, true
   823  	}
   824  
   825  	b := make([]byte, len(s)+2*utf8.UTFMax)
   826  	w := copy(b, s[0:r])
   827  	for r < len(s) {
   828  		// Out of room?  Can only happen if s is full of
   829  		// malformed UTF-8 and we're replacing each
   830  		// byte with RuneError.
   831  		if w >= len(b)-2*utf8.UTFMax {
   832  			nb := make([]byte, (len(b)+utf8.UTFMax)*2)
   833  			copy(nb, b[0:w])
   834  			b = nb
   835  		}
   836  		switch c := s[r]; {
   837  		case c == '\\':
   838  			r++
   839  			if r >= len(s) {
   840  				return
   841  			}
   842  			switch s[r] {
   843  			default:
   844  				return
   845  			case '"', '\\', '/', '\'':
   846  				b[w] = s[r]
   847  				r++
   848  				w++
   849  			case 'b':
   850  				b[w] = '\b'
   851  				r++
   852  				w++
   853  			case 'f':
   854  				b[w] = '\f'
   855  				r++
   856  				w++
   857  			case 'n':
   858  				b[w] = '\n'
   859  				r++
   860  				w++
   861  			case 'r':
   862  				b[w] = '\r'
   863  				r++
   864  				w++
   865  			case 't':
   866  				b[w] = '\t'
   867  				r++
   868  				w++
   869  			case 'u':
   870  				r--
   871  				rune := getu4(s[r:])
   872  				if rune < 0 {
   873  					return
   874  				}
   875  				r += 6
   876  				if utf16.IsSurrogate(rune) {
   877  					rune1 := getu4(s[r:])
   878  					if dec := utf16.DecodeRune(rune, rune1); dec != unicode.ReplacementChar {
   879  						// A valid pair; consume.
   880  						r += 6
   881  						w += utf8.EncodeRune(b[w:], dec)
   882  						break
   883  					}
   884  					// Invalid surrogate; fall back to replacement rune.
   885  					rune = unicode.ReplacementChar
   886  				}
   887  				w += utf8.EncodeRune(b[w:], rune)
   888  			}
   889  
   890  		// Quote, control characters are invalid.
   891  		case c == '"', c < ' ':
   892  			return
   893  
   894  		// ASCII
   895  		case c < utf8.RuneSelf:
   896  			b[w] = c
   897  			r++
   898  			w++
   899  
   900  		// Coerce to well-formed UTF-8.
   901  		default:
   902  			rune, size := utf8.DecodeRune(s[r:])
   903  			r += size
   904  			w += utf8.EncodeRune(b[w:], rune)
   905  		}
   906  	}
   907  	return b[0:w], true
   908  }