From 35b1506d457a62f85549e54f4d9e9ab2b16cad11 Mon Sep 17 00:00:00 2001 From: Nikita Mochalov Date: Wed, 21 Aug 2024 13:49:04 +0300 Subject: [PATCH] Use iterators --- sync/go.mod | 2 +- sync/hatmap/map.go | 23 +++++++++++++---------- sync/hatmap/map_test.go | 12 +++++------- 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/sync/go.mod b/sync/go.mod index 44b97f4..5787d93 100644 --- a/sync/go.mod +++ b/sync/go.mod @@ -1,3 +1,3 @@ module github.com/Zamony/go/sync -go 1.21 +go 1.23 diff --git a/sync/hatmap/map.go b/sync/hatmap/map.go index 52b033a..23d9154 100644 --- a/sync/hatmap/map.go +++ b/sync/hatmap/map.go @@ -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. @@ -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 } diff --git a/sync/hatmap/map_test.go b/sync/hatmap/map_test.go index aa871b4..b2830c9 100644 --- a/sync/hatmap/map_test.go +++ b/sync/hatmap/map_test.go @@ -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, @@ -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 + } }) } }