ModuloReader: handle zero reads from inner reader

This commit is contained in:
Rob Watson 2021-11-17 08:22:15 +01:00
parent 47e3e47216
commit 8794b42459
2 changed files with 21 additions and 1 deletions

View File

@ -522,6 +522,15 @@ func (r *ModuloBufReader) Read(p []byte) (int, error) {
nr := nr1 + nr2
rem := nr % r.modSize
// if there was an error, return immediately.
if err == io.EOF {
return nr, err
} else if err != nil {
return nr - rem, err
}
// write any remainder to the buffer
if rem != 0 {
// err is always nil
_, _ = r.buf.Write(p[nr-rem : nr])

View File

@ -27,9 +27,10 @@ func TestModuloBufReader(t *testing.T) {
data: [][]byte{
{'a', 'b', 'c', 'd'},
{'e', 'f', 'g', 'h', 'i'},
{},
{'j', 'k', 'l', 'm'},
{'n', 'o', 'p'},
{'q', 'r', 's', 't'},
{'q', 'r', 's', 't', 'u'},
},
}
@ -47,6 +48,11 @@ func TestModuloBufReader(t *testing.T) {
assert.Equal(t, 4, n)
assert.Equal(t, []byte{'e', 'f', 'g', 'h'}, out[:n])
n, err = modReader.Read(out)
assert.NoError(t, err)
assert.Zero(t, n)
assert.Empty(t, out[:n])
n, err = modReader.Read(out)
assert.NoError(t, err)
assert.NoError(t, err)
@ -63,6 +69,11 @@ func TestModuloBufReader(t *testing.T) {
assert.Equal(t, 4, n)
assert.Equal(t, []byte{'q', 'r', 's', 't'}, out[:n])
n, err = modReader.Read(out)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 1, n)
assert.Equal(t, []byte{'u'}, out[:n])
n, err = modReader.Read(out)
assert.Zero(t, n)
assert.Equal(t, io.EOF, err)