Commit ae238688 authored by Martin Garton's avatar Martin Garton Committed by Robert Griesemer

bufio: make Reader.Peek invalidate Unreads

Since Reader.Peek potentially reads from the underlying io.Reader,
discarding previous buffers, UnreadRune and UnreadByte cannot
necessarily work.  Change Peek to invalidate the unread buffers in all
cases (as allowed according to the documentation) and thus prevent
hiding bugs in the caller.

Fixes #18556

Change-Id: I8d836db7ce31c4aaecb4f61c24573b0332bbf30d
Reviewed-on: https://go-review.googlesource.com/46850Reviewed-by: default avatarRobert Griesemer <gri@golang.org>
parent 81ed9ca1
...@@ -125,6 +125,9 @@ func (b *Reader) Peek(n int) ([]byte, error) { ...@@ -125,6 +125,9 @@ func (b *Reader) Peek(n int) ([]byte, error) {
return nil, ErrNegativeCount return nil, ErrNegativeCount
} }
b.lastByte = -1
b.lastRuneSize = -1
for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil { for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil {
b.fill() // b.w-b.r < len(b.buf) => buffer is not full b.fill() // b.w-b.r < len(b.buf) => buffer is not full
} }
......
...@@ -285,6 +285,24 @@ func TestUnreadRune(t *testing.T) { ...@@ -285,6 +285,24 @@ func TestUnreadRune(t *testing.T) {
} }
} }
func TestNoUnreadRuneAfterPeek(t *testing.T) {
br := NewReader(strings.NewReader("example"))
br.ReadRune()
br.Peek(1)
if err := br.UnreadRune(); err == nil {
t.Error("UnreadRune didn't fail after Peek")
}
}
func TestNoUnreadByteAfterPeek(t *testing.T) {
br := NewReader(strings.NewReader("example"))
br.ReadByte()
br.Peek(1)
if err := br.UnreadByte(); err == nil {
t.Error("UnreadByte didn't fail after Peek")
}
}
func TestUnreadByte(t *testing.T) { func TestUnreadByte(t *testing.T) {
segments := []string{"Hello, ", "world"} segments := []string{"Hello, ", "world"}
r := NewReader(&StringReader{data: segments}) r := NewReader(&StringReader{data: segments})
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment