]> Cypherpunks repositories - gostls13.git/commitdiff
bytes: fix panic in bytes.Buffer.Peek
authorAaron Chen <aaronchen.lisp@gmail.com>
Thu, 13 Nov 2025 01:43:03 +0000 (01:43 +0000)
committerGopher Robot <gobot@golang.org>
Fri, 14 Nov 2025 19:01:17 +0000 (11:01 -0800)
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: fb97ebc3b188959835706626f66898d6306c16fb
GitHub-Pull-Request: golang/go#76165
Reviewed-on: https://go-review.googlesource.com/c/go/+/717640
Reviewed-by: Michael Pratt <mpratt@google.com>
Auto-Submit: Michael Pratt <mpratt@google.com>
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Junyang Shao <shaojunyang@google.com>
src/bytes/buffer.go
src/bytes/buffer_test.go

index 3eb5b350c382c6049627251984cae0856dc15f7b..6cb4d6a8f66ebf556eb4543f495ec8d537889fd9 100644 (file)
@@ -86,7 +86,7 @@ func (b *Buffer) Peek(n int) ([]byte, error) {
        if b.Len() < n {
                return b.buf[b.off:], io.EOF
        }
-       return b.buf[b.off:n], nil
+       return b.buf[b.off : b.off+n], nil
 }
 
 // empty reports whether the unread portion of the buffer is empty.
index 5f5cc483b03f2dc17095d64a7114a03833feb4bc..9c1ba0a838054f38d7d68890312843af7daf594d 100644 (file)
@@ -533,19 +533,25 @@ func TestReadString(t *testing.T) {
 
 var peekTests = []struct {
        buffer   string
+       skip     int
        n        int
        expected string
        err      error
 }{
-       {"", 0, "", nil},
-       {"aaa", 3, "aaa", nil},
-       {"foobar", 2, "fo", nil},
-       {"a", 2, "a", io.EOF},
+       {"", 0, 0, "", nil},
+       {"aaa", 0, 3, "aaa", nil},
+       {"foobar", 0, 2, "fo", nil},
+       {"a", 0, 2, "a", io.EOF},
+       {"helloworld", 4, 3, "owo", nil},
+       {"helloworld", 5, 5, "world", nil},
+       {"helloworld", 5, 6, "world", io.EOF},
+       {"helloworld", 10, 1, "", io.EOF},
 }
 
 func TestPeek(t *testing.T) {
        for _, test := range peekTests {
                buf := NewBufferString(test.buffer)
+               buf.Next(test.skip)
                bytes, err := buf.Peek(test.n)
                if string(bytes) != test.expected {
                        t.Errorf("expected %q, got %q", test.expected, bytes)
@@ -553,8 +559,8 @@ func TestPeek(t *testing.T) {
                if err != test.err {
                        t.Errorf("expected error %v, got %v", test.err, err)
                }
-               if buf.Len() != len(test.buffer) {
-                       t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer))
+               if buf.Len() != len(test.buffer)-test.skip {
+                       t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer)-test.skip)
                }
        }
 }