-
Notifications
You must be signed in to change notification settings - Fork 211
/
datafile.go
106 lines (89 loc) · 1.99 KB
/
datafile.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package post
import (
"bufio"
"github.com/spacemeshos/go-spacemesh/log"
"os"
"path"
)
// dataFile is a simple binary data file
type dataFile interface {
exists() bool
delete() error
create() error
close() error
read(off int64, out []byte) error // read len(out) bytes at offset off from the file
write(data []byte) error // write data at current offset and advanced offset
seek(off int64) error // set new write offset from 0
sync() error // sync all changes to store
}
type dataFileImpl struct {
name string
file *os.File
writer *bufio.Writer
offset int64
}
func newDataFile(dir string) dataFile {
fileName := path.Join(dir, "post.dat")
f := &dataFileImpl{name: fileName}
return f
}
func (d *dataFileImpl) seek(off int64) error {
if off == d.offset { // we are already here
return nil
}
// flush any existing buffered data
err := d.writer.Flush()
if err != nil {
return err
}
// seek to new offset
_, err = d.file.Seek(off, 0)
if err != nil {
return err
}
d.offset = off
// create buffered writer at current offset
d.writer = bufio.NewWriter(d.file)
return nil
}
func (d *dataFileImpl) write(data []byte) error {
_, err := d.writer.Write(data)
d.offset = d.offset + int64(len(data))
return err
}
func (d *dataFileImpl) sync() error {
return d.writer.Flush()
}
func (d *dataFileImpl) read(off int64, out []byte) error {
_, err := d.file.ReadAt(out, off)
return err
}
func (d *dataFileImpl) exists() bool {
_, err := os.Stat(d.name)
if err == nil {
return true
} else if os.IsNotExist(err) {
return false
} else {
// stats error
return false
}
}
func (d *dataFileImpl) delete() error {
return os.Remove(d.name)
}
func (d *dataFileImpl) close() error {
if d.file == nil {
return nil
}
return d.file.Close()
}
func (d *dataFileImpl) create() error {
file, err := os.Create(d.name)
if err == nil {
d.file = file
d.writer = bufio.NewWriter(file)
}
log.Debug("Created table file at: %s", d.name)
return err
}