Skip to content

Commit 2006335

Browse files
committed
add yield for sync map && slice
1 parent 91fd4ae commit 2006335

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

data.go

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,10 @@
55

66
package syncing
77

8-
import "sync"
8+
import (
9+
"iter"
10+
"sync"
11+
)
912

1013
type Map[K comparable, V any] struct {
1114
data map[K]V
@@ -77,7 +80,19 @@ func (v *Map[K, V]) Reset() {
7780
for key := range v.data {
7881
delete(v.data, key)
7982
}
80-
return
83+
}
84+
85+
func (v *Map[K, V]) Yield() iter.Seq2[K, V] {
86+
keys := v.Keys()
87+
return func(yield func(K, V) bool) {
88+
for _, key := range keys {
89+
if val, ok := v.Get(key); ok {
90+
if !yield(key, val) {
91+
return
92+
}
93+
}
94+
}
95+
}
8196
}
8297

8398
//-----------------------------------------------------------------------------------------------
@@ -101,6 +116,13 @@ func (v *Slice[V]) Size() int {
101116
return len(v.data)
102117
}
103118

119+
func (v *Slice[V]) Reset() {
120+
v.mux.Lock()
121+
defer v.mux.Unlock()
122+
123+
v.data = v.data[:0]
124+
}
125+
104126
func (v *Slice[V]) Append(val ...V) {
105127
v.mux.Lock()
106128
defer v.mux.Unlock()
@@ -117,3 +139,28 @@ func (v *Slice[V]) Extract() []V {
117139
v.data = v.data[:0]
118140
return tmp
119141
}
142+
143+
func (v *Slice[V]) Index(i int) (V, bool) {
144+
v.mux.RLock()
145+
defer v.mux.RUnlock()
146+
147+
if i >= len(v.data) {
148+
var empty V
149+
return empty, false
150+
}
151+
152+
return v.data[i], true
153+
}
154+
155+
func (v *Slice[V]) Yield() iter.Seq[V] {
156+
var i int
157+
return func(yield func(V) bool) {
158+
for {
159+
if val, ok := v.Index(i); ok {
160+
if !yield(val) {
161+
return
162+
}
163+
}
164+
}
165+
}
166+
}

0 commit comments

Comments
 (0)