Skip to content

Commit 3494d93

Browse files
committed
bytes: add Buffer.Peek
Fixes golang#73794
1 parent 99b724f commit 3494d93

File tree

4 files changed

+43
-0
lines changed

4 files changed

+43
-0
lines changed

api/next/73794.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pkg bytes, method (*Buffer) Peek(int) ([]uint8, error) #73794
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
The new [Buffer.Peek] method returns the next n bytes from the buffer without
2+
advancing it.

src/bytes/buffer.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,18 @@ func (b *Buffer) String() string {
7777
return string(b.buf[b.off:])
7878
}
7979

80+
// Peek returns the next n bytes without advancing the buffer.
81+
// If Peek returns fewer than n bytes, it also returns [io.EOF].
82+
// The slice is only valid until the next call to a read or write method.
83+
// The slice aliases the buffer content at least until the next buffer modification,
84+
// so immediate changes to the slice will affect the result of future reads.
85+
func (b *Buffer) Peek(n int) ([]byte, error) {
86+
if b.Len() < n {
87+
return b.buf[b.off:], io.EOF
88+
}
89+
return b.buf[b.off:n], nil
90+
}
91+
8092
// empty reports whether the unread portion of the buffer is empty.
8193
func (b *Buffer) empty() bool { return len(b.buf) <= b.off }
8294

src/bytes/buffer_test.go

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

534+
var peekTests = []struct {
535+
buffer string
536+
n int
537+
expected string
538+
err error
539+
}{
540+
{"", 0, "", nil},
541+
{"aaa", 3, "aaa", nil},
542+
{"foobar", 2, "fo", nil},
543+
{"a", 2, "a", io.EOF},
544+
}
545+
546+
func TestPeek(t *testing.T) {
547+
for _, test := range peekTests {
548+
buf := NewBufferString(test.buffer)
549+
bytes, err := buf.Peek(test.n)
550+
if string(bytes) != test.expected {
551+
t.Errorf("expected %q, got %q", test.expected, bytes)
552+
}
553+
if err != test.err {
554+
t.Errorf("expected error %v, got %v", test.err, err)
555+
}
556+
if buf.Len() != len(test.buffer) {
557+
t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer))
558+
}
559+
}
560+
}
561+
534562
func BenchmarkReadString(b *testing.B) {
535563
const n = 32 << 10
536564

0 commit comments

Comments
 (0)