Skip to content

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

Open
@bfreis

Description

@bfreis

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions