-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
68 lines (59 loc) · 1.5 KB
/
utils.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
package fs
import (
"bytes"
"github.com/vlorc/lua-vm/base"
"unsafe"
)
type FileUtilsFactory struct {
filesystem FileSystem
}
func NewFileUtilsFactory(filesystem FileSystem) *FileUtilsFactory {
return &FileUtilsFactory{filesystem: filesystem}
}
func (f *FileUtilsFactory) ReadString(file string, args ...int) (string, error) {
buf, err := f.__readBuffer(file, args...)
if nil != err {
return "", nil
}
return *(*string)(unsafe.Pointer(&buf)), nil
}
func (f *FileUtilsFactory) ReadBuffer(file string, args ...int) (base.Buffer, error) {
buf, err := f.__readBuffer(file, args...)
if nil != err {
return nil, nil
}
return base.Buffer(buf), nil
}
func (f *FileUtilsFactory) __readBuffer(file string, args ...int) ([]byte, error) {
fd, err := f.filesystem.Open(file)
if nil != err {
return nil, err
}
defer fd.Close()
var n int64 = bytes.MinRead
if fi, err := fd.Stat(); err == nil {
if size := fi.Size() + bytes.MinRead; size > n {
n = size
}
}
var buf bytes.Buffer
buf.Grow(int(n))
_, err = buf.ReadFrom(fd)
return buf.Bytes(), err
}
func (f *FileUtilsFactory) WriteString(file string, str string, args ...int) (int, error) {
fd, err := f.filesystem.Open(file, 0, 0666)
if nil != err {
return 0, err
}
defer fd.Close()
return fd.Write(*(*[]byte)(unsafe.Pointer(&str)))
}
func (f *FileUtilsFactory) WriteBuffer(file string, buf base.Buffer, args ...int) (int, error) {
fd, err := f.filesystem.Open(file, 0, 0666)
if nil != err {
return 0, err
}
defer fd.Close()
return fd.Write(buf)
}