OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [encoding/] [json/] [decode.go] - Blame information for rev 750

Go to most recent revision | Details | Compare with Previous | View Log

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

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.