Compare commits

...

4 Commits
v0.0.1 ... main

Author SHA1 Message Date
bfe23f53e2 updated Go version and edited Iter() function to use the newly added iterator syntax 2025-03-24 17:20:30 +01:00
f5f1228e44 Update go.mod 2024-12-16 19:42:22 +01:00
Milarin
a0c89117d9 added DoWithError and Clone methods 2024-07-31 23:33:50 +02:00
Milarin
4b810c6ffb removed DoUnsafe 2024-02-15 16:38:27 +01:00
2 changed files with 34 additions and 23 deletions

4
go.mod
View File

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

53
map.go
View File

@ -1,6 +1,9 @@
package cmap
import "sync"
import (
"iter"
"sync"
)
// Map represents a map safe for concurrent use
type Map[K comparable, V any] struct {
@ -55,15 +58,18 @@ func (m *Map[K, V]) Count() int {
return len(m.data)
}
// Iter calls f for every key-value pair stored in m.
// Be aware that this locks m for write access
// as pointer types could be modified in f
func (m *Map[K, V]) Iter(f func(key K, value V)) {
m.mutex.Lock()
defer m.mutex.Unlock()
// Iterate returns a Go iterator to make for-range loops possible.
// Be aware that the whole map is locked during iteration.
func (m *Map[K, V]) Iterate() iter.Seq2[K, V] {
return func(yield func(K, V) bool) {
m.mutex.Lock()
defer m.mutex.Unlock()
for key, value := range m.data {
f(key, value)
for key, value := range m.data {
if !yield(key, value) {
return
}
}
}
}
@ -96,24 +102,29 @@ func (m *Map[K, V]) Values() []V {
// Do calls f with the underlying primitive map.
// Be aware that this locks m for write access
// so Do can be used for reading as well as modifiying m.
// After f returns, the map will be shallow-copied in order to prevent
// clueless programmers from storing the map and modifying it afterwards.
// If you need that little bit of optimization, use DoUnsafe instead
func (m *Map[K, V]) Do(f func(m map[K]V)) {
m.mutex.Lock()
defer m.mutex.Unlock()
f(m.data)
nm := map[K]V{}
for key, value := range m.data {
nm[key] = value
}
m.data = nm
}
// DoUnsafe behaves like Do but does not create a shallow-copy of m
func (m *Map[K, V]) DoUnsafe(f func(m map[K]V)) {
// 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()
f(m.data)
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
}