]> Cypherpunks repositories - gostls13.git/commitdiff
bytes.Buffer: read of 0 bytes at EOF shouldn't be an EOF
authorRob Pike <r@golang.org>
Tue, 27 Dec 2011 07:49:24 +0000 (23:49 -0800)
committerRob Pike <r@golang.org>
Tue, 27 Dec 2011 07:49:24 +0000 (23:49 -0800)
This corner case arose doing an RPC with a empty-slice payload. Ouch.

R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/5505073

src/pkg/bytes/buffer.go
src/pkg/bytes/buffer_test.go

index e66ac026e5beb8232a71dae4c10d6077220dc74a..066023a3ec9ace12e9218f8d872317df4594e88d 100644 (file)
@@ -200,13 +200,16 @@ func (b *Buffer) WriteRune(r rune) (n int, err error) {
 
 // Read reads the next len(p) bytes from the buffer or until the buffer
 // is drained.  The return value n is the number of bytes read.  If the
-// buffer has no data to return, err is io.EOF even if len(p) is zero;
+// buffer has no data to return, err is io.EOF (unless len(p) is zero);
 // otherwise it is nil.
 func (b *Buffer) Read(p []byte) (n int, err error) {
        b.lastRead = opInvalid
        if b.off >= len(b.buf) {
                // Buffer is empty, reset to recover space.
                b.Truncate(0)
+               if len(p) == 0 {
+                       return
+               }
                return 0, io.EOF
        }
        n = copy(p, b.buf[b.off:])
index adb93302a541ebcea1cc9ea6b7f9df1e055e11cb..d0af11f104b9d1706a70121c2523bf946cf5ef22 100644 (file)
@@ -373,3 +373,16 @@ func TestReadBytes(t *testing.T) {
                }
        }
 }
+
+// Was a bug: used to give EOF reading empty slice at EOF.
+func TestReadEmptyAtEOF(t *testing.T) {
+       b := new(Buffer)
+       slice := make([]byte, 0)
+       n, err := b.Read(slice)
+       if err != nil {
+               t.Errorf("read error: %v", err)
+       }
+       if n != 0 {
+               t.Errorf("wrong count; got %d want 0", n)
+       }
+}