return string(b.buf[b.off:])
}
+// Peek returns the next n bytes without advancing the buffer.
+// If Peek returns fewer than n bytes, it also returns [io.EOF].
+// The slice is only valid until the next call to a read or write method.
+// The slice aliases the buffer content at least until the next buffer modification,
+// so immediate changes to the slice will affect the result of future reads.
+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 }
}
}
+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)
+ }
+ if buf.Len() != len(test.buffer) {
+ t.Errorf("bad length after peek: %d, want %d", buf.Len(), len(test.buffer))
+ }
+ }
+}
+
func BenchmarkReadString(b *testing.B) {
const n = 32 << 10