-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmap_of.go
96 lines (79 loc) · 1.91 KB
/
map_of.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
package gokit
import "sync"
// MapOf 泛型实现的sync.Map
type MapOf[K comparable, V any] struct {
values *sync.Map
}
// NewMapOf 构造函数
func NewMapOf[K comparable, V any]() *MapOf[K, V] {
return &MapOf[K, V]{
values: &sync.Map{},
}
}
// CompareAndDelete 比较并删除
func (mo *MapOf[K, V]) CompareAndDelete(key K, old V) (deleted bool) {
return mo.values.CompareAndDelete(key, old)
}
// CompareAndSwap 比较并替换
func (mo *MapOf[K, V]) CompareAndSwap(key K, old, new V) bool {
return mo.values.CompareAndSwap(key, old, new)
}
// Load 根据key查询结果
func (mo *MapOf[K, V]) Load(key K) (value V, found bool) {
if v, ok := mo.values.Load(key); ok {
return v.(V), true
}
return
}
// LoadAndDelete 查询并删除
func (mo *MapOf[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
if v, ok := mo.values.LoadAndDelete(key); ok {
return v.(V), true
}
return
}
// LoadOrStore 查询已经存在的数据,不存在则存储
func (mo *MapOf[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
if v, ok := mo.values.LoadOrStore(key, value); ok {
return v.(V), true
}
return value, false
}
// Store 保存
func (mo *MapOf[K, V]) Store(key K, value V) {
mo.values.Store(key, value)
}
// Delete 删除
func (mo *MapOf[K, V]) Delete(key K) {
mo.values.Delete(key)
}
// Range 遍历
func (mo *MapOf[K, V]) Range(f func(key K, value V) bool) {
mo.values.Range(func(k, v any) bool {
return f(k.(K), v.(V))
})
}
// Swap 替换值
func (mo *MapOf[K, V]) Swap(key K, value V) (previous V, loaded bool) {
if v, ok := mo.values.Swap(key, value); ok {
return v.(V), true
}
return
}
// ToMap to map
func (mo *MapOf[K, V]) ToMap() map[K]V {
result := make(map[K]V)
mo.Range(func(k K, v V) bool {
result[k] = v
return true
})
return result
}
// Count 总数
func (mo *MapOf[K, V]) Count() (count int64) {
mo.values.Range(func(k, v any) bool {
count++
return true
})
return
}