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