Skip to content

Commit

Permalink
Use iterators
Browse files Browse the repository at this point in the history
  • Loading branch information
Zamony committed Aug 21, 2024
1 parent ac9b290 commit 041f05f
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 19 deletions.
2 changes: 1 addition & 1 deletion sync/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ SetIf(key K, newValue V, cond Condition) (actual V, ok bool)
Delete(key K)
DeleteIf(key K, cond Condition) bool
Clear()
All(yield func(key K, value V) bool) bool
All() iter.Seq2[K, V]
```

**Safer waitgroup**
Expand Down
2 changes: 1 addition & 1 deletion sync/go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/Zamony/go/sync

go 1.21
go 1.23
23 changes: 13 additions & 10 deletions sync/hatmap/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
// It is implemented as an ordinary map protected by mutex ("mutex hat" idiom).
package hatmap

import "sync"
import (
"iter"
"sync"
)

// Condition to operate on a current value by the given key.
// May be called multiple times.
Expand Down Expand Up @@ -119,15 +122,15 @@ func (m *Map[K, V]) Clear() {
}

// All iterates over a map.
func (m *Map[K, V]) All(yield func(K, V) bool) bool {
m.mu.RLock()
defer m.mu.RUnlock()

for k, v := range m.data {
if !yield(k, v) {
return false
func (m *Map[K, V]) All() iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
m.mu.RLock()
defer m.mu.RUnlock()

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

return true
}
12 changes: 5 additions & 7 deletions sync/hatmap/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,9 @@ func TestMapForEach(t *testing.T) {
m.Set("c", 3)

mit := map[string]int{}
completed := m.All(func(key string, value int) bool {
for key, value := range m.All() {
mit[key] = value
return true
})
equal(t, completed, true)
}
equal(t, mit, map[string]int{
"a": 1,
"b": 2,
Expand Down Expand Up @@ -134,9 +132,9 @@ func TestMapConcurrent(t *testing.T) {
})
})
goGroup(&wg, func() {
m.All(func(string, int) bool {
return true
})
for k, v := range m.All() {
_, _ = k, v
}
})
}
}
Expand Down

0 comments on commit 041f05f

Please sign in to comment.