slicefile.go 1.23 KB
Newer Older
1 2
package files

3 4 5 6
import (
	"errors"
	"io"
)
7 8 9 10 11

// SliceFile implements File, and provides simple directory handling.
// It contains children files, and is created from a `[]File`.
// SliceFiles are always directories, and can't be read from or closed.
type SliceFile struct {
12 13 14 15 16 17 18
	filename string
	files    []File
	n        int
}

func NewSliceFile(filename string, files []File) *SliceFile {
	return &SliceFile{filename, files, 0}
19 20 21 22 23 24 25
}

func (f *SliceFile) IsDirectory() bool {
	return true
}

func (f *SliceFile) NextFile() (File, error) {
26
	if f.n >= len(f.files) {
27 28
		return nil, io.EOF
	}
29 30
	file := f.files[f.n]
	f.n++
31 32 33 34
	return file, nil
}

func (f *SliceFile) FileName() string {
35
	return f.filename
36 37 38 39 40 41 42 43 44
}

func (f *SliceFile) Read(p []byte) (int, error) {
	return 0, ErrNotReader
}

func (f *SliceFile) Close() error {
	return ErrNotReader
}
45 46 47 48 49 50 51 52

func (f *SliceFile) Peek(n int) File {
	return f.files[n]
}

func (f *SliceFile) Length() int {
	return len(f.files)
}
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71

func (f *SliceFile) Size() (int64, error) {
	var size int64

	for _, file := range f.files {
		sizeFile, ok := file.(SizeFile)
		if !ok {
			return 0, errors.New("Could not get size of child file")
		}

		s, err := sizeFile.Size()
		if err != nil {
			return 0, err
		}
		size += s
	}

	return size, nil
}