-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.go
65 lines (57 loc) · 1.26 KB
/
storage.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
package raftgo
import (
"sync"
)
type Storage interface {
LastIndex() int
Entry(index int) *LogEntry
BatchEntries(startIndex int, maxLen int) []LogEntry
TruncateAndAppend(entries []LogEntry)
}
type MemStorage struct {
entries []LogEntry
mu sync.RWMutex
}
func NewMemStorage() *MemStorage {
return &MemStorage{
entries: []LogEntry{{LogIndex: 0, LogTerm: 0, Command: ""}},
}
}
func (m *MemStorage) BatchEntries(startIndex int, maxLen int) []LogEntry {
m.mu.RLock()
defer m.mu.RUnlock()
endIndex := startIndex + maxLen
if endIndex > len(m.entries) {
endIndex = len(m.entries)
}
return m.entries[startIndex:endIndex]
}
func (m *MemStorage) Entry(index int) *LogEntry {
m.mu.RLock()
defer m.mu.RUnlock()
if index < len(m.entries) {
return &m.entries[index]
}
return nil
}
func (m *MemStorage) LastIndex() int {
m.mu.RLock()
defer m.mu.RUnlock()
return m.entries[len(m.entries)-1].LogIndex
}
func (m *MemStorage) TruncateAndAppend(entries []LogEntry) {
m.mu.Lock()
defer m.mu.Unlock()
if len(entries) == 0 {
return
}
for _, e := range entries {
if e.LogIndex > len(m.entries)-1 {
m.entries = append(m.entries, e)
} else {
m.entries[e.LogIndex] = e
}
}
lastId := entries[len(entries)-1].LogIndex
m.entries = m.entries[:lastId+1]
}