-
Notifications
You must be signed in to change notification settings - Fork 4
/
aof.go
66 lines (57 loc) · 1.15 KB
/
aof.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
package main
import (
"bytes"
"github.com/xgzlucario/rotom/internal/resp"
"io"
"os"
"github.com/tidwall/mmap"
)
// Aof manages an append-only file system for storing data.
type Aof struct {
file *os.File
buf *bytes.Buffer
}
func NewAof(path string) (*Aof, error) {
fd, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
if err != nil {
return nil, err
}
return &Aof{
file: fd,
buf: bytes.NewBuffer(make([]byte, 0, KB)),
}, nil
}
func (a *Aof) Close() error {
return a.file.Close()
}
func (a *Aof) Write(buf []byte) (int, error) {
return a.buf.Write(buf)
}
func (a *Aof) Flush() error {
_, _ = a.buf.WriteTo(a.file)
return a.file.Sync()
}
func (a *Aof) Read(fn func(args []resp.RESP)) error {
// Read file data by mmap.
data, err := mmap.MapFile(a.file, false)
if len(data) == 0 {
return nil
}
if err != nil {
return err
}
// Iterate over the records in the file, applying the function to each.
reader := resp.NewReader(data)
argsBuf := make([]resp.RESP, 8)
for {
args, _, err := reader.ReadNextCommand(argsBuf)
if err != nil {
if err == io.EOF {
break
}
return err
}
fn(args)
}
return nil
}