forked from go-faster/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dec_arr.go
81 lines (77 loc) · 1.56 KB
/
dec_arr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package jx
import (
"github.com/go-faster/errors"
)
// Elem skips to the start of next array element, returning true boolean
// if element exists.
//
// Can be called before or in Array.
func (d *Decoder) Elem() (ok bool, err error) {
c, err := d.next()
if err != nil {
return false, err
}
switch c {
case '[':
c, err := d.more()
if err != nil {
return false, err
}
if c != ']' {
d.unread()
return true, nil
}
return false, nil
case ']':
return false, nil
case ',':
return true, nil
default:
return false, errors.Wrap(badToken(c, d.offset()), `"[", "," or "]" expected`)
}
}
// Arr decodes array and invokes callback on each array element.
func (d *Decoder) Arr(f func(d *Decoder) error) error {
if err := d.consume('['); err != nil {
return errors.Wrap(err, `"[" expected`)
}
if f == nil {
return d.skipArr()
}
if err := d.incDepth(); err != nil {
return err
}
c, err := d.more()
if err != nil {
return errors.Wrap(err, `value or "]" expected`)
}
if c == ']' {
return d.decDepth()
}
d.unread()
if err := f(d); err != nil {
return errors.Wrap(err, "callback")
}
c, err = d.more()
if err != nil {
return errors.Wrap(err, `"," or "]" expected`)
}
for c == ',' {
// Skip whitespace before reading element.
if _, err := d.next(); err != nil {
return err
}
d.unread()
if err := f(d); err != nil {
return errors.Wrap(err, "callback")
}
if c, err = d.next(); err != nil {
return err
}
}
if c != ']' {
err := badToken(c, d.offset()-1)
return errors.Wrap(err, `"]" expected`)
}
return d.decDepth()
}