Merge pull request #287 from tdakkota/fix/issue-286

Fix incorrect (*mem.File).WriteAt
This commit is contained in:
Michail Kargakis 2021-03-20 15:22:17 +01:00 committed by GitHub
commit bc94f58bed
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 52 additions and 1 deletions

View File

@ -267,7 +267,7 @@ func (f *File) Write(b []byte) (n int, err error) {
tail = f.fileData.data[n+int(cur):]
}
if diff > 0 {
f.fileData.data = append(bytes.Repeat([]byte{00}, int(diff)), b...)
f.fileData.data = append(f.fileData.data, append(bytes.Repeat([]byte{00}, int(diff)), b...)...)
f.fileData.data = append(f.fileData.data, tail...)
} else {
f.fileData.data = append(f.fileData.data[:cur], b...)

View File

@ -95,6 +95,57 @@ func TestFileDataModeRace(t *testing.T) {
}
}
// See https://github.com/spf13/afero/issues/286.
func TestFileWriteAt(t *testing.T) {
t.Parallel()
data := CreateFile("abc.txt")
f := NewFileHandle(data)
testData := []byte{1, 2, 3, 4, 5}
offset := len(testData)
// 5 zeros + testdata
_, err := f.WriteAt(testData, int64(offset))
if err != nil {
t.Fatal(err)
}
// 2 * testdata
_, err = f.WriteAt(testData, 0)
if err != nil {
t.Fatal(err)
}
// 3 * testdata
_, err = f.WriteAt(testData, int64(offset*2))
if err != nil {
t.Fatal(err)
}
// 3 * testdata + 5 zeros + testdata
_, err = f.WriteAt(testData, int64(offset*4))
if err != nil {
t.Fatal(err)
}
// 5 * testdata
_, err = f.WriteAt(testData, int64(offset*3))
if err != nil {
t.Fatal(err)
}
err = f.Close()
if err != nil {
t.Fatal(err)
}
expected := bytes.Repeat(testData, 5)
if !bytes.Equal(expected, data.data) {
t.Fatalf("expected: %v, got: %v", expected, data.data)
}
}
func TestFileDataIsDirRace(t *testing.T) {
t.Parallel()