Skip to content

Commit

Permalink
Merge pull request #68 from jfontan/fix/memfs-negative-offsets
Browse files Browse the repository at this point in the history
memfs: return error when using negative offsets
  • Loading branch information
mcuadros authored Jun 30, 2019
2 parents 63e7cf0 + 39609cc commit 711f3aa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
15 changes: 15 additions & 0 deletions memfs/memory_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package memfs

import (
"io"
"testing"

"gopkg.in/src-d/go-billy.v4"
Expand Down Expand Up @@ -29,3 +30,17 @@ func (s *MemorySuite) TestCapabilities(c *C) {
caps := billy.Capabilities(s.FS)
c.Assert(caps, Equals, billy.DefaultCapabilities&^billy.LockCapability)
}

func (s *MemorySuite) TestNegativeOffsets(c *C) {
f, err := s.FS.Create("negative")
c.Assert(err, IsNil)

buf := make([]byte, 100)
_, err = f.ReadAt(buf, -100)
c.Assert(err, ErrorMatches, "readat negative: negative offset")

_, err = f.Seek(-100, io.SeekCurrent)
c.Assert(err, IsNil)
_, err = f.Write(buf)
c.Assert(err, ErrorMatches, "writeat negative: negative offset")
}
24 changes: 22 additions & 2 deletions memfs/storage.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package memfs

import (
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -36,9 +37,11 @@ func (s *storage) New(path string, mode os.FileMode, flag int) (*file, error) {
return nil, nil
}

name := filepath.Base(path)

f := &file{
name: filepath.Base(path),
content: &content{},
name: name,
content: &content{name: name},
mode: mode,
flag: flag,
}
Expand Down Expand Up @@ -169,10 +172,19 @@ func clean(path string) string {
}

type content struct {
name string
bytes []byte
}

func (c *content) WriteAt(p []byte, off int64) (int, error) {
if off < 0 {
return 0, &os.PathError{
Op: "writeat",
Path: c.name,
Err: errors.New("negative offset"),
}
}

prev := len(c.bytes)

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

func (c *content) ReadAt(b []byte, off int64) (n int, err error) {
if off < 0 {
return 0, &os.PathError{
Op: "readat",
Path: c.name,
Err: errors.New("negative offset"),
}
}

size := int64(len(c.bytes))
if off >= size {
return 0, io.EOF
Expand Down

0 comments on commit 711f3aa

Please sign in to comment.