-
Notifications
You must be signed in to change notification settings - Fork 4
/
data_set.go
98 lines (75 loc) · 1.56 KB
/
data_set.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
package encoding
import (
"sync"
)
// 构造函数
func NewDataSet[N DataName, M any]() *DataSet[N, M] {
return &DataSet[N, M]{
data: make(map[N]func() M),
}
}
type DataName interface {
~uint | ~int | ~string
}
/**
* 数据设置
*
* @create 2023-3-31
* @author deatil
*/
type DataSet[N DataName, M any] struct {
// 锁定
mu sync.RWMutex
// 数据
data map[N]func() M
}
// 设置
func (this *DataSet[N, M]) Add(name N, data func() M) *DataSet[N, M] {
this.mu.Lock()
defer this.mu.Unlock()
this.data[name] = data
return this
}
func (this *DataSet[N, M]) Has(name N) bool {
this.mu.RLock()
defer this.mu.RUnlock()
if _, ok := this.data[name]; ok {
return true
}
return false
}
func (this *DataSet[N, M]) Get(name N) func() M {
this.mu.RLock()
defer this.mu.RUnlock()
if data, ok := this.data[name]; ok {
return data
}
return nil
}
// 删除
func (this *DataSet[N, M]) Remove(name N) *DataSet[N, M] {
this.mu.Lock()
defer this.mu.Unlock()
delete(this.data, name)
return this
}
func (this *DataSet[N, M]) Names() []N {
names := make([]N, 0)
for name, _ := range this.data {
names = append(names, name)
}
return names
}
func (this *DataSet[N, M]) All() map[N]func() M {
return this.data
}
func (this *DataSet[N, M]) Clean() {
this.mu.Lock()
defer this.mu.Unlock()
for name, _ := range this.data {
delete(this.data, name)
}
}
func (this *DataSet[N, M]) Len() int {
return len(this.data)
}