Debian Codegraph @

decode.go

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