Skip to content

Commit e51b19a

Browse files
mjgartonianlancetaylor
authored andcommitted
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. (This change was previoiusly merged and then reverted due concern about being too close to a release) Fixes #18556 Change-Id: I9027d75aa834d4b27703f37711ba25de04d89f3c GitHub-Last-Rev: 917ef1e GitHub-Pull-Request: #28768 Reviewed-on: https://go-review.googlesource.com/c/149297 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent 9d025bd commit e51b19a

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/bufio/bufio.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,9 @@ func (b *Reader) Peek(n int) ([]byte, error) {
128128
return nil, ErrNegativeCount
129129
}
130130

131+
b.lastByte = -1
132+
b.lastRuneSize = -1
133+
131134
for b.w-b.r < n && b.w-b.r < len(b.buf) && b.err == nil {
132135
b.fill() // b.w-b.r < len(b.buf) => buffer is not full
133136
}

src/bufio/bufio_test.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,24 @@ func TestUnreadRune(t *testing.T) {
285285
}
286286
}
287287

288+
func TestNoUnreadRuneAfterPeek(t *testing.T) {
289+
br := NewReader(strings.NewReader("example"))
290+
br.ReadRune()
291+
br.Peek(1)
292+
if err := br.UnreadRune(); err == nil {
293+
t.Error("UnreadRune didn't fail after Peek")
294+
}
295+
}
296+
297+
func TestNoUnreadByteAfterPeek(t *testing.T) {
298+
br := NewReader(strings.NewReader("example"))
299+
br.ReadByte()
300+
br.Peek(1)
301+
if err := br.UnreadByte(); err == nil {
302+
t.Error("UnreadByte didn't fail after Peek")
303+
}
304+
}
305+
288306
func TestUnreadByte(t *testing.T) {
289307
segments := []string{"Hello, ", "world"}
290308
r := NewReader(&StringReader{data: segments})

0 commit comments

Comments
 (0)