Skip to content

Commit

Permalink
Merge pull request #4 from antlabs/rwmap-ex
Browse files Browse the repository at this point in the history
rwmap加上Keys, Values函数
  • Loading branch information
guonaihong authored Nov 9, 2022
2 parents dbc00b4 + 6f25492 commit 2c3b87b
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 2 deletions.
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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)

Expand Down Expand Up @@ -179,4 +179,6 @@ for pair := range m.Iter() {
}

m.Len()// 获取长度
allKeys := m.Keys() //返回所有的key
allValues := m.Values()// 返回所有的value
```
32 changes: 31 additions & 1 deletion rwmap/rwmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down
26 changes: 26 additions & 0 deletions rwmap/rwmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

0 comments on commit 2c3b87b

Please sign in to comment.