-
Notifications
You must be signed in to change notification settings - Fork 7
/
mem.go
47 lines (38 loc) · 838 Bytes
/
mem.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
package engine
import (
"log"
"unsafe"
"github.com/nvanbenschoten/rafttoy/proposal"
"go.etcd.io/etcd/raft/v3"
"go.etcd.io/etcd/raft/v3/raftpb"
)
type mem struct {
m *raft.MemoryStorage
kv map[string][]byte
}
// NewMem creates a new in-memory storage engine.
func NewMem() Engine {
return &mem{
m: raft.NewMemoryStorage(),
kv: make(map[string][]byte),
}
}
func (m *mem) SetHardState(st raftpb.HardState, _ bool) {
if err := m.m.SetHardState(st); err != nil {
log.Fatal(err)
}
}
func (m *mem) ApplyEntry(ent raftpb.Entry) {
prop := proposal.Decode(ent.Data)
m.kv[unsafeString(prop.Key)] = prop.Val
}
func unsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func (m *mem) Clear() {
m.m = raft.NewMemoryStorage()
m.kv = make(map[string][]byte)
}
func (m *mem) CloseEngine() {
// No-op.
}