tstor/src/host/vfs/memory.go

94 lines
1.7 KiB
Go
Raw Normal View History

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 {
2024-03-20 10:49:19 +00:00
name string
2023-10-16 09:18:40 +00:00
files map[string]*MemoryFile
2021-11-23 12:05:49 +00:00
}
2024-03-20 10:49:19 +00:00
// Info implements Filesystem.
func (fs *MemoryFs) Info() (fs.FileInfo, error) {
return newDirInfo(fs.name), nil
}
// IsDir implements Filesystem.
func (fs *MemoryFs) IsDir() bool {
return true
}
// Name implements Filesystem.
func (fs *MemoryFs) Name() string {
return fs.name
}
// Type implements Filesystem.
func (mfs *MemoryFs) Type() fs.FileMode {
return fs.ModeDir
}
2023-12-25 22:11:03 +00:00
// Unlink implements Filesystem.
func (fs *MemoryFs) Unlink(filename string) error {
return ErrNotImplemented
}
2024-03-20 10:49:19 +00:00
func NewMemoryFS(name string, files map[string]*MemoryFile) *MemoryFs {
2023-10-16 09:18:40 +00:00
return &MemoryFs{
2024-03-20 10:49:19 +00:00
name: name,
2023-10-16 09:18:40 +00:00
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
}