Skip to content

Commit a364508

Browse files
committed
bytes: add Buffer.Peek
Fixes #73794
1 parent c8bf388 commit a364508

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/bytes/buffer.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,16 @@ 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 there are fewer than n bytes in the buffer, it returns error [io.EOF].
82+
// The slice is only valid until the next buffer modification.
83+
func (b *Buffer) Peek(n int) ([]byte, error) {
84+
if b.Len() < n {
85+
return b.buf[b.off:], io.EOF
86+
}
87+
return b.buf[b.off:n], nil
88+
}
89+
8090
// empty reports whether the unread portion of the buffer is empty.
8191
func (b *Buffer) empty() bool { return len(b.buf) <= b.off }
8292

src/bytes/buffer_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -531,6 +531,31 @@ 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 rror %v, got %v", test.err, err)
555+
}
556+
}
557+
}
558+
534559
func BenchmarkReadString(b *testing.B) {
535560
const n = 32 << 10
536561

0 commit comments

Comments
 (0)