Skip to content

Commit

Permalink
Fix peeker.Reader.Peek and Read panic on negative length (#4848)
Browse files Browse the repository at this point in the history
Peek and Read panics if their length parameter is negative.  Return an
error instead.

Closes #4844.
  • Loading branch information
nwt authored Nov 3, 2023
1 parent fe4487d commit 41b965c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pkg/peeker/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ func (r *Reader) fill(need int) error {
}

func (r *Reader) Peek(n int) ([]byte, error) {
if n < 0 {
return nil, errors.New("peeker: negative length")
}
if len(r.cursor) == 0 && r.eof {
return nil, io.EOF
}
Expand Down
8 changes: 8 additions & 0 deletions pkg/peeker/reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,11 @@ func TestEOFOnEmptyFill(t *testing.T) {
assert.ErrorIs(t, err, io.EOF)
assert.Len(t, n, 0)
}

func TestNegativeLength(t *testing.T) {
p := NewReader(nil, 0, 0)
_, err := p.Read(-1)
assert.ErrorContains(t, err, "peeker: negative length")
_, err = p.Peek(-1)
assert.ErrorContains(t, err, "peeker: negative length")
}

0 comments on commit 41b965c

Please sign in to comment.