Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug: *mem.File violates io.ReaderAt contract #352

Open
bfreis opened this issue May 10, 2022 · 0 comments · May be fixed by #353
Open

bug: *mem.File violates io.ReaderAt contract #352

bfreis opened this issue May 10, 2022 · 0 comments · May be fixed by #353

Comments

@bfreis
Copy link

bfreis commented May 10, 2022

The current implementation of *mem.File violates the contract defined by the Standard Library's io.ReaderAt interface.

Specifically, according to the docs for io.ReaderAt:

When ReadAt returns n < len(p), it returns a non-nil error explaining why more bytes were not returned. In this respect, ReadAt is stricter than Read.

The current implementation simply delegates ReadAt to Read:

afero/mem/file.go

Lines 208 to 214 in 100c9a6

func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
prev := atomic.LoadInt64(&f.at)
atomic.StoreInt64(&f.at, off)
n, err = f.Read(b)
atomic.StoreInt64(&f.at, prev)
return
}

This causes ReadAt to return a nil error when ReadAt reads less than the length of the give []byte, while the contract requires it to return a non-nil error.

A secondary bug, consequence of the problem above, is that using the fstest.TestFS(...) func of the standard library fails if the tested files have any content. This happens because it delegates testing ReadAt of the given fs.FS of the test to iotest.TestReader(...), which, in turn, makes an assertion on the condition described above.

In practical terms, I found this issue when I introduced afero and specificaly the MemMapFs to make some assertions on code I was writing that's supposed to generate and write files, and used fstest.TestFS(...) to check for the presence of the expected files I expected my code to generate.

It's an easy fix. Will soon send a PR with tests for both *mem.File and NewIOFS (i.e., use MemMapFs), and the fix.

bfreis added a commit to bfreis/afero that referenced this issue May 10, 2022
Add tests:
- ``*mem.File` implementation of `io.ReaderAt` must return non-nil error when reading less than length of give slice.
- `MemMapFs` must pass `fstest.TestFS` tests for non-empty files.

Fixes the bug.
@bfreis bfreis linked a pull request May 10, 2022 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant