[bug] - Improve BufferedFileReader Close Behavior (#2768)

* Dont allow read after close

* update comment

* remove defer
This commit is contained in:
ahrav 2024-04-30 08:50:16 -07:00 committed by GitHub
parent 23b3ddde58
commit 88967192e8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 16 additions and 18 deletions

View file

@ -15,7 +15,6 @@ func TestBufferedFileReader(t *testing.T) {
bufferReadSeekCloser, err := NewBufferedFileReader(bytes.NewReader(data))
assert.NoError(t, err)
defer bufferReadSeekCloser.Close()
// Test Read.
buffer := make([]byte, len(data))
@ -53,25 +52,11 @@ func TestBufferedFileReaderClose(t *testing.T) {
err = bufferReadSeekCloser.Close()
assert.NoError(t, err)
// Read after closing.
// Read should NOT return any data after closing the reader.
buffer := make([]byte, len(data))
n, err := bufferReadSeekCloser.Read(buffer)
assert.NoError(t, err)
assert.Equal(t, len(data), n)
assert.Equal(t, data, buffer)
// Seek after closing.
offset := 7
seekPos, err := bufferReadSeekCloser.Seek(int64(offset), io.SeekStart)
assert.NoError(t, err)
assert.Equal(t, int64(offset), seekPos)
// ReadAt after closing.
buffer = make([]byte, len(data)-offset)
n, err = bufferReadSeekCloser.ReadAt(buffer, int64(offset))
assert.NoError(t, err)
assert.Equal(t, len(data)-offset, n)
assert.Equal(t, data[offset:], buffer)
assert.ErrorIs(t, err, io.EOF)
assert.Equal(t, 0, n)
}
func TestBufferedFileReaderReadFromFile(t *testing.T) {

View file

@ -166,5 +166,18 @@ func (brc *readCloser) Close() error {
}
brc.onClose() // Return the buffer to the pool
brc.Reader = nil
return nil
}
// Read reads up to len(p) bytes into p from the underlying reader.
// It returns the number of bytes read and any error encountered.
// On reaching the end of the available data, it returns 0 and io.EOF.
// Calling Read on a closed reader will also return 0 and io.EOF.
func (brc *readCloser) Read(p []byte) (int, error) {
if brc.Reader == nil {
return 0, io.EOF
}
return brc.Reader.Read(p)
}