syncmap-range.patch

· erock's pastes · raw

expires: 2024-12-25

 1From 375f187c63ade964e87eb179ae10b9bea3800f67 Mon Sep 17 00:00:00 2001
 2From: Eric Bower <me@erock.io>
 3Date: Wed, 25 Sep 2024 23:42:29 -0400
 4Subject: [PATCH] refactor(range): use `iter` pkg
 5
 6Having `Range` return an iterator makes it so we can `range` over it
 7like a slice which provides us with better flow control (e.g. `break`,
 8`continue`, and `return`.
 9---
10 go.mod          |  2 +-
11 syncmap.go      | 19 +++++++++++--------
12 syncmap_test.go |  8 +++-----
13 3 files changed, 15 insertions(+), 14 deletions(-)
14
15diff --git a/go.mod b/go.mod
16index 1539c26..9b97f97 100644
17--- a/go.mod
18+++ b/go.mod
19@@ -1,3 +1,3 @@
20 module github.com/antoniomika/syncmap
21 
22-go 1.18
23+go 1.23
24diff --git a/syncmap.go b/syncmap.go
25index 2978dac..025158b 100644
26--- a/syncmap.go
27+++ b/syncmap.go
28@@ -2,6 +2,7 @@
29 package syncmap
30 
31 import (
32+	"iter"
33 	"sync"
34 )
35 
36@@ -61,14 +62,16 @@ func (m *Map[K, V]) Store(I K, J V) {
37 }
38 
39 // Range will iterate over the data in the Map and apply the func on it.
40-func (m *Map[K, V]) Range(L func(I K, J V) bool) {
41-	m.ds.Range(func(A, B any) bool {
42-		var C K
43-		var D V
44+func (m *Map[K, V]) Range() iter.Seq2[K, V] {
45+	return func(yield func(K, V) bool) {
46+		m.ds.Range(func(A, B any) bool {
47+			var C K
48+			var D V
49 
50-		C, _ = A.(K)
51-		D, _ = B.(V)
52+			C, _ = A.(K)
53+			D, _ = B.(V)
54 
55-		return L(C, D)
56-	})
57+			return yield(C, D)
58+		})
59+	}
60 }
61diff --git a/syncmap_test.go b/syncmap_test.go
62index b9b8a9e..11c046c 100644
63--- a/syncmap_test.go
64+++ b/syncmap_test.go
65@@ -91,15 +91,13 @@ func TestRange(t *testing.T) {
66 	testMap.Store("foo", "bar")
67 	testMap.Store("baz", "buz")
68 
69-	testMap.Range(func(a, b string) bool {
70+	for a, b := range testMap.Range() {
71 		if a == "foo" || a == "baz" {
72 			if b == "bar" || b == "buz" {
73-				return true
74+				continue
75 			}
76 		}
77 
78 		t.Error("expected range data")
79-
80-		return true
81-	})
82+	}
83 }
84-- 
852.45.2
86