Skip to content

Commit

Permalink
Allow empty SeekTo to seek to the end
Browse files Browse the repository at this point in the history
  • Loading branch information
peterwald committed Apr 7, 2021
1 parent e84ac1b commit 13a7a2a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 14 deletions.
13 changes: 6 additions & 7 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,16 +39,15 @@ func NewDecoder(r io.Reader) *Decoder {
// Decoder is intended to be used with a stream of tokens. As a result it navigates forward only.
func (d *Decoder) SeekTo(path ...interface{}) (bool, error) {

if len(path) == 0 {
return len(d.path) == 0, nil
}
last := len(path) - 1
if i, ok := path[last].(int); ok {
path[last] = i - 1
if len(path) > 0 {
last := len(path) - 1
if i, ok := path[last].(int); ok {
path[last] = i - 1
}
}

for {
if d.path.Equal(path) {
if len(path) == len(d.path) && d.path.Equal(path) {
return true, nil
}
_, err := d.Token()
Expand Down
19 changes: 12 additions & 7 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,32 @@ func ExampleDecoder_SeekTo() {
var j = []byte(`[
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
]`)
][]`)

w := NewDecoder(bytes.NewReader(j))
var v interface{}

w.SeekTo(0, "Space")
w.Decode(&v)
fmt.Println(0, "Space", v)
fmt.Printf("%v => %v\n", w.Path(), v)

w.SeekTo(0, "Point", "Cr")
w.Decode(&v)
fmt.Println(0, "Point", "Cr", v)
fmt.Printf("%v => %v\n", w.Path(), v)

w.SeekTo(1, "Point", "G")
w.Decode(&v)
fmt.Println(1, "Point", "G", v)
fmt.Printf("%v => %v\n", w.Path(), v)

// seek to the end of the object
w.SeekTo()
fmt.Printf("%v\n", w.Path())

// Output:
// 0 Space YCbCr
// 0 Point Cr -10
// 1 Point G 218
// [0 Space] => YCbCr
// [0 Point Cr] => -10
// [1 Point G] => 218
// []
}

func ExampleDecoder_Scan() {
Expand Down

0 comments on commit 13a7a2a

Please sign in to comment.