Skip to content

Commit b57962b

Browse files
AaronChen0gopherbot
authored andcommitted
bytes: fix panic in bytes.Buffer.Peek
This change fixed the overlooked offset in bytes.Buffer.Peek. Otherwise, it will either return wrong result or panic with "runtime error: slice bounds out of range". Change-Id: Ic42fd8a27fb9703c51430f298933b91cf0d45451 GitHub-Last-Rev: fb97ebc GitHub-Pull-Request: #76165 Reviewed-on: https://go-review.googlesource.com/c/go/+/717640 Reviewed-by: Michael Pratt <[email protected]> Auto-Submit: Michael Pratt <[email protected]> LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Junyang Shao <[email protected]>
1 parent 0a56952 commit b57962b

File tree

2 files changed

+13
-7
lines changed

2 files changed

+13
-7
lines changed

src/bytes/buffer.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ func (b *Buffer) Peek(n int) ([]byte, error) {
8686
if b.Len() < n {
8787
return b.buf[b.off:], io.EOF
8888
}
89-
return b.buf[b.off:n], nil
89+
return b.buf[b.off : b.off+n], nil
9090
}
9191

9292
// empty reports whether the unread portion of the buffer is empty.

src/bytes/buffer_test.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -533,28 +533,34 @@ func TestReadString(t *testing.T) {
533533

534534
var peekTests = []struct {
535535
buffer string
536+
skip int
536537
n int
537538
expected string
538539
err error
539540
}{
540-
{"", 0, "", nil},
541-
{"aaa", 3, "aaa", nil},
542-
{"foobar", 2, "fo", nil},
543-
{"a", 2, "a", io.EOF},
541+
{"", 0, 0, "", nil},
542+
{"aaa", 0, 3, "aaa", nil},
543+
{"foobar", 0, 2, "fo", nil},
544+
{"a", 0, 2, "a", io.EOF},
545+
{"helloworld", 4, 3, "owo", nil},
546+
{"helloworld", 5, 5, "world", nil},
547+
{"helloworld", 5, 6, "world", io.EOF},
548+
{"helloworld", 10, 1, "", io.EOF},
544549
}
545550

546551
func TestPeek(t *testing.T) {
547552
for _, test := range peekTests {
548553
buf := NewBufferString(test.buffer)
554+
buf.Next(test.skip)
549555
bytes, err := buf.Peek(test.n)
550556
if string(bytes) != test.expected {
551557
t.Errorf("expected %q, got %q", test.expected, bytes)
552558
}
553559
if err != test.err {
554560
t.Errorf("expected error %v, got %v", test.err, err)
555561
}
556-
if buf.Len() != len(test.buffer) {
557-
t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer))
562+
if buf.Len() != len(test.buffer)-test.skip {
563+
t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer)-test.skip)
558564
}
559565
}
560566
}

0 commit comments

Comments
 (0)