Skip to content

Commit e2307cd

Browse files
committed
rwmux+map兼容sync.Map的接口
1 parent 6d29579 commit e2307cd

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

rwmap/rwmap.go

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// apache 2.0 antlabs
2+
3+
package rwmap
4+
5+
import "sync"
6+
7+
type RWMap[K comparable, V any] struct {
8+
rw sync.RWMutex
9+
m map[K]V
10+
}
11+
12+
func (r *RWMap[K, V]) Delete(key K) {
13+
r.rw.Lock()
14+
delete(r.m, key)
15+
r.rw.Unlock()
16+
}
17+
18+
func (r *RWMap[K, V]) Load(key K) (value any, ok bool) {
19+
r.rw.RLock()
20+
value, ok = r.m[key]
21+
r.rw.RUnlock()
22+
return
23+
24+
}
25+
26+
func (r *RWMap[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
27+
r.rw.Lock()
28+
if r.m == nil {
29+
r.m = make(map[K]V)
30+
}
31+
value, loaded = r.m[key]
32+
delete(r.m, key)
33+
r.rw.Unlock()
34+
return
35+
}
36+
37+
// 存在返回现有的值,loaded 为true
38+
// 不存在就保存现在的值,loaded为false
39+
func (r *RWMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
40+
r.rw.Lock()
41+
actual, loaded = r.m[key]
42+
if !loaded {
43+
actual = value
44+
r.m[key] = actual
45+
}
46+
r.rw.Unlock()
47+
return
48+
}
49+
50+
func (r *RWMap[K, V]) Range(f func(key K, value V) bool) {
51+
r.rw.RLock()
52+
for k, v := range r.m {
53+
if !f(k, v) {
54+
break
55+
}
56+
}
57+
r.rw.RUnlock()
58+
}
59+
60+
// 保存值
61+
func (r *RWMap[K, V]) Store(key K, value V) {
62+
r.rw.Lock()
63+
if r.m == nil {
64+
r.m = make(map[K]V)
65+
}
66+
r.rw.Unlock()
67+
}
68+
69+
// 返回长度
70+
func (r *RWMap[K, V]) Len() (l int) {
71+
r.rw.RLock()
72+
l = len(r.m)
73+
r.rw.RUnlock()
74+
return
75+
}

0 commit comments

Comments
 (0)