diff --git a/README.md b/README.md index 9eea0f0..3c37024 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # gstl -支持泛型的数据结构库 +支持泛型的数据结构库 [![Go](https://github.com/antlabs/gstl/workflows/Go/badge.svg)](https://github.com/antlabs/gstl/actions) [![codecov](https://codecov.io/gh/antlabs/gstl/branch/master/graph/badge.svg)](https://codecov.io/gh/antlabs/gstl) @@ -179,4 +179,6 @@ for pair := range m.Iter() { } m.Len()// 获取长度 +allKeys := m.Keys() //返回所有的key +allValues := m.Values()// 返回所有的value ``` diff --git a/rwmap/rwmap.go b/rwmap/rwmap.go index aefe5bf..4ee9723 100644 --- a/rwmap/rwmap.go +++ b/rwmap/rwmap.go @@ -2,7 +2,11 @@ package rwmap -import "sync" +import ( + "sync" + + "github.com/antlabs/gstl/mapex" +) type RWMap[K comparable, V any] struct { rw sync.RWMutex @@ -100,6 +104,32 @@ func (r *RWMap[K, V]) Store(key K, value V) { r.rw.Unlock() } +// keys +func (r *RWMap[K, V]) Keys() (keys []K) { + + r.rw.RLock() + if r.m == nil { + r.rw.RUnlock() + return + } + keys = mapex.Keys(r.m) + r.rw.RUnlock() + return keys +} + +// vals +func (r *RWMap[K, V]) Values() (values []V) { + + r.rw.RLock() + if r.m == nil { + r.rw.RUnlock() + return + } + values = mapex.Values(r.m) + r.rw.RUnlock() + return values +} + // 返回长度 func (r *RWMap[K, V]) Len() (l int) { r.rw.RLock() diff --git a/rwmap/rwmap_test.go b/rwmap/rwmap_test.go index 4be6913..5c351d4 100644 --- a/rwmap/rwmap_test.go +++ b/rwmap/rwmap_test.go @@ -156,3 +156,29 @@ func Test_New(t *testing.T) { m.Store("3", "3") assert.Equal(t, m.Len(), 3) } + +func Test_Keys(t *testing.T) { + m := New[string, string](3) + m.Store("a", "1") + m.Store("b", "2") + m.Store("c", "3") + get := m.Keys() + sort.Strings(get) + assert.Equal(t, get, []string{"a", "b", "c"}) + + var m2 RWMap[string, string] + assert.Equal(t, len(m2.Values()), 0) +} + +func Test_Values(t *testing.T) { + m := New[string, string](3) + m.Store("a", "1") + m.Store("b", "2") + m.Store("c", "3") + get := m.Values() + sort.Strings(get) + assert.Equal(t, get, []string{"1", "2", "3"}) + + var m2 RWMap[string, string] + assert.Equal(t, len(m2.Keys()), 0) +}