Skip to content

bytes: add Buffer.Peek #73795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/bytes/buffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,16 @@ func (b *Buffer) String() string {
return string(b.buf[b.off:])
}

// Peek returns the next n bytes without advancing the buffer.
// If there are fewer than n bytes in the buffer, it returns error [io.EOF].
// The slice is only valid until the next buffer modification.
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
}

// empty reports whether the unread portion of the buffer is empty.
func (b *Buffer) empty() bool { return len(b.buf) <= b.off }

Expand Down
25 changes: 25 additions & 0 deletions src/bytes/buffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -531,6 +531,31 @@ func TestReadString(t *testing.T) {
}
}

var peekTests = []struct{
buffer string
n int
expected string
err error
}{
{"", 0, "", nil},
{"aaa", 3, "aaa", nil},
{"foobar", 2, "fo", nil},
{"a", 2, "a", io.EOF},
}

func TestPeek(t *testing.T) {
for _, test := range peekTests {
buf := NewBufferString(test.buffer)
bytes, err := buf.Peek(test.n)
if string(bytes) != test.expected {
t.Errorf("expected %q, got %q", test.expected, bytes)
}
if err != test.err {
t.Errorf("expected error %v, got %v", test.err, err)
}
}
}

func BenchmarkReadString(b *testing.B) {
const n = 32 << 10

Expand Down