-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader_seek.go
90 lines (72 loc) · 1.28 KB
/
reader_seek.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
82
83
84
85
86
87
88
89
90
package json
// Seek seeks to the beginning of the value at the path – list of object keys and array indexes.
// If you parse multiple object and you only need one value from each,
// it's good to use Break(len(path)) to move to the beginning of the next object.
func (r *Reader) Seek(path ...interface{}) (err error) {
for _, p := range path {
switch p := p.(type) {
case string:
err = r.seekObj(p)
case int:
err = r.seekArr(p)
}
if err != nil {
return err
}
}
return nil
}
func (r *Reader) seekObj(key string) (err error) {
err = r.Enter(Object)
if err != nil {
return
}
var k []byte
for err == nil && r.ForMore(Object, &err) {
k, err = r.Key()
if err != nil {
return
}
if string(k) == key {
_, err = r.Type()
return
}
err = r.Skip()
}
if err != nil {
return
}
return ErrNoSuchKey
}
func (r *Reader) seekArr(idx int) (err error) {
if idx < 0 {
r.Lock()
l, err := r.Length()
if err != nil {
return err
}
r.Rewind()
r.Unlock()
idx = l + idx
}
if idx < 0 {
return ErrOutOfBounds
}
err = r.Enter(Array)
if err != nil {
return
}
j := 0
for err == nil && r.ForMore(Array, &err) {
if j == idx {
_, err = r.Type()
return
}
err = r.Skip()
j++
}
if err != nil {
return
}
return ErrOutOfBounds
}