-
Notifications
You must be signed in to change notification settings - Fork 0
/
history.go
99 lines (85 loc) · 1.49 KB
/
history.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 code
import (
"sync"
)
type History struct {
Items []HistoryItem
mu sync.RWMutex
lastID int64
}
type HistoryItem struct {
Code string
ID int64
}
func (hi HistoryItem) GetID() int64 {
return hi.ID
}
func NewHistory() *History {
return &History{
Items: make([]HistoryItem, 0),
mu: sync.RWMutex{},
}
}
func (h *History) Add(item string) {
h.mu.Lock()
defer h.mu.Unlock()
h.Items = append(h.Items, HistoryItem{
Code: item,
ID: h.lastID,
})
h.lastID++
}
func (h *History) Get(id int64) (HistoryItem, bool) {
h.mu.RLock()
defer h.mu.RUnlock()
for _, item := range h.Items {
if item.ID == id {
return item, true
}
}
return HistoryItem{}, false
}
func (h *History) Update(id int64, item HistoryItem) {
h.mu.Lock()
defer h.mu.Unlock()
idx := -1
for i, item := range h.Items {
if item.ID != id {
continue
}
idx = i
break
}
if idx == -1 {
panic("item not found")
}
h.Items[idx] = item
}
func (h *History) List() []HistoryItem {
h.mu.RLock()
defer h.mu.RUnlock()
items := make([]HistoryItem, len(h.Items))
copy(items, h.Items)
return items
}
func (h *History) Clear() {
h.mu.Lock()
defer h.mu.Unlock()
h.Items = make([]HistoryItem, 0)
}
func (h *History) Len() int {
h.mu.RLock()
defer h.mu.RUnlock()
return len(h.Items)
}
func (h *History) Remove(id int64) bool {
h.mu.Lock()
defer h.mu.Unlock()
for i, item := range h.Items {
if item.ID == id {
h.Items = append(h.Items[:i], h.Items[i+1:]...)
return true
}
}
return false
}