From 082a4a8a47d03c5fd246b4d079391bdb21f2c3ed Mon Sep 17 00:00:00 2001
From: Rob Pike <r@golang.org>
Date: Wed, 10 Apr 2013 20:58:19 -0700
Subject: [PATCH] bufio/Scan: fix error handling at EOF Fixes #5268.

R=golang-dev, dsymonds, bradfitz
CC=golang-dev
https://golang.org/cl/8646045
---
 src/pkg/bufio/scan.go      |  5 +++--
 src/pkg/bufio/scan_test.go | 18 ++++++++++++++++++
 2 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/src/pkg/bufio/scan.go b/src/pkg/bufio/scan.go
index 486853e6bc..cebe92d331 100644
--- a/src/pkg/bufio/scan.go
+++ b/src/pkg/bufio/scan.go
@@ -103,7 +103,8 @@ func (s *Scanner) Text() string {
 
 // Scan advances the Scanner to the next token, which will then be
 // available through the Bytes or Text method. It returns false when the
-// scan stops, either by reaching the end of the input or an error.
+// scan stops, either by reaching the end of the input, a zero-length
+// read from the input, or an error.
 // After Scan returns false, the Err method will return any error that
 // occurred during scanning, except that if it was io.EOF, Err
 // will return nil.
@@ -164,7 +165,7 @@ func (s *Scanner) Scan() bool {
 			s.setErr(err)
 		}
 		if n == 0 { // Don't loop forever if Reader doesn't deliver EOF.
-			s.err = io.EOF
+			s.setErr(io.EOF)
 		}
 		s.end += n
 	}
diff --git a/src/pkg/bufio/scan_test.go b/src/pkg/bufio/scan_test.go
index 48729aabb1..1b112f46da 100644
--- a/src/pkg/bufio/scan_test.go
+++ b/src/pkg/bufio/scan_test.go
@@ -368,3 +368,21 @@ func TestErrAtEOF(t *testing.T) {
 		t.Fatal("wrong error:", s.Err())
 	}
 }
+
+// Test for issue 5268.
+type alwaysError struct{}
+
+func (alwaysError) Read(p []byte) (int, error) {
+	return 0, io.ErrUnexpectedEOF
+}
+
+func TestNonEOFWithEmptyRead(t *testing.T) {
+	scanner := NewScanner(alwaysError{})
+	for scanner.Scan() {
+		t.Fatal("read should fail")
+	}
+	err := scanner.Err()
+	if err != io.ErrUnexpectedEOF {
+		t.Errorf("unexpected error: %v", err)
+	}
+}
-- 
2.30.9