Skip to content

Commit 39609cc

Browse files
committed
memfs: return error when using negative offsets
same error as in go library: golang/go@a5999b7 Signed-off-by: Javi Fontan <[email protected]>
1 parent 40f7491 commit 39609cc

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

memfs/memory_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package memfs
22

33
import (
4+
"io"
45
"testing"
56

67
"gopkg.in/src-d/go-billy.v4"
@@ -29,3 +30,17 @@ func (s *MemorySuite) TestCapabilities(c *C) {
2930
caps := billy.Capabilities(s.FS)
3031
c.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability)
3132
}
33+
34+
func (s *MemorySuite) TestNegativeOffsets(c *C) {
35+
f, err := s.FS.Create("negative")
36+
c.Assert(err, IsNil)
37+
38+
buf := make([]byte, 100)
39+
_, err = f.ReadAt(buf, -100)
40+
c.Assert(err, ErrorMatches, "readat negative: negative offset")
41+
42+
_, err = f.Seek(-100, io.SeekCurrent)
43+
c.Assert(err, IsNil)
44+
_, err = f.Write(buf)
45+
c.Assert(err, ErrorMatches, "writeat negative: negative offset")
46+
}

memfs/storage.go

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package memfs
22

33
import (
4+
"errors"
45
"fmt"
56
"io"
67
"os"
@@ -36,9 +37,11 @@ func (s *storage) New(path string, mode os.FileMode, flag int) (*file, error) {
3637
return nil, nil
3738
}
3839

40+
name := filepath.Base(path)
41+
3942
f := &file{
40-
name: filepath.Base(path),
41-
content: &content{},
43+
name: name,
44+
content: &content{name: name},
4245
mode: mode,
4346
flag: flag,
4447
}
@@ -169,10 +172,19 @@ func clean(path string) string {
169172
}
170173

171174
type content struct {
175+
name string
172176
bytes []byte
173177
}
174178

175179
func (c *content) WriteAt(p []byte, off int64) (int, error) {
180+
if off < 0 {
181+
return 0, &os.PathError{
182+
Op: "writeat",
183+
Path: c.name,
184+
Err: errors.New("negative offset"),
185+
}
186+
}
187+
176188
prev := len(c.bytes)
177189

178190
diff := int(off) - prev
@@ -189,6 +201,14 @@ func (c *content) WriteAt(p []byte, off int64) (int, error) {
189201
}
190202

191203
func (c *content) ReadAt(b []byte, off int64) (n int, err error) {
204+
if off < 0 {
205+
return 0, &os.PathError{
206+
Op: "readat",
207+
Path: c.name,
208+
Err: errors.New("negative offset"),
209+
}
210+
}
211+
192212
size := int64(len(c.bytes))
193213
if off >= size {
194214
return 0, io.EOF

0 commit comments

Comments
 (0)