-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
fs.go
81 lines (70 loc) · 1.18 KB
/
fs.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package stdio
import (
"errors"
"io"
"os"
"sync"
"github.com/gotranspile/cxgo/runtime/libc"
)
type FileI interface {
Fd() uintptr
Name() string
Sync() error
io.Reader
io.Writer
io.Seeker
io.Closer
}
type Filesystem interface {
Stdout() FileI
Stderr() FileI
Stdin() FileI
Getwd() (string, error)
Chdir(path string) error
Rmdir(path string) error
Unlink(path string) error
Open(path string, flag int, mode os.FileMode) (FileI, error)
Stat(path string) (os.FileInfo, error)
}
var defaultFS *filesystem
func init() {
SetFS(nil)
}
func SetFS(fs Filesystem) {
if fs == nil {
fs = localFS{}
}
// TODO: mount stdout, stderr, stdin
defaultFS = &filesystem{
fs: fs,
byFD: make(map[uintptr]*File),
}
}
func FS() Filesystem {
if defaultFS == nil {
SetFS(nil)
}
return defaultFS.fs
}
func ByFD(fd uintptr) *File {
f, err := defaultFS.fileByFD(fd)
if err != nil {
libc.SetErr(err)
return nil
}
return f
}
type filesystem struct {
fs Filesystem
sync.RWMutex
byFD map[uintptr]*File
}
func (fs *filesystem) fileByFD(fd uintptr) (*File, error) {
fs.RLock()
f := fs.byFD[fd]
fs.RUnlock()
if f == nil {
return nil, errors.New("invalid fd")
}
return f, nil
}