Skip to content

Commit 85a405f

Browse files
committed
memfs: Fix memory FS implementation bug
Now, using memory FS, is possible to seek outside the size of the file and write something, adding '0' between the old file content and the new one.
1 parent bf5cdf7 commit 85a405f

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

memfs/memory.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ func (f *file) Seek(offset int64, whence int) (int64, error) {
282282
case io.SeekStart:
283283
f.position = offset
284284
case io.SeekEnd:
285-
f.position = int64(f.content.Len()) - offset
285+
f.position = int64(f.content.Len()) + offset
286286
}
287287

288288
return f.position, nil
@@ -368,6 +368,12 @@ type content struct {
368368

369369
func (c *content) WriteAt(p []byte, off int64) (int, error) {
370370
prev := len(c.bytes)
371+
372+
diff := int(off) - prev
373+
if diff > 0 {
374+
c.bytes = append(c.bytes, make([]byte, diff)...)
375+
}
376+
371377
c.bytes = append(c.bytes[:off], p...)
372378
if len(c.bytes) < prev {
373379
c.bytes = c.bytes[:prev]

test/fs_suite.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,26 @@ func (s *FilesystemSuite) TestOpenFileReadWrite(c *C) {
142142
s.testReadClose(c, f, "quxbar")
143143
}
144144

145+
func (s *FilesystemSuite) TestSeekToEndAndWrite(c *C) {
146+
defaultMode := os.FileMode(0666)
147+
148+
f, err := s.FS.OpenFile("foo1", os.O_CREATE|os.O_TRUNC|os.O_RDWR, defaultMode)
149+
c.Assert(err, IsNil)
150+
c.Assert(f.Filename(), Equals, "foo1")
151+
152+
_, err = f.Seek(10, io.SeekEnd)
153+
c.Assert(err, IsNil)
154+
155+
n, err := f.Write([]byte(`TEST`))
156+
c.Assert(err, IsNil)
157+
c.Assert(n, Equals, 4)
158+
159+
_, err = f.Seek(0, io.SeekStart)
160+
c.Assert(err, IsNil)
161+
162+
s.testReadClose(c, f, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00TEST")
163+
}
164+
145165
func (s *FilesystemSuite) TestOpenFile(c *C) {
146166
defaultMode := os.FileMode(0666)
147167

0 commit comments

Comments
 (0)