Skip to content
This repository was archived by the owner on Sep 11, 2020. It is now read-only.

Commit 3e7f535

Browse files
smolamcuadros
authored andcommitted
utils/fs: add ReadAt to memory file and tests. (#122)
* memory files now implement io.ReaderAt. * tests now check ReadAt behaviour.
1 parent ac095bb commit 3e7f535

File tree

3 files changed

+46
-2
lines changed

3 files changed

+46
-2
lines changed

utils/fs/memory/memory.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,16 @@ func newFile(base, fullpath string, flag int) *file {
189189
}
190190

191191
func (f *file) Read(b []byte) (int, error) {
192+
n, err := f.ReadAt(b, f.position)
193+
if err != nil {
194+
return 0, err
195+
}
196+
197+
f.position += int64(n)
198+
return n, err
199+
}
200+
201+
func (f *file) ReadAt(b []byte, off int64) (int, error) {
192202
if f.IsClosed() {
193203
return 0, fs.ErrClosed
194204
}
@@ -197,7 +207,7 @@ func (f *file) Read(b []byte) (int, error) {
197207
return 0, errors.New("read not supported")
198208
}
199209

200-
n, err := f.content.ReadAt(b, f.position)
210+
n, err := f.content.ReadAt(b, off)
201211
f.position += int64(n)
202212

203213
return n, err

utils/fs/os/os.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,6 @@ func (f *osFile) Close() error {
178178
return f.file.Close()
179179
}
180180

181-
func (f *osFile) ReadAt(p []byte, off int64) (n int, err error) {
181+
func (f *osFile) ReadAt(p []byte, off int64) (int, error) {
182182
return f.file.ReadAt(p, off)
183183
}

utils/fs/test/fs_suite.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,3 +379,37 @@ func (s *FilesystemSuite) TestJoin(c *C) {
379379
func (s *FilesystemSuite) TestBase(c *C) {
380380
c.Assert(s.Fs.Base(), Not(Equals), "")
381381
}
382+
383+
func (s *FilesystemSuite) TestReadAtOnReadWrite(c *C) {
384+
f, err := s.Fs.Create("foo")
385+
c.Assert(err, IsNil)
386+
_, err = f.Write([]byte("abcdefg"))
387+
c.Assert(err, IsNil)
388+
rf, ok := f.(io.ReaderAt)
389+
c.Assert(ok, Equals, true)
390+
b := make([]byte, 3)
391+
n, err := rf.ReadAt(b, 2)
392+
c.Assert(err, IsNil)
393+
c.Assert(n, Equals, 3)
394+
c.Assert(string(b), Equals, "cde")
395+
c.Assert(f.Close(), IsNil)
396+
}
397+
398+
func (s *FilesystemSuite) TestReadAtOnReadOnly(c *C) {
399+
f, err := s.Fs.Create("foo")
400+
c.Assert(err, IsNil)
401+
_, err = f.Write([]byte("abcdefg"))
402+
c.Assert(err, IsNil)
403+
c.Assert(f.Close(), IsNil)
404+
405+
f, err = s.Fs.Open("foo")
406+
c.Assert(err, IsNil)
407+
rf, ok := f.(io.ReaderAt)
408+
c.Assert(ok, Equals, true)
409+
b := make([]byte, 3)
410+
n, err := rf.ReadAt(b, 2)
411+
c.Assert(err, IsNil)
412+
c.Assert(n, Equals, 3)
413+
c.Assert(string(b), Equals, "cde")
414+
c.Assert(f.Close(), IsNil)
415+
}

0 commit comments

Comments
 (0)