Closed
Description
Today the Read
method of an io.Reader
is allowed to return 0, nil
. It is uncommon and discouraged:
Implementations of Read are discouraged from returning a zero byte
count with a nil error, except when len(p) == 0. Callers should treat a
return of 0 and nil as indicating that nothing happened; in particular
it does not indicate EOF.
It is so uncommon that it is hard to remember to deal with this case when using an io.Reader. All correct calls to Read
need to be wrapped in a loop that tries multiple times, and after some ill-defined cutoff, report an error like io.ErrNoProgress
. Consider the correct example of reading from bufio.Reader:
// Read new data: try a limited number of times.
for i := maxConsecutiveEmptyReads; i > 0; i-- {
n, err := b.rd.Read(b.buf[b.w:])
if n < 0 {
panic(errNegativeRead)
}
b.w += n
if err != nil {
b.err = err
return
}
if n > 0 {
return
}
}
b.err = io.ErrNoProgress
For Go 2 I propose we change the contract of io.Reader
so implementations are required to return either n > 0
or a non-nil error.