-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnapshot.go
55 lines (43 loc) · 918 Bytes
/
snapshot.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
package raft
import (
"bufio"
"fmt"
"github.com/treeforest/raft/pb"
"hash/crc32"
"os"
)
type Snapshot struct {
pb.Snapshot
Path string
}
func newSnapshot(path string, ss *pb.Snapshot) *Snapshot {
return &Snapshot{Snapshot: *ss, Path: path}
}
func (ss *Snapshot) Save() error {
file, err := os.OpenFile(ss.Path, os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
defer file.Close()
b, err := ss.Snapshot.Marshal()
if err != nil {
return err
}
w := bufio.NewWriter(file)
if _, err = w.Write([]byte(fmt.Sprintf("%08x\n", crc32.ChecksumIEEE(b)))); err != nil {
return err
}
if _, err = w.Write(b); err != nil {
return err
}
return w.Flush()
}
func (ss *Snapshot) Remove() error {
return os.Remove(ss.Path)
}
func (ss *Snapshot) Marshal() ([]byte, error) {
return ss.Snapshot.Marshal()
}
func (ss *Snapshot) Unmarshal(b []byte) error {
return ss.Snapshot.Unmarshal(b)
}