-
Notifications
You must be signed in to change notification settings - Fork 92
/
file.go
107 lines (97 loc) · 1.87 KB
/
file.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
107
package pogreb
import (
"io"
"os"
"github.com/akrylysov/pogreb/fs"
)
// file is a database file.
// When stored in a file system, the file starts with a header.
type file struct {
fs.File
size int64
}
type openFileFlags struct {
truncate bool
readOnly bool
}
func openFile(fsyst fs.FileSystem, name string, flags openFileFlags) (*file, error) {
var flag int
if flags.readOnly {
flag = os.O_RDONLY
} else {
flag = os.O_CREATE | os.O_RDWR
if flags.truncate {
flag |= os.O_TRUNC
}
}
fi, err := fsyst.OpenFile(name, flag, os.FileMode(0640))
f := &file{}
if err != nil {
return f, err
}
clean := fi.Close
defer func() {
if clean != nil {
_ = clean()
}
}()
f.File = fi
stat, err := fi.Stat()
if err != nil {
return f, err
}
f.size = stat.Size()
if f.size == 0 {
// It's a new file - write header.
if err := f.writeHeader(); err != nil {
return nil, err
}
} else {
if err := f.readHeader(); err != nil {
return nil, err
}
}
if _, err := f.Seek(int64(headerSize), io.SeekStart); err != nil {
return nil, err
}
clean = nil
return f, nil
}
func (f *file) writeHeader() error {
h := newHeader()
data, err := h.MarshalBinary()
if err != nil {
return err
}
if _, err = f.append(data); err != nil {
return err
}
return nil
}
func (f *file) readHeader() error {
h := &header{}
buf := make([]byte, headerSize)
if _, err := io.ReadFull(f, buf); err != nil {
return err
}
return h.UnmarshalBinary(buf)
}
func (f *file) empty() bool {
return f.size == int64(headerSize)
}
func (f *file) extend(size uint32) (int64, error) {
off := f.size
if err := f.Truncate(off + int64(size)); err != nil {
return 0, err
}
f.size += int64(size)
return off, nil
}
func (f *file) append(data []byte) (int64, error) {
off := f.size
if _, err := f.WriteAt(data, off); err != nil {
return 0, err
}
f.size += int64(len(data))
return off, nil
}