Skip to content

Commit

Permalink
Added decoder input offset method
Browse files Browse the repository at this point in the history
This new method gives the location in the input stream of the most recently read byte.

Signed-off-by: Miguel Ángel Ortuño <[email protected]>
  • Loading branch information
ortuman authored and kaiburjack committed May 28, 2023
1 parent e6fb7e2 commit 5a12f17
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
7 changes: 7 additions & 0 deletions decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ type Decoder interface {
// and then only read/touch the fields relevant for that kind.
NextToken(t *Token) error

// InputOffset returns the current offset in the input stream.
InputOffset() int

// Reset resets the Decoder to the given io.Reader.
Reset(r io.Reader)
}
Expand Down Expand Up @@ -101,6 +104,10 @@ func (thiz *decoder) discard(n int) (int, error) {
return n, nil
}

func (thiz *decoder) InputOffset() int {
return thiz.r
}

func (thiz *decoder) Reset(r io.Reader) {
thiz.rd = r
thiz.r = 0
Expand Down
23 changes: 23 additions & 0 deletions decoder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,29 @@ func TestIgnoreComments(t *testing.T) {
assert.Equal(t, io.EOF, err3)
}

func TestInputOffset(t *testing.T) {
// given
var tk gosaxml.Token

doc := "<a>Testing input offset</a>"
lastOffset := len(doc)

dec := gosaxml.NewDecoder(bufio.NewReaderSize(strings.NewReader(doc), 1024))

// when
_ = dec.NextToken(&tk)
off1 := dec.InputOffset()
_ = dec.NextToken(&tk)
off2 := dec.InputOffset()
_ = dec.NextToken(&tk)
off3 := dec.InputOffset()

// then
assert.Equal(t, 2, off1)
assert.Equal(t, 23, off2)
assert.Equal(t, lastOffset, off3)
}

func assertTextElement(t *testing.T, text string, token gosaxml.Token) {
assert.Equal(t, uint8(gosaxml.TokenTypeTextElement), token.Kind)
assert.Equal(t, []byte(text), token.ByteData)
Expand Down

0 comments on commit 5a12f17

Please sign in to comment.