Skip to content

Commit 2c3b87b

Browse files
authored
Merge pull request #4 from antlabs/rwmap-ex
rwmap加上Keys, Values函数
2 parents dbc00b4 + 6f25492 commit 2c3b87b

File tree

3 files changed

+60
-2
lines changed

3 files changed

+60
-2
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# gstl
2-
支持泛型的数据结构库
2+
支持泛型的数据结构库
33
[![Go](https://github.com/antlabs/gstl/workflows/Go/badge.svg)](https://github.com/antlabs/gstl/actions)
44
[![codecov](https://codecov.io/gh/antlabs/gstl/branch/master/graph/badge.svg)](https://codecov.io/gh/antlabs/gstl)
55

@@ -179,4 +179,6 @@ for pair := range m.Iter() {
179179
}
180180

181181
m.Len()// 获取长度
182+
allKeys := m.Keys() //返回所有的key
183+
allValues := m.Values()// 返回所有的value
182184
```

rwmap/rwmap.go

+31-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,11 @@
22

33
package rwmap
44

5-
import "sync"
5+
import (
6+
"sync"
7+
8+
"github.com/antlabs/gstl/mapex"
9+
)
610

711
type RWMap[K comparable, V any] struct {
812
rw sync.RWMutex
@@ -100,6 +104,32 @@ func (r *RWMap[K, V]) Store(key K, value V) {
100104
r.rw.Unlock()
101105
}
102106

107+
// keys
108+
func (r *RWMap[K, V]) Keys() (keys []K) {
109+
110+
r.rw.RLock()
111+
if r.m == nil {
112+
r.rw.RUnlock()
113+
return
114+
}
115+
keys = mapex.Keys(r.m)
116+
r.rw.RUnlock()
117+
return keys
118+
}
119+
120+
// vals
121+
func (r *RWMap[K, V]) Values() (values []V) {
122+
123+
r.rw.RLock()
124+
if r.m == nil {
125+
r.rw.RUnlock()
126+
return
127+
}
128+
values = mapex.Values(r.m)
129+
r.rw.RUnlock()
130+
return values
131+
}
132+
103133
// 返回长度
104134
func (r *RWMap[K, V]) Len() (l int) {
105135
r.rw.RLock()

rwmap/rwmap_test.go

+26
Original file line numberDiff line numberDiff line change
@@ -156,3 +156,29 @@ func Test_New(t *testing.T) {
156156
m.Store("3", "3")
157157
assert.Equal(t, m.Len(), 3)
158158
}
159+
160+
func Test_Keys(t *testing.T) {
161+
m := New[string, string](3)
162+
m.Store("a", "1")
163+
m.Store("b", "2")
164+
m.Store("c", "3")
165+
get := m.Keys()
166+
sort.Strings(get)
167+
assert.Equal(t, get, []string{"a", "b", "c"})
168+
169+
var m2 RWMap[string, string]
170+
assert.Equal(t, len(m2.Values()), 0)
171+
}
172+
173+
func Test_Values(t *testing.T) {
174+
m := New[string, string](3)
175+
m.Store("a", "1")
176+
m.Store("b", "2")
177+
m.Store("c", "3")
178+
get := m.Values()
179+
sort.Strings(get)
180+
assert.Equal(t, get, []string{"1", "2", "3"})
181+
182+
var m2 RWMap[string, string]
183+
assert.Equal(t, len(m2.Keys()), 0)
184+
}

0 commit comments

Comments
 (0)