Skip to content

Commit

Permalink
Fix readdir and implement seek for directory
Browse files Browse the repository at this point in the history
If n <= 0, Readdir should return the remaining files and
never return io.EOF.
If n > 0, Readdir should only return io.EOF if it returns
an empty slice, per the documentation of os.Readdir.
It should also not reset the offset to 0.

Implement seek for directories when offset is 0 and
whence is io.SeekStart, because os.Seek supports this.
  • Loading branch information
nkovacs committed Jul 20, 2017
1 parent 341d7a8 commit 96d5b2a
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions virtual.go
Original file line number Diff line number Diff line change
Expand Up @@ -203,24 +203,31 @@ func (vd *virtualDir) readdir(n int) (fi []os.FileInfo, err error) {
// Sort it by filename (lexical order)
sort.Sort(SortByName(files))

// Return all contents if that's what is requested
// Return all remainign contents if that's what is requested
if n <= 0 {
vd.offset = 0
return files, nil
offset := vd.offset
vd.offset = len(files)
return files[offset:], nil
}

end := vd.offset + n
// If user has requested past the end of our list
// return what we can and send an EOF
if vd.offset+n >= len(files) {
offset := vd.offset
vd.offset = 0
return files[offset:], io.EOF
// return what we can
if end >= len(files) {
end = len(files)
}

offset := vd.offset
vd.offset += n
return files[offset : offset+n], nil
vd.offset = end
fi = files[offset:end]

if len(fi) == 0 && n > 0 {
// Per File.Readdir, the slice must be non-empty or err
// must be non-nil if n > 0.
err = io.EOF
}

return fi, err
}

func (vd *virtualDir) read(bts []byte) (int, error) {
Expand All @@ -246,6 +253,11 @@ func (vd *virtualDir) seek(offset int64, whence int) (int64, error) {
Err: errors.New("bad file descriptor"),
}
}
if whence == io.SeekStart && offset == 0 {
// special case for rewinddir
vd.offset = 0
return 0, nil
}
return 0, &os.PathError{
Op: "seek",
Path: vd.Filename,
Expand Down

0 comments on commit 96d5b2a

Please sign in to comment.