Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add PeekByte and Next optimization #32

Merged
merged 1 commit into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,38 @@ func (r *Reader) Peek(n int) ([]byte, error) {
return r.data[r.n : r.n+n], nil
}

func (r *Reader) PeekByte() (b byte, err error) {
if len(r.data)-r.n >= 1 {
b = r.data[r.n]
} else {
b, err = r.peekByte()
}
return
}

func (r *Reader) peekByte() (byte, error) {
const n = 1
if cap(r.data) < n {
old := r.data[r.n:]
r.data = make([]byte, n+r.buffered())
r.data = r.data[:copy(r.data, old)]
r.n = 0
}

// keep filling until
// we hit an error or
// read enough bytes
for r.buffered() < n && r.state == nil {
r.more()
}

// we must have hit an error
if r.buffered() < n {
return 0, r.err()
}
return r.data[r.n], nil
}

// discard(n) discards up to 'n' buffered bytes, and
// and returns the number of bytes discarded
func (r *Reader) discard(n int) int {
Expand Down Expand Up @@ -256,7 +288,18 @@ func (r *Reader) Skip(n int) (int, error) {
// If an the returned slice is less than the
// length asked for, an error will be returned,
// and the reader position will not be incremented.
func (r *Reader) Next(n int) ([]byte, error) {
func (r *Reader) Next(n int) (b []byte, err error) {
if r.state == nil && len(r.data)-r.n >= n {
b = r.data[r.n : r.n+n]
r.n += n
r.inputOffset += int64(n)
} else {
b, err = r.next(n)
}
return
}

func (r *Reader) next(n int) ([]byte, error) {
// in case the buffer is too small
if cap(r.data) < n {
old := r.data[r.n:]
Expand Down
29 changes: 29 additions & 0 deletions reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,35 @@ func TestPeek(t *testing.T) {
}
}

func TestPeekByte(t *testing.T) {
bts := randomBts(1024)
rd := NewReaderSize(partialReader{bytes.NewReader(bts)}, 200)

// first, a peek < buffer size
var (
peek byte
err error
)
rd.Skip(100)
peek, err = rd.PeekByte()
if err != nil {
t.Fatal(err)
}
if peek != bts[100] {
t.Fatalf("peeked byte not equal: want %d got %d", bts[100], peek)
}

// now, a peek > buffer size
rd.Skip(156)
peek, err = rd.PeekByte()
if err != nil {
t.Fatal(err)
}
if peek != bts[256] {
t.Fatalf("peeked byte not equal: want %d got %d", bts[256], peek)
}
}

func TestNext(t *testing.T) {
size := 1024
bts := randomBts(size)
Expand Down