2023-10-16 09:18:40 +00:00
|
|
|
package vfs
|
2021-11-23 12:05:49 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2023-12-21 23:15:39 +00:00
|
|
|
"io/fs"
|
|
|
|
"path"
|
2021-11-23 12:05:49 +00:00
|
|
|
)
|
|
|
|
|
2023-10-16 09:18:40 +00:00
|
|
|
var _ Filesystem = &MemoryFs{}
|
2021-11-23 12:05:49 +00:00
|
|
|
|
2023-10-16 09:18:40 +00:00
|
|
|
type MemoryFs struct {
|
|
|
|
files map[string]*MemoryFile
|
2021-11-23 12:05:49 +00:00
|
|
|
}
|
|
|
|
|
2023-12-25 22:11:03 +00:00
|
|
|
// Unlink implements Filesystem.
|
|
|
|
func (fs *MemoryFs) Unlink(filename string) error {
|
|
|
|
return ErrNotImplemented
|
|
|
|
}
|
|
|
|
|
2023-10-16 09:18:40 +00:00
|
|
|
func NewMemoryFS(files map[string]*MemoryFile) *MemoryFs {
|
|
|
|
return &MemoryFs{
|
|
|
|
files: files,
|
2021-11-23 12:05:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-16 09:18:40 +00:00
|
|
|
func (m *MemoryFs) Open(filename string) (File, error) {
|
|
|
|
return getFile(m.files, filename)
|
2021-11-23 12:05:49 +00:00
|
|
|
}
|
|
|
|
|
2023-12-21 23:15:39 +00:00
|
|
|
func (fs *MemoryFs) ReadDir(path string) ([]fs.DirEntry, error) {
|
|
|
|
return listDirFromFiles(fs.files, path)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Stat implements Filesystem.
|
|
|
|
func (mfs *MemoryFs) Stat(filename string) (fs.FileInfo, error) {
|
|
|
|
file, ok := mfs.files[filename]
|
|
|
|
if !ok {
|
|
|
|
return nil, ErrNotExist
|
|
|
|
}
|
|
|
|
return newFileInfo(path.Base(filename), file.Size()), nil
|
2021-11-23 12:05:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
var _ File = &MemoryFile{}
|
|
|
|
|
|
|
|
type MemoryFile struct {
|
2023-12-21 23:15:39 +00:00
|
|
|
name string
|
2021-11-23 12:05:49 +00:00
|
|
|
*bytes.Reader
|
|
|
|
}
|
|
|
|
|
2023-12-21 23:15:39 +00:00
|
|
|
func NewMemoryFile(name string, data []byte) *MemoryFile {
|
2021-11-23 12:05:49 +00:00
|
|
|
return &MemoryFile{
|
2023-12-21 23:15:39 +00:00
|
|
|
name: name,
|
2021-11-23 12:05:49 +00:00
|
|
|
Reader: bytes.NewReader(data),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-21 23:15:39 +00:00
|
|
|
func (d *MemoryFile) Stat() (fs.FileInfo, error) {
|
|
|
|
return newFileInfo(d.name, int64(d.Reader.Len())), nil
|
|
|
|
}
|
|
|
|
|
2021-11-23 12:05:49 +00:00
|
|
|
func (d *MemoryFile) Size() int64 {
|
|
|
|
return int64(d.Reader.Len())
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *MemoryFile) IsDir() bool {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func (d *MemoryFile) Close() (err error) {
|
|
|
|
return
|
|
|
|
}
|