-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_internal.go
99 lines (87 loc) · 2.09 KB
/
log_internal.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
package raft
import (
"sort"
"github.com/sumimakito/raft/pb"
)
type internalLogStore struct {
logs []*pb.Log
}
func newInternalLogStore() *internalLogStore {
return &internalLogStore{}
}
func (s *internalLogStore) putLog(log *pb.Log) {
i := sort.Search(len(s.logs), func(i int) bool { return s.logs[i].Meta.Index > log.Meta.Index })
if i == len(s.logs) {
s.logs = append(s.logs, log.Copy())
return
}
s.logs = append(s.logs, nil)
copy(s.logs[i+1:], s.logs[i:])
s.logs[i] = log.Copy()
}
func (s *internalLogStore) AppendLogs(logs []*pb.Log) error {
for _, log := range logs {
s.putLog(log)
}
return nil
}
func (s *internalLogStore) TrimPrefix(index uint64) error {
i := sort.Search(len(s.logs), func(i int) bool { return s.logs[i].Meta.Index >= index })
if i == 0 {
return nil
}
s.logs = append([]*pb.Log(nil), s.logs[i:]...)
return nil
}
func (s *internalLogStore) TrimSuffix(index uint64) error {
i := sort.Search(len(s.logs), func(i int) bool { return s.logs[i].Meta.Index >= index })
if i == len(s.logs) {
return nil
}
if s.logs[i].Meta.Index > index {
// We did not find the exact entry.
if i == 0 {
s.logs = []*pb.Log{}
return nil
}
i -= 1
}
s.logs = append([]*pb.Log(nil), s.logs[:i+1]...)
return nil
}
func (s *internalLogStore) FirstIndex() (uint64, error) {
if len(s.logs) == 0 {
return 0, nil
}
return s.logs[0].Meta.Index, nil
}
func (s *internalLogStore) LastIndex() (uint64, error) {
if len(s.logs) == 0 {
return 0, nil
}
return s.logs[len(s.logs)-1].Meta.Index, nil
}
func (s *internalLogStore) Entry(index uint64) (*pb.Log, error) {
if len(s.logs) == 0 {
return nil, nil
}
i := sort.Search(len(s.logs), func(i int) bool { return s.logs[i].Meta.Index >= index })
if i == len(s.logs) || s.logs[i].Meta.Index != index {
return nil, nil
}
return s.logs[i], nil
}
func (s *internalLogStore) LastEntry(t pb.LogType) (*pb.Log, error) {
if len(s.logs) == 0 {
return nil, nil
}
if t == 0 {
return s.logs[len(s.logs)-1], nil
}
for i := len(s.logs) - 1; i >= 0; i-- {
if s.logs[i].Body.Type == t {
return s.logs[i], nil
}
}
return nil, nil
}