Debian Codegraph @

internal/json/decode.go

raw
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 map, Unmarshal first establishes a map to
65 // use, If the map is nil, Unmarshal allocates a new map. Otherwise Unmarshal
66 // reuses the existing map, keeping existing entries. Unmarshal then stores key-
67 // value pairs from the JSON object into the map. The map's key type must
68 // either be a string or implement encoding.TextUnmarshaler.
69 //
70 // If a JSON value is not appropriate for a given target type,
71 // or if a JSON number overflows the target type, Unmarshal
72 // skips that field and completes the unmarshaling as best it can.
73 // If no more serious errors are encountered, Unmarshal returns
74 // an UnmarshalTypeError describing the earliest such error.
75 //
76 // The JSON null value unmarshals into an interface, map, pointer, or slice
77 // by setting that Go value to nil. Because null is often used in JSON to mean
78 // ``not present,'' unmarshaling a JSON null into any other Go type has no effect
79 // on the value and produces no error.
80 //
81 // When unmarshaling quoted strings, invalid UTF-8 or
82 // invalid UTF-16 surrogate pairs are not treated as an error.
83 // Instead, they are replaced by the Unicode replacement
84 // character U+FFFD.
85 //
86 func Unmarshal(data []byte, v interface{}) error {
87 // Check for well-formedness.
88 // Avoids filling out half a data structure
89 // before discovering a JSON syntax error.
90 var d decodeState
91 err := checkValid(data, &d.scan)
92 if err != nil {
93 return err
94 }
95
96 d.init(data)
97 return d.unmarshal(v)
98 }
99
100 // Unmarshaler is the interface implemented by types
101 // that can unmarshal a JSON description of themselves.
102 // The input can be assumed to be a valid encoding of
103 // a JSON value. UnmarshalJSON must copy the JSON data
104 // if it wishes to retain the data after returning.
105 type Unmarshaler interface {
106 UnmarshalJSON([]byte) error
107 }
108
109 // An UnmarshalTypeError describes a JSON value that was
110 // not appropriate for a value of a specific Go type.
111 type UnmarshalTypeError struct {
112 Value string // description of JSON value - "bool", "array", "number -5"
113 Type reflect.Type // type of Go value it could not be assigned to
114 Offset int64 // error occurred after reading Offset bytes
115 }
116
117 func (e *UnmarshalTypeError) Error() string {
118 return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String()
119 }
120
121 // An UnmarshalFieldError describes a JSON object key that
122 // led to an unexported (and therefore unwritable) struct field.
123 // (No longer used; kept for compatibility.)
124 type UnmarshalFieldError struct {
125 Key string
126 Type reflect.Type
127 Field reflect.StructField
128 }
129
130 func (e *UnmarshalFieldError) Error() string {
131 return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String()
132 }
133
134 // An InvalidUnmarshalError describes an invalid argument passed to Unmarshal.
135 // (The argument to Unmarshal must be a non-nil pointer.)
136 type InvalidUnmarshalError struct {
137 Type reflect.Type
138 }
139
140 func (e *InvalidUnmarshalError) Error() string {
141 if e.Type == nil {
142 return "json: Unmarshal(nil)"
143 }
144
145 if e.Type.Kind() != reflect.Ptr {
146 return "json: Unmarshal(non-pointer " + e.Type.String() + ")"
147 }
148 return "json: Unmarshal(nil " + e.Type.String() + ")"
149 }
150
151 func (d *decodeState) unmarshal(v interface{}) (err error) {
152 defer func() {
153 if r := recover(); r != nil {
154 if _, ok := r.(runtime.Error); ok {
155 panic(r)
156 }
157 err = r.(error)
158 }
159 }()
160
161 rv := reflect.ValueOf(v)
162 if rv.Kind() != reflect.Ptr || rv.IsNil() {
163 return &InvalidUnmarshalError{reflect.TypeOf(v)}
164 }
165
166 d.scan.reset()
167 // We decode rv not rv.Elem because the Unmarshaler interface
168 // test must be applied at the top level of the value.
169 d.value(rv)
170 return d.savedError
171 }
172
173 // A Number represents a JSON number literal.
174 type Number string
175
176 // String returns the literal text of the number.
177 func (n Number) String() string { return string(n) }
178
179 // Float64 returns the number as a float64.
180 func (n Number) Float64() (float64, error) {
181 return strconv.ParseFloat(string(n), 64)
182 }
183
184 // Int64 returns the number as an int64.
185 func (n Number) Int64() (int64, error) {
186 return strconv.ParseInt(string(n), 10, 64)
187 }
188
189 // isValidNumber reports whether s is a valid JSON number literal.
190 func isValidNumber(s string) bool {
191 // This function implements the JSON numbers grammar.
192 // See https://tools.ietf.org/html/rfc7159#section-6
193 // and http://json.org/number.gif
194
195 if s == "" {
196 return false
197 }
198
199 // Optional -
200 if s[0] == '-' {
201 s = s[1:]
202 if s == "" {
203 return false
204 }
205 }
206
207 // Digits
208 switch {
209 default:
210 return false
211
212 case s[0] == '0':
213 s = s[1:]
214
215 case '1' <= s[0] && s[0] <= '9':
216 s = s[1:]
217 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
218 s = s[1:]
219 }
220 }
221
222 // . followed by 1 or more digits.
223 if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' {
224 s = s[2:]
225 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
226 s = s[1:]
227 }
228 }
229
230 // e or E followed by an optional - or + and
231 // 1 or more digits.
232 if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') {
233 s = s[1:]
234 if s[0] == '+' || s[0] == '-' {
235 s = s[1:]
236 if s == "" {
237 return false
238 }
239 }
240 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' {
241 s = s[1:]
242 }
243 }
244
245 // Make sure we are at the end.
246 return s == ""
247 }
248
249 // decodeState represents the state while decoding a JSON value.
250 type decodeState struct {
251 data []byte
252 off int // read offset in data
253 scan scanner
254 nextscan scanner // for calls to nextValue
255 savedError error
256 useNumber bool
257 ext Extension
258 }
259
260 // errPhase is used for errors that should not happen unless
261 // there is a bug in the JSON decoder or something is editing
262 // the data slice while the decoder executes.
263 var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?")
264
265 func (d *decodeState) init(data []byte) *decodeState {
266 d.data = data
267 d.off = 0
268 d.savedError = nil
269 return d
270 }
271
272 // error aborts the decoding by panicking with err.
273 func (d *decodeState) error(err error) {
274 panic(err)
275 }
276
277 // saveError saves the first err it is called with,
278 // for reporting at the end of the unmarshal.
279 func (d *decodeState) saveError(err error) {
280 if d.savedError == nil {
281 d.savedError = err
282 }
283 }
284
285 // next cuts off and returns the next full JSON value in d.data[d.off:].
286 // The next value is known to be an object or array, not a literal.
287 func (d *decodeState) next() []byte {
288 c := d.data[d.off]
289 item, rest, err := nextValue(d.data[d.off:], &d.nextscan)
290 if err != nil {
291 d.error(err)
292 }
293 d.off = len(d.data) - len(rest)
294
295 // Our scanner has seen the opening brace/bracket
296 // and thinks we're still in the middle of the object.
297 // invent a closing brace/bracket to get it out.
298 if c == '{' {
299 d.scan.step(&d.scan, '}')
300 } else if c == '[' {
301 d.scan.step(&d.scan, ']')
302 } else {
303 // Was inside a function name. Get out of it.
304 d.scan.step(&d.scan, '(')
305 d.scan.step(&d.scan, ')')
306 }
307
308 return item
309 }
310
311 // scanWhile processes bytes in d.data[d.off:] until it
312 // receives a scan code not equal to op.
313 // It updates d.off and returns the new scan code.
314 func (d *decodeState) scanWhile(op int) int {
315 var newOp int
316 for {
317 if d.off >= len(d.data) {
318 newOp = d.scan.eof()
319 d.off = len(d.data) + 1 // mark processed EOF with len+1
320 } else {
321 c := d.data[d.off]
322 d.off++
323 newOp = d.scan.step(&d.scan, c)
324 }
325 if newOp != op {
326 break
327 }
328 }
329 return newOp
330 }
331
332 // value decodes a JSON value from d.data[d.off:] into the value.
333 // it updates d.off to point past the decoded value.
334 func (d *decodeState) value(v reflect.Value) {
335 if !v.IsValid() {
336 _, rest, err := nextValue(d.data[d.off:], &d.nextscan)
337 if err != nil {
338 d.error(err)
339 }
340 d.off = len(d.data) - len(rest)
341
342 // d.scan thinks we're still at the beginning of the item.
343 // Feed in an empty string - the shortest, simplest value -
344 // so that it knows we got to the end of the value.
345 if d.scan.redo {
346 // rewind.
347 d.scan.redo = false
348 d.scan.step = stateBeginValue
349 }
350 d.scan.step(&d.scan, '"')
351 d.scan.step(&d.scan, '"')
352
353 n := len(d.scan.parseState)
354 if n > 0 && d.scan.parseState[n-1] == parseObjectKey {
355 // d.scan thinks we just read an object key; finish the object
356 d.scan.step(&d.scan, ':')
357 d.scan.step(&d.scan, '"')
358 d.scan.step(&d.scan, '"')
359 d.scan.step(&d.scan, '}')
360 }
361
362 return
363 }
364
365 switch op := d.scanWhile(scanSkipSpace); op {
366 default:
367 d.error(errPhase)
368
369 case scanBeginArray:
370 d.array(v)
371
372 case scanBeginObject:
373 d.object(v)
374
375 case scanBeginLiteral:
376 d.literal(v)
377
378 case scanBeginName:
379 d.name(v)
380 }
381 }
382
383 type unquotedValue struct{}
384
385 // valueQuoted is like value but decodes a
386 // quoted string literal or literal null into an interface value.
387 // If it finds anything other than a quoted string literal or null,
388 // valueQuoted returns unquotedValue{}.
389 func (d *decodeState) valueQuoted() interface{} {
390 switch op := d.scanWhile(scanSkipSpace); op {
391 default:
392 d.error(errPhase)
393
394 case scanBeginArray:
395 d.array(reflect.Value{})
396
397 case scanBeginObject:
398 d.object(reflect.Value{})
399
400 case scanBeginName:
401 switch v := d.nameInterface().(type) {
402 case nil, string:
403 return v
404 }
405
406 case scanBeginLiteral:
407 switch v := d.literalInterface().(type) {
408 case nil, string:
409 return v
410 }
411 }
412 return unquotedValue{}
413 }
414
415 // indirect walks down v allocating pointers as needed,
416 // until it gets to a non-pointer.
417 // if it encounters an Unmarshaler, indirect stops and returns that.
418 // if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
419 func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
420 // If v is a named type and is addressable,
421 // start with its address, so that if the type has pointer methods,
422 // we find them.
423 if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
424 v = v.Addr()
425 }
426 for {
427 // Load value from interface, but only if the result will be
428 // usefully addressable.
429 if v.Kind() == reflect.Interface && !v.IsNil() {
430 e := v.Elem()
431 if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
432 v = e
433 continue
434 }
435 }
436
437 if v.Kind() != reflect.Ptr {
438 break
439 }
440
441 if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
442 break
443 }
444 if v.IsNil() {
445 v.Set(reflect.New(v.Type().Elem()))
446 }
447 if v.Type().NumMethod() > 0 {
448 if u, ok := v.Interface().(Unmarshaler); ok {
449 return u, nil, v
450 }
451 if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
452 return nil, u, v
453 }
454 }
455 v = v.Elem()
456 }
457 return nil, nil, v
458 }
459
460 // array consumes an array from d.data[d.off-1:], decoding into the value v.
461 // the first byte of the array ('[') has been read already.
462 func (d *decodeState) array(v reflect.Value) {
463 // Check for unmarshaler.
464 u, ut, pv := d.indirect(v, false)
465 if u != nil {
466 d.off--
467 err := u.UnmarshalJSON(d.next())
468 if err != nil {
469 d.error(err)
470 }
471 return
472 }
473 if ut != nil {
474 d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)})
475 d.off--
476 d.next()
477 return
478 }
479
480 v = pv
481
482 // Check type of target.
483 switch v.Kind() {
484 case reflect.Interface:
485 if v.NumMethod() == 0 {
486 // Decoding into nil interface? Switch to non-reflect code.
487 v.Set(reflect.ValueOf(d.arrayInterface()))
488 return
489 }
490 // Otherwise it's invalid.
491 fallthrough
492 default:
493 d.saveError(&UnmarshalTypeError{"array", v.Type(), int64(d.off)})
494 d.off--
495 d.next()
496 return
497 case reflect.Array:
498 case reflect.Slice:
499 break
500 }
501
502 i := 0
503 for {
504 // Look ahead for ] - can only happen on first iteration.
505 op := d.scanWhile(scanSkipSpace)
506 if op == scanEndArray {
507 break
508 }
509
510 // Back up so d.value can have the byte we just read.
511 d.off--
512 d.scan.undo(op)
513
514 // Get element of array, growing if necessary.
515 if v.Kind() == reflect.Slice {
516 // Grow slice if necessary
517 if i >= v.Cap() {
518 newcap := v.Cap() + v.Cap()/2
519 if newcap < 4 {
520 newcap = 4
521 }
522 newv := reflect.MakeSlice(v.Type(), v.Len(), newcap)
523 reflect.Copy(newv, v)
524 v.Set(newv)
525 }
526 if i >= v.Len() {
527 v.SetLen(i + 1)
528 }
529 }
530
531 if i < v.Len() {
532 // Decode into element.
533 d.value(v.Index(i))
534 } else {
535 // Ran out of fixed array: skip.
536 d.value(reflect.Value{})
537 }
538 i++
539
540 // Next token must be , or ].
541 op = d.scanWhile(scanSkipSpace)
542 if op == scanEndArray {
543 break
544 }
545 if op != scanArrayValue {
546 d.error(errPhase)
547 }
548 }
549
550 if i < v.Len() {
551 if v.Kind() == reflect.Array {
552 // Array. Zero the rest.
553 z := reflect.Zero(v.Type().Elem())
554 for ; i < v.Len(); i++ {
555 v.Index(i).Set(z)
556 }
557 } else {
558 v.SetLen(i)
559 }
560 }
561 if i == 0 && v.Kind() == reflect.Slice {
562 v.Set(reflect.MakeSlice(v.Type(), 0, 0))
563 }
564 }
565
566 var nullLiteral = []byte("null")
567 var textUnmarshalerType = reflect.TypeOf(new(encoding.TextUnmarshaler)).Elem()
568
569 // object consumes an object from d.data[d.off-1:], decoding into the value v.
570 // the first byte ('{') of the object has been read already.
571 func (d *decodeState) object(v reflect.Value) {
572 // Check for unmarshaler.
573 u, ut, pv := d.indirect(v, false)
574 if d.storeKeyed(pv) {
575 return
576 }
577 if u != nil {
578 d.off--
579 err := u.UnmarshalJSON(d.next())
580 if err != nil {
581 d.error(err)
582 }
583 return
584 }
585 if ut != nil {
586 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
587 d.off--
588 d.next() // skip over { } in input
589 return
590 }
591 v = pv
592
593 // Decoding into nil interface? Switch to non-reflect code.
594 if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
595 v.Set(reflect.ValueOf(d.objectInterface()))
596 return
597 }
598
599 // Check type of target:
600 // struct or
601 // map[string]T or map[encoding.TextUnmarshaler]T
602 switch v.Kind() {
603 case reflect.Map:
604 // Map key must either have string kind or be an encoding.TextUnmarshaler.
605 t := v.Type()
606 if t.Key().Kind() != reflect.String &&
607 !reflect.PtrTo(t.Key()).Implements(textUnmarshalerType) {
608 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
609 d.off--
610 d.next() // skip over { } in input
611 return
612 }
613 if v.IsNil() {
614 v.Set(reflect.MakeMap(t))
615 }
616 case reflect.Struct:
617
618 default:
619 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
620 d.off--
621 d.next() // skip over { } in input
622 return
623 }
624
625 var mapElem reflect.Value
626
627 empty := true
628 for {
629 // Read opening " of string key or closing }.
630 op := d.scanWhile(scanSkipSpace)
631 if op == scanEndObject {
632 if !empty && !d.ext.trailingCommas {
633 d.syntaxError("beginning of object key string")
634 }
635 break
636 }
637 empty = false
638 if op == scanBeginName {
639 if !d.ext.unquotedKeys {
640 d.syntaxError("beginning of object key string")
641 }
642 } else if op != scanBeginLiteral {
643 d.error(errPhase)
644 }
645 unquotedKey := op == scanBeginName
646
647 // Read key.
648 start := d.off - 1
649 op = d.scanWhile(scanContinue)
650 item := d.data[start : d.off-1]
651 var key []byte
652 if unquotedKey {
653 key = item
654 // TODO Fix code below to quote item when necessary.
655 } else {
656 var ok bool
657 key, ok = unquoteBytes(item)
658 if !ok {
659 d.error(errPhase)
660 }
661 }
662
663 // Figure out field corresponding to key.
664 var subv reflect.Value
665 destring := false // whether the value is wrapped in a string to be decoded first
666
667 if v.Kind() == reflect.Map {
668 elemType := v.Type().Elem()
669 if !mapElem.IsValid() {
670 mapElem = reflect.New(elemType).Elem()
671 } else {
672 mapElem.Set(reflect.Zero(elemType))
673 }
674 subv = mapElem
675 } else {
676 var f *field
677 fields := cachedTypeFields(v.Type())
678 for i := range fields {
679 ff := &fields[i]
680 if bytes.Equal(ff.nameBytes, key) {
681 f = ff
682 break
683 }
684 if f == nil && ff.equalFold(ff.nameBytes, key) {
685 f = ff
686 }
687 }
688 if f != nil {
689 subv = v
690 destring = f.quoted
691 for _, i := range f.index {
692 if subv.Kind() == reflect.Ptr {
693 if subv.IsNil() {
694 subv.Set(reflect.New(subv.Type().Elem()))
695 }
696 subv = subv.Elem()
697 }
698 subv = subv.Field(i)
699 }
700 }
701 }
702
703 // Read : before value.
704 if op == scanSkipSpace {
705 op = d.scanWhile(scanSkipSpace)
706 }
707 if op != scanObjectKey {
708 d.error(errPhase)
709 }
710
711 // Read value.
712 if destring {
713 switch qv := d.valueQuoted().(type) {
714 case nil:
715 d.literalStore(nullLiteral, subv, false)
716 case string:
717 d.literalStore([]byte(qv), subv, true)
718 default:
719 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
720 }
721 } else {
722 d.value(subv)
723 }
724
725 // Write value back to map;
726 // if using struct, subv points into struct already.
727 if v.Kind() == reflect.Map {
728 kt := v.Type().Key()
729 var kv reflect.Value
730 switch {
731 case kt.Kind() == reflect.String:
732 kv = reflect.ValueOf(key).Convert(v.Type().Key())
733 case reflect.PtrTo(kt).Implements(textUnmarshalerType):
734 kv = reflect.New(v.Type().Key())
735 d.literalStore(item, kv, true)
736 kv = kv.Elem()
737 default:
738 panic("json: Unexpected key type") // should never occur
739 }
740 v.SetMapIndex(kv, subv)
741 }
742
743 // Next token must be , or }.
744 op = d.scanWhile(scanSkipSpace)
745 if op == scanEndObject {
746 break
747 }
748 if op != scanObjectValue {
749 d.error(errPhase)
750 }
751 }
752 }
753
754 // isNull returns whether there's a null literal at the provided offset.
755 func (d *decodeState) isNull(off int) bool {
756 if off+4 >= len(d.data) || d.data[off] != 'n' || d.data[off+1] != 'u' || d.data[off+2] != 'l' || d.data[off+3] != 'l' {
757 return false
758 }
759 d.nextscan.reset()
760 for i, c := range d.data[off:] {
761 if i > 4 {
762 return false
763 }
764 switch d.nextscan.step(&d.nextscan, c) {
765 case scanContinue, scanBeginName:
766 continue
767 }
768 break
769 }
770 return true
771 }
772
773 // name consumes a const or function from d.data[d.off-1:], decoding into the value v.
774 // the first byte of the function name has been read already.
775 func (d *decodeState) name(v reflect.Value) {
776 if d.isNull(d.off-1) {
777 d.literal(v)
778 return
779 }
780
781 // Check for unmarshaler.
782 u, ut, pv := d.indirect(v, false)
783 if d.storeKeyed(pv) {
784 return
785 }
786 if u != nil {
787 d.off--
788 err := u.UnmarshalJSON(d.next())
789 if err != nil {
790 d.error(err)
791 }
792 return
793 }
794 if ut != nil {
795 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
796 d.off--
797 d.next() // skip over function in input
798 return
799 }
800 v = pv
801
802 // Decoding into nil interface? Switch to non-reflect code.
803 if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
804 out := d.nameInterface()
805 if out == nil {
806 v.Set(reflect.Zero(v.Type()))
807 } else {
808 v.Set(reflect.ValueOf(out))
809 }
810 return
811 }
812
813 nameStart := d.off - 1
814
815 op := d.scanWhile(scanContinue)
816
817 name := d.data[nameStart : d.off-1]
818 if op != scanParam {
819 // Back up so the byte just read is consumed next.
820 d.off--
821 d.scan.undo(op)
822 if l, ok := d.convertLiteral(name); ok {
823 d.storeValue(v, l)
824 return
825 }
826 d.error(&SyntaxError{fmt.Sprintf("json: unknown constant %q", name), int64(d.off)})
827 }
828
829 funcName := string(name)
830 funcData := d.ext.funcs[funcName]
831 if funcData.key == "" {
832 d.error(fmt.Errorf("json: unknown function %q", funcName))
833 }
834
835 // Check type of target:
836 // struct or
837 // map[string]T or map[encoding.TextUnmarshaler]T
838 switch v.Kind() {
839 case reflect.Map:
840 // Map key must either have string kind or be an encoding.TextUnmarshaler.
841 t := v.Type()
842 if t.Key().Kind() != reflect.String &&
843 !reflect.PtrTo(t.Key()).Implements(textUnmarshalerType) {
844 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
845 d.off--
846 d.next() // skip over { } in input
847 return
848 }
849 if v.IsNil() {
850 v.Set(reflect.MakeMap(t))
851 }
852 case reflect.Struct:
853
854 default:
855 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
856 d.off--
857 d.next() // skip over { } in input
858 return
859 }
860
861 // TODO Fix case of func field as map.
862 //topv := v
863
864 // Figure out field corresponding to function.
865 key := []byte(funcData.key)
866 if v.Kind() == reflect.Map {
867 elemType := v.Type().Elem()
868 v = reflect.New(elemType).Elem()
869 } else {
870 var f *field
871 fields := cachedTypeFields(v.Type())
872 for i := range fields {
873 ff := &fields[i]
874 if bytes.Equal(ff.nameBytes, key) {
875 f = ff
876 break
877 }
878 if f == nil && ff.equalFold(ff.nameBytes, key) {
879 f = ff
880 }
881 }
882 if f != nil {
883 for _, i := range f.index {
884 if v.Kind() == reflect.Ptr {
885 if v.IsNil() {
886 v.Set(reflect.New(v.Type().Elem()))
887 }
888 v = v.Elem()
889 }
890 v = v.Field(i)
891 }
892 if v.Kind() == reflect.Ptr {
893 if v.IsNil() {
894 v.Set(reflect.New(v.Type().Elem()))
895 }
896 v = v.Elem()
897 }
898 }
899 }
900
901 // Check for unmarshaler on func field itself.
902 u, ut, pv = d.indirect(v, false)
903 if u != nil {
904 d.off = nameStart
905 err := u.UnmarshalJSON(d.next())
906 if err != nil {
907 d.error(err)
908 }
909 return
910 }
911
912 var mapElem reflect.Value
913
914 // Parse function arguments.
915 for i := 0; ; i++ {
916 // closing ) - can only happen on first iteration.
917 op := d.scanWhile(scanSkipSpace)
918 if op == scanEndParams {
919 break
920 }
921
922 // Back up so d.value can have the byte we just read.
923 d.off--
924 d.scan.undo(op)
925
926 if i >= len(funcData.args) {
927 d.error(fmt.Errorf("json: too many arguments for function %s", funcName))
928 }
929 key := []byte(funcData.args[i])
930
931 // Figure out field corresponding to key.
932 var subv reflect.Value
933 destring := false // whether the value is wrapped in a string to be decoded first
934
935 if v.Kind() == reflect.Map {
936 elemType := v.Type().Elem()
937 if !mapElem.IsValid() {
938 mapElem = reflect.New(elemType).Elem()
939 } else {
940 mapElem.Set(reflect.Zero(elemType))
941 }
942 subv = mapElem
943 } else {
944 var f *field
945 fields := cachedTypeFields(v.Type())
946 for i := range fields {
947 ff := &fields[i]
948 if bytes.Equal(ff.nameBytes, key) {
949 f = ff
950 break
951 }
952 if f == nil && ff.equalFold(ff.nameBytes, key) {
953 f = ff
954 }
955 }
956 if f != nil {
957 subv = v
958 destring = f.quoted
959 for _, i := range f.index {
960 if subv.Kind() == reflect.Ptr {
961 if subv.IsNil() {
962 subv.Set(reflect.New(subv.Type().Elem()))
963 }
964 subv = subv.Elem()
965 }
966 subv = subv.Field(i)
967 }
968 }
969 }
970
971 // Read value.
972 if destring {
973 switch qv := d.valueQuoted().(type) {
974 case nil:
975 d.literalStore(nullLiteral, subv, false)
976 case string:
977 d.literalStore([]byte(qv), subv, true)
978 default:
979 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal unquoted value into %v", subv.Type()))
980 }
981 } else {
982 d.value(subv)
983 }
984
985 // Write value back to map;
986 // if using struct, subv points into struct already.
987 if v.Kind() == reflect.Map {
988 kt := v.Type().Key()
989 var kv reflect.Value
990 switch {
991 case kt.Kind() == reflect.String:
992 kv = reflect.ValueOf(key).Convert(v.Type().Key())
993 case reflect.PtrTo(kt).Implements(textUnmarshalerType):
994 kv = reflect.New(v.Type().Key())
995 d.literalStore(key, kv, true)
996 kv = kv.Elem()
997 default:
998 panic("json: Unexpected key type") // should never occur
999 }
1000 v.SetMapIndex(kv, subv)
1001 }
1002
1003 // Next token must be , or ).
1004 op = d.scanWhile(scanSkipSpace)
1005 if op == scanEndParams {
1006 break
1007 }
1008 if op != scanParam {
1009 d.error(errPhase)
1010 }
1011 }
1012 }
1013
1014 // keyed attempts to decode an object or function using a keyed doc extension,
1015 // and returns the value and true on success, or nil and false otherwise.
1016 func (d *decodeState) keyed() (interface{}, bool) {
1017 if len(d.ext.keyed) == 0 {
1018 return nil, false
1019 }
1020
1021 unquote := false
1022
1023 // Look-ahead first key to check for a keyed document extension.
1024 d.nextscan.reset()
1025 var start, end int
1026 for i, c := range d.data[d.off-1:] {
1027 switch op := d.nextscan.step(&d.nextscan, c); op {
1028 case scanSkipSpace, scanContinue, scanBeginObject:
1029 continue
1030 case scanBeginLiteral, scanBeginName:
1031 unquote = op == scanBeginLiteral
1032 start = i
1033 continue
1034 }
1035 end = i
1036 break
1037 }
1038
1039 name := d.data[d.off-1+start : d.off-1+end]
1040
1041 var key []byte
1042 var ok bool
1043 if unquote {
1044 key, ok = unquoteBytes(name)
1045 if !ok {
1046 d.error(errPhase)
1047 }
1048 } else {
1049 funcData, ok := d.ext.funcs[string(name)]
1050 if !ok {
1051 return nil, false
1052 }
1053 key = []byte(funcData.key)
1054 }
1055
1056 decode, ok := d.ext.keyed[string(key)]
1057 if !ok {
1058 return nil, false
1059 }
1060
1061 d.off--
1062 out, err := decode(d.next())
1063 if err != nil {
1064 d.error(err)
1065 }
1066 return out, true
1067 }
1068
1069 func (d *decodeState) storeKeyed(v reflect.Value) bool {
1070 keyed, ok := d.keyed()
1071 if !ok {
1072 return false
1073 }
1074 d.storeValue(v, keyed)
1075 return true
1076 }
1077
1078 var (
1079 trueBytes = []byte("true")
1080 falseBytes = []byte("false")
1081 nullBytes = []byte("null")
1082 )
1083
1084 func (d *decodeState) storeValue(v reflect.Value, from interface{}) {
1085 switch from {
1086 case nil:
1087 d.literalStore(nullBytes, v, false)
1088 return
1089 case true:
1090 d.literalStore(trueBytes, v, false)
1091 return
1092 case false:
1093 d.literalStore(falseBytes, v, false)
1094 return
1095 }
1096 fromv := reflect.ValueOf(from)
1097 for fromv.Kind() == reflect.Ptr && !fromv.IsNil() {
1098 fromv = fromv.Elem()
1099 }
1100 fromt := fromv.Type()
1101 for v.Kind() == reflect.Ptr && !v.IsNil() {
1102 v = v.Elem()
1103 }
1104 vt := v.Type()
1105 if fromt.AssignableTo(vt) {
1106 v.Set(fromv)
1107 } else if fromt.ConvertibleTo(vt) {
1108 v.Set(fromv.Convert(vt))
1109 } else {
1110 d.saveError(&UnmarshalTypeError{"object", v.Type(), int64(d.off)})
1111 }
1112 }
1113
1114 func (d *decodeState) convertLiteral(name []byte) (interface{}, bool) {
1115 if len(name) == 0 {
1116 return nil, false
1117 }
1118 switch name[0] {
1119 case 't':
1120 if bytes.Equal(name, trueBytes) {
1121 return true, true
1122 }
1123 case 'f':
1124 if bytes.Equal(name, falseBytes) {
1125 return false, true
1126 }
1127 case 'n':
1128 if bytes.Equal(name, nullBytes) {
1129 return nil, true
1130 }
1131 }
1132 if l, ok := d.ext.consts[string(name)]; ok {
1133 return l, true
1134 }
1135 return nil, false
1136 }
1137
1138 // literal consumes a literal from d.data[d.off-1:], decoding into the value v.
1139 // The first byte of the literal has been read already
1140 // (that's how the caller knows it's a literal).
1141 func (d *decodeState) literal(v reflect.Value) {
1142 // All bytes inside literal return scanContinue op code.
1143 start := d.off - 1
1144 op := d.scanWhile(scanContinue)
1145
1146 // Scan read one byte too far; back up.
1147 d.off--
1148 d.scan.undo(op)
1149
1150 d.literalStore(d.data[start:d.off], v, false)
1151 }
1152
1153 // convertNumber converts the number literal s to a float64 or a Number
1154 // depending on the setting of d.useNumber.
1155 func (d *decodeState) convertNumber(s string) (interface{}, error) {
1156 if d.useNumber {
1157 return Number(s), nil
1158 }
1159 f, err := strconv.ParseFloat(s, 64)
1160 if err != nil {
1161 return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.off)}
1162 }
1163 return f, nil
1164 }
1165
1166 var numberType = reflect.TypeOf(Number(""))
1167
1168 // literalStore decodes a literal stored in item into v.
1169 //
1170 // fromQuoted indicates whether this literal came from unwrapping a
1171 // string from the ",string" struct tag option. this is used only to
1172 // produce more helpful error messages.
1173 func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) {
1174 // Check for unmarshaler.
1175 if len(item) == 0 {
1176 //Empty string given
1177 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1178 return
1179 }
1180 wantptr := item[0] == 'n' // null
1181 u, ut, pv := d.indirect(v, wantptr)
1182 if u != nil {
1183 err := u.UnmarshalJSON(item)
1184 if err != nil {
1185 d.error(err)
1186 }
1187 return
1188 }
1189 if ut != nil {
1190 if item[0] != '"' {
1191 if fromQuoted {
1192 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1193 } else {
1194 d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
1195 }
1196 return
1197 }
1198 s, ok := unquoteBytes(item)
1199 if !ok {
1200 if fromQuoted {
1201 d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1202 } else {
1203 d.error(errPhase)
1204 }
1205 }
1206 err := ut.UnmarshalText(s)
1207 if err != nil {
1208 d.error(err)
1209 }
1210 return
1211 }
1212
1213 v = pv
1214
1215 switch c := item[0]; c {
1216 case 'n': // null
1217 switch v.Kind() {
1218 case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice:
1219 v.Set(reflect.Zero(v.Type()))
1220 // otherwise, ignore null for primitives/string
1221 }
1222 case 't', 'f': // true, false
1223 value := c == 't'
1224 switch v.Kind() {
1225 default:
1226 if fromQuoted {
1227 d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1228 } else {
1229 d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)})
1230 }
1231 case reflect.Bool:
1232 v.SetBool(value)
1233 case reflect.Interface:
1234 if v.NumMethod() == 0 {
1235 v.Set(reflect.ValueOf(value))
1236 } else {
1237 d.saveError(&UnmarshalTypeError{"bool", v.Type(), int64(d.off)})
1238 }
1239 }
1240
1241 case '"': // string
1242 s, ok := unquoteBytes(item)
1243 if !ok {
1244 if fromQuoted {
1245 d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1246 } else {
1247 d.error(errPhase)
1248 }
1249 }
1250 switch v.Kind() {
1251 default:
1252 d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
1253 case reflect.Slice:
1254 if v.Type().Elem().Kind() != reflect.Uint8 {
1255 d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
1256 break
1257 }
1258 b := make([]byte, base64.StdEncoding.DecodedLen(len(s)))
1259 n, err := base64.StdEncoding.Decode(b, s)
1260 if err != nil {
1261 d.saveError(err)
1262 break
1263 }
1264 v.SetBytes(b[:n])
1265 case reflect.String:
1266 v.SetString(string(s))
1267 case reflect.Interface:
1268 if v.NumMethod() == 0 {
1269 v.Set(reflect.ValueOf(string(s)))
1270 } else {
1271 d.saveError(&UnmarshalTypeError{"string", v.Type(), int64(d.off)})
1272 }
1273 }
1274
1275 default: // number
1276 if c != '-' && (c < '0' || c > '9') {
1277 if fromQuoted {
1278 d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1279 } else {
1280 d.error(errPhase)
1281 }
1282 }
1283 s := string(item)
1284 switch v.Kind() {
1285 default:
1286 if v.Kind() == reflect.String && v.Type() == numberType {
1287 v.SetString(s)
1288 if !isValidNumber(s) {
1289 d.error(fmt.Errorf("json: invalid number literal, trying to unmarshal %q into Number", item))
1290 }
1291 break
1292 }
1293 if fromQuoted {
1294 d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type()))
1295 } else {
1296 d.error(&UnmarshalTypeError{"number", v.Type(), int64(d.off)})
1297 }
1298 case reflect.Interface:
1299 n, err := d.convertNumber(s)
1300 if err != nil {
1301 d.saveError(err)
1302 break
1303 }
1304 if v.NumMethod() != 0 {
1305 d.saveError(&UnmarshalTypeError{"number", v.Type(), int64(d.off)})
1306 break
1307 }
1308 v.Set(reflect.ValueOf(n))
1309
1310 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
1311 n, err := strconv.ParseInt(s, 10, 64)
1312 if err != nil || v.OverflowInt(n) {
1313 d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)})
1314 break
1315 }
1316 v.SetInt(n)
1317
1318 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
1319 n, err := strconv.ParseUint(s, 10, 64)
1320 if err != nil || v.OverflowUint(n) {
1321 d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)})
1322 break
1323 }
1324 v.SetUint(n)
1325
1326 case reflect.Float32, reflect.Float64:
1327 n, err := strconv.ParseFloat(s, v.Type().Bits())
1328 if err != nil || v.OverflowFloat(n) {
1329 d.saveError(&UnmarshalTypeError{"number " + s, v.Type(), int64(d.off)})
1330 break
1331 }
1332 v.SetFloat(n)
1333 }
1334 }
1335 }
1336
1337 // The xxxInterface routines build up a value to be stored
1338 // in an empty interface. They are not strictly necessary,
1339 // but they avoid the weight of reflection in this common case.
1340
1341 // valueInterface is like value but returns interface{}
1342 func (d *decodeState) valueInterface() interface{} {
1343 switch d.scanWhile(scanSkipSpace) {
1344 default:
1345 d.error(errPhase)
1346 panic("unreachable")
1347 case scanBeginArray:
1348 return d.arrayInterface()
1349 case scanBeginObject:
1350 return d.objectInterface()
1351 case scanBeginLiteral:
1352 return d.literalInterface()
1353 case scanBeginName:
1354 return d.nameInterface()
1355 }
1356 }
1357
1358 func (d *decodeState) syntaxError(expected string) {
1359 msg := fmt.Sprintf("invalid character '%c' looking for %s", d.data[d.off-1], expected)
1360 d.error(&SyntaxError{msg, int64(d.off)})
1361 }
1362
1363 // arrayInterface is like array but returns []interface{}.
1364 func (d *decodeState) arrayInterface() []interface{} {
1365 var v = make([]interface{}, 0)
1366 for {
1367 // Look ahead for ] - can only happen on first iteration.
1368 op := d.scanWhile(scanSkipSpace)
1369 if op == scanEndArray {
1370 if len(v) > 0 && !d.ext.trailingCommas {
1371 d.syntaxError("beginning of value")
1372 }
1373 break
1374 }
1375
1376 // Back up so d.value can have the byte we just read.
1377 d.off--
1378 d.scan.undo(op)
1379
1380 v = append(v, d.valueInterface())
1381
1382 // Next token must be , or ].
1383 op = d.scanWhile(scanSkipSpace)
1384 if op == scanEndArray {
1385 break
1386 }
1387 if op != scanArrayValue {
1388 d.error(errPhase)
1389 }
1390 }
1391 return v
1392 }
1393
1394 // objectInterface is like object but returns map[string]interface{}.
1395 func (d *decodeState) objectInterface() interface{} {
1396 v, ok := d.keyed()
1397 if ok {
1398 return v
1399 }
1400
1401 m := make(map[string]interface{})
1402 for {
1403 // Read opening " of string key or closing }.
1404 op := d.scanWhile(scanSkipSpace)
1405 if op == scanEndObject {
1406 if len(m) > 0 && !d.ext.trailingCommas {
1407 d.syntaxError("beginning of object key string")
1408 }
1409 break
1410 }
1411 if op == scanBeginName {
1412 if !d.ext.unquotedKeys {
1413 d.syntaxError("beginning of object key string")
1414 }
1415 } else if op != scanBeginLiteral {
1416 d.error(errPhase)
1417 }
1418 unquotedKey := op == scanBeginName
1419
1420 // Read string key.
1421 start := d.off - 1
1422 op = d.scanWhile(scanContinue)
1423 item := d.data[start : d.off-1]
1424 var key string
1425 if unquotedKey {
1426 key = string(item)
1427 } else {
1428 var ok bool
1429 key, ok = unquote(item)
1430 if !ok {
1431 d.error(errPhase)
1432 }
1433 }
1434
1435 // Read : before value.
1436 if op == scanSkipSpace {
1437 op = d.scanWhile(scanSkipSpace)
1438 }
1439 if op != scanObjectKey {
1440 d.error(errPhase)
1441 }
1442
1443 // Read value.
1444 m[key] = d.valueInterface()
1445
1446 // Next token must be , or }.
1447 op = d.scanWhile(scanSkipSpace)
1448 if op == scanEndObject {
1449 break
1450 }
1451 if op != scanObjectValue {
1452 d.error(errPhase)
1453 }
1454 }
1455 return m
1456 }
1457
1458 // literalInterface is like literal but returns an interface value.
1459 func (d *decodeState) literalInterface() interface{} {
1460 // All bytes inside literal return scanContinue op code.
1461 start := d.off - 1
1462 op := d.scanWhile(scanContinue)
1463
1464 // Scan read one byte too far; back up.
1465 d.off--
1466 d.scan.undo(op)
1467 item := d.data[start:d.off]
1468
1469 switch c := item[0]; c {
1470 case 'n': // null
1471 return nil
1472
1473 case 't', 'f': // true, false
1474 return c == 't'
1475
1476 case '"': // string
1477 s, ok := unquote(item)
1478 if !ok {
1479 d.error(errPhase)
1480 }
1481 return s
1482
1483 default: // number
1484 if c != '-' && (c < '0' || c > '9') {
1485 d.error(errPhase)
1486 }
1487 n, err := d.convertNumber(string(item))
1488 if err != nil {
1489 d.saveError(err)
1490 }
1491 return n
1492 }
1493 }
1494
1495 // nameInterface is like function but returns map[string]interface{}.
1496 func (d *decodeState) nameInterface() interface{} {
1497 v, ok := d.keyed()
1498 if ok {
1499 return v
1500 }
1501
1502 nameStart := d.off - 1
1503
1504 op := d.scanWhile(scanContinue)
1505
1506 name := d.data[nameStart : d.off-1]
1507 if op != scanParam {
1508 // Back up so the byte just read is consumed next.
1509 d.off--
1510 d.scan.undo(op)
1511 if l, ok := d.convertLiteral(name); ok {
1512 return l
1513 }
1514 d.error(&SyntaxError{fmt.Sprintf("json: unknown constant %q", name), int64(d.off)})
1515 }
1516
1517 funcName := string(name)
1518 funcData := d.ext.funcs[funcName]
1519 if funcData.key == "" {
1520 d.error(fmt.Errorf("json: unknown function %q", funcName))
1521 }
1522
1523 m := make(map[string]interface{})
1524 for i := 0; ; i++ {
1525 // Look ahead for ) - can only happen on first iteration.
1526 op := d.scanWhile(scanSkipSpace)
1527 if op == scanEndParams {
1528 break
1529 }
1530
1531 // Back up so d.value can have the byte we just read.
1532 d.off--
1533 d.scan.undo(op)
1534
1535 if i >= len(funcData.args) {
1536 d.error(fmt.Errorf("json: too many arguments for function %s", funcName))
1537 }
1538 m[funcData.args[i]] = d.valueInterface()
1539
1540 // Next token must be , or ).
1541 op = d.scanWhile(scanSkipSpace)
1542 if op == scanEndParams {
1543 break
1544 }
1545 if op != scanParam {
1546 d.error(errPhase)
1547 }
1548 }
1549 return map[string]interface{}{funcData.key: m}
1550 }
1551
1552 // getu4 decodes \uXXXX from the beginning of s, returning the hex value,
1553 // or it returns -1.
1554 func getu4(s []byte) rune {
1555 if len(s) < 6 || s[0] != '\\' || s[1] != 'u' {
1556 return -1
1557 }
1558 r, err := strconv.ParseUint(string(s[2:6]), 16, 64)
1559 if err != nil {
1560 return -1
1561 }
1562 return rune(r)
1563 }
1564
1565 // unquote converts a quoted JSON string literal s into an actual string t.
1566 // The rules are different than for Go, so cannot use strconv.Unquote.
1567 func unquote(s []byte) (t string, ok bool) {
1568 s, ok = unquoteBytes(s)
1569 t = string(s)
1570 return
1571 }
1572
1573 func unquoteBytes(s []byte) (t []byte, ok bool) {
1574 if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
1575 return
1576 }
1577 s = s[1 : len(s)-1]
1578
1579 // Check for unusual characters. If there are none,
1580 // then no unquoting is needed, so return a slice of the
1581 // original bytes.
1582 r := 0
1583 for r < len(s) {
1584 c := s[r]
1585 if c == '\\' || c == '"' || c < ' ' {
1586 break
1587 }
1588 if c < utf8.RuneSelf {
1589 r++
1590 continue
1591 }
1592 rr, size := utf8.DecodeRune(s[r:])
1593 if rr == utf8.RuneError && size == 1 {
1594 break
1595 }
1596 r += size
1597 }
1598 if r == len(s) {
1599 return s, true
1600 }
1601
1602 b := make([]byte, len(s)+2*utf8.UTFMax)
1603 w := copy(b, s[0:r])
1604 for r < len(s) {
1605 // Out of room? Can only happen if s is full of
1606 // malformed UTF-8 and we're replacing each
1607 // byte with RuneError.
1608 if w >= len(b)-2*utf8.UTFMax {
1609 nb := make([]byte, (len(b)+utf8.UTFMax)*2)
1610 copy(nb, b[0:w])
1611 b = nb
1612 }
1613 switch c := s[r]; {
1614 case c == '\\':
1615 r++
1616 if r >= len(s) {
1617 return
1618 }
1619 switch s[r] {
1620 default:
1621 return
1622 case '"', '\\', '/', '\'':
1623 b[w] = s[r]
1624 r++
1625 w++
1626 case 'b':
1627 b[w] = '\b'
1628 r++
1629 w++
1630 case 'f':
1631 b[w] = '\f'
1632 r++
1633 w++
1634 case 'n':
1635 b[w] = '\n'
1636 r++
1637 w++
1638 case 'r':
1639 b[w] = '\r'
1640 r++
1641 w++
1642 case 't':
1643 b[w] = '\t'
1644 r++
1645 w++
1646 case 'u':
1647 r--
1648 rr := getu4(s[r:])
1649 if rr < 0 {
1650 return
1651 }
1652 r += 6
1653 if utf16.IsSurrogate(rr) {
1654 rr1 := getu4(s[r:])
1655 if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar {
1656 // A valid pair; consume.
1657 r += 6
1658 w += utf8.EncodeRune(b[w:], dec)
1659 break
1660 }
1661 // Invalid surrogate; fall back to replacement rune.
1662 rr = unicode.ReplacementChar
1663 }
1664 w += utf8.EncodeRune(b[w:], rr)
1665 }
1666
1667 // Quote, control characters are invalid.
1668 case c == '"', c < ' ':
1669 return
1670
1671 // ASCII
1672 case c < utf8.RuneSelf:
1673 b[w] = c
1674 r++
1675 w++
1676
1677 // Coerce to well-formed UTF-8.
1678 default:
1679 rr, size := utf8.DecodeRune(s[r:])
1680 r += size
1681 w += utf8.EncodeRune(b[w:], rr)
1682 }
1683 }
1684 return b[0:w], true
1685 }