Compare commits

..

No commits in common. "main" and "v0.0.2" have entirely different histories.
main ... v0.0.2

2 changed files with 11 additions and 38 deletions

4
go.mod
View File

@ -1,3 +1,3 @@
module git.tordarus.net/tordarus/cmap module git.milar.in/milarin/cmap
go 1.24.1 go 1.22.0

45
map.go
View File

@ -1,9 +1,6 @@
package cmap package cmap
import ( import "sync"
"iter"
"sync"
)
// Map represents a map safe for concurrent use // Map represents a map safe for concurrent use
type Map[K comparable, V any] struct { type Map[K comparable, V any] struct {
@ -58,18 +55,15 @@ func (m *Map[K, V]) Count() int {
return len(m.data) return len(m.data)
} }
// Iterate returns a Go iterator to make for-range loops possible. // Iter calls f for every key-value pair stored in m.
// Be aware that the whole map is locked during iteration. // Be aware that this locks m for write access
func (m *Map[K, V]) Iterate() iter.Seq2[K, V] { // as pointer types could be modified in f
return func(yield func(K, V) bool) { func (m *Map[K, V]) Iter(f func(key K, value V)) {
m.mutex.Lock() m.mutex.Lock()
defer m.mutex.Unlock() defer m.mutex.Unlock()
for key, value := range m.data { for key, value := range m.data {
if !yield(key, value) { f(key, value)
return
}
}
} }
} }
@ -107,24 +101,3 @@ func (m *Map[K, V]) Do(f func(m map[K]V)) {
defer m.mutex.Unlock() defer m.mutex.Unlock()
f(m.data) f(m.data)
} }
// DoWithError calls f with the underlying primitive map and returns its error.
// Be aware that this locks m for write access
// so Do can be used for reading as well as modifiying m.
func (m *Map[K, V]) DoWithError(f func(m map[K]V) error) error {
m.mutex.Lock()
defer m.mutex.Unlock()
return f(m.data)
}
// Clone returns a copy of the underlying map data
func (m *Map[K, V]) Clone() map[K]V {
m.mutex.RLock()
defer m.mutex.RUnlock()
c := map[K]V{}
for key, value := range m.data {
c[key] = value
}
return c
}