Skip to content

Commit

Permalink
text/scanner: avoid further reads after EOF
Browse files Browse the repository at this point in the history
Fixes golang#10735.

Change-Id: I5c6e424653657c89da176136ac56597c7565abe5
Reviewed-on: https://go-review.googlesource.com/10039
Reviewed-by: Rob Pike <[email protected]>
  • Loading branch information
griesemer committed May 13, 2015
1 parent f8fbcef commit fd5b8aa
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 9 deletions.
6 changes: 5 additions & 1 deletion src/text/scanner/scanner.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,9 @@ func (s *Scanner) Next() rune {
s.tokPos = -1 // don't collect token text
s.Line = 0 // invalidate token position
ch := s.Peek()
s.ch = s.next()
if ch != EOF {
s.ch = s.next()
}
return ch
}

Expand Down Expand Up @@ -597,6 +599,8 @@ redo:
}
default:
switch ch {
case EOF:
break
case '"':
if s.Mode&ScanStrings != 0 {
s.scanString('"')
Expand Down
36 changes: 28 additions & 8 deletions src/text/scanner/scanner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -619,29 +619,49 @@ func TestPos(t *testing.T) {

type countReader int

func (c *countReader) Read([]byte) (int, error) {
*c++

func (r *countReader) Read([]byte) (int, error) {
*r++
return 0, io.EOF
}

func TestPeekEOFHandling(t *testing.T) {
func TestNextEOFHandling(t *testing.T) {
var r countReader

// corner case: empty source
s := new(Scanner).Init(&r)

tok := s.Next()
if tok != EOF {
t.Errorf("EOF not reported")
t.Error("1) EOF not reported")
}

tok = s.Peek()
if tok != EOF {
t.Error("2) EOF not reported")
}

if r != 1 {
t.Errorf("scanner called Read %d times, not once", r)
}
}

func TestScanEOFHandling(t *testing.T) {
var r countReader

// corner case: empty source
s := new(Scanner).Init(&r)

tok := s.Scan()
if tok != EOF {
t.Error("1) EOF not reported")
}

tok = s.Peek()
if tok != EOF {
t.Errorf("EOF not reported")
t.Error("2) EOF not reported")
}

if r != 2 {
t.Errorf("scanner called Read %d times, not twice", r)
if r != 1 {
t.Errorf("scanner called Read %d times, not once", r)
}
}

0 comments on commit fd5b8aa

Please sign in to comment.