-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.go
57 lines (50 loc) · 895 Bytes
/
index.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
package slices
import "sync"
// Index 索引
type Index[T any, I comparable] struct {
idx []I
value []T
sync.RWMutex
}
func NewIndex[T any, I comparable]() *Index[T, I] {
return &Index[T, I]{
idx: make([]I, 0),
value: make([]T, 0),
}
}
func (i *Index[T, I]) Add(idx I, res T) {
i.idx = append(i.idx, idx)
i.value = append(i.value, res)
}
func (i *Index[T, I]) Get(idx I) T {
i.RLock()
defer i.RUnlock()
for j, v := range i.idx {
if v == idx {
return i.value[j]
}
}
return *new(T)
}
func (i *Index[T, I]) Set(idx I, v T) {
i.RLock()
defer i.RUnlock()
for j, x := range i.idx {
if x == idx {
i.value[j] = v
}
return
}
}
func (i *Index[T, I]) Remove(idx I) {
i.Lock()
defer i.Unlock()
for j, v := range i.idx {
if v == idx {
i.idx = append(i.idx[0:j], i.idx[j:]...)
i.value = append(i.value[0:j], i.value[j:]...)
return
}
}
return
}