Skip to content

Commit

Permalink
Merge pull request #39 from KyberNetwork/feat/x/syncmap/range-and-keys
Browse files Browse the repository at this point in the history
feat: ✨ x/syncmap: add Range and Keys
  • Loading branch information
thanhpp authored Apr 11, 2024
2 parents 6287762 + 5dd1e55 commit a16bfed
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 10 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/flashbots/mev-share-node v0.0.0-20230926173018-7862d944990a
github.com/golang-migrate/migrate/v4 v4.17.0
github.com/google/uuid v1.4.0
github.com/holiman/uint256 v1.2.4
github.com/jmoiron/sqlx v1.3.5
github.com/shopspring/decimal v1.3.1
github.com/sourcegraph/conc v0.3.0
Expand Down Expand Up @@ -37,7 +38,6 @@ require (
github.com/gorilla/websocket v1.4.2 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
github.com/holiman/uint256 v1.2.4 // indirect
github.com/huin/goupnp v1.3.0 // indirect
github.com/jackpal/go-nat-pmp v1.0.2 // indirect
github.com/lib/pq v1.10.9 // indirect
Expand Down
42 changes: 33 additions & 9 deletions x/syncmap/syncmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import "sync"

type SyncMap[K comparable, V any] struct {
data map[K]V
l sync.RWMutex
rw sync.RWMutex
}

func New[K comparable, V any]() SyncMap[K, V] {
Expand All @@ -14,20 +14,20 @@ func New[K comparable, V any]() SyncMap[K, V] {
}

func (m *SyncMap[K, V]) Store(k K, v V) {
m.l.Lock()
defer m.l.Unlock()
m.rw.Lock()
defer m.rw.Unlock()
m.data[k] = v
}

func (m *SyncMap[K, V]) Delete(k K) {
m.l.Lock()
defer m.l.Unlock()
m.rw.Lock()
defer m.rw.Unlock()
delete(m.data, k)
}

func (m *SyncMap[K, V]) Update(k K, fn func(V) (V, error)) (bool, error) {
m.l.Lock()
defer m.l.Unlock()
m.rw.Lock()
defer m.rw.Unlock()

v, ok := m.data[k]
if !ok {
Expand All @@ -45,8 +45,32 @@ func (m *SyncMap[K, V]) Update(k K, fn func(V) (V, error)) (bool, error) {
}

func (m *SyncMap[K, V]) Load(k K) (v V, ok bool) {
m.l.RLock()
defer m.l.RUnlock()
m.rw.RLock()
defer m.rw.RUnlock()
v, ok = m.data[k]
return v, ok
}

func (m *SyncMap[K, V]) Keys() []K {
m.rw.RLock()
defer m.rw.RUnlock()

keys := make([]K, 0, len(m.data))

for k := range m.data {
keys = append(keys, k)
}

return keys
}

func (m *SyncMap[K, V]) RangeMut(fn func(k K, v V) bool) {
m.rw.Lock()
defer m.rw.Unlock()

for k, v := range m.data {
if !fn(k, v) {
break
}
}
}

0 comments on commit a16bfed

Please sign in to comment.