Compare commits
3 Commits
Author | SHA1 | Date | |
---|---|---|---|
bfe23f53e2 | |||
f5f1228e44 | |||
![]() |
a0c89117d9 |
4
go.mod
4
go.mod
@ -1,3 +1,3 @@
|
|||||||
module git.milar.in/milarin/cmap
|
module git.tordarus.net/tordarus/cmap
|
||||||
|
|
||||||
go 1.22.0
|
go 1.24.1
|
||||||
|
45
map.go
45
map.go
@ -1,6 +1,9 @@
|
|||||||
package cmap
|
package cmap
|
||||||
|
|
||||||
import "sync"
|
import (
|
||||||
|
"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 {
|
||||||
@ -55,15 +58,18 @@ func (m *Map[K, V]) Count() int {
|
|||||||
return len(m.data)
|
return len(m.data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iter calls f for every key-value pair stored in m.
|
// Iterate returns a Go iterator to make for-range loops possible.
|
||||||
// Be aware that this locks m for write access
|
// Be aware that the whole map is locked during iteration.
|
||||||
// as pointer types could be modified in f
|
func (m *Map[K, V]) Iterate() iter.Seq2[K, V] {
|
||||||
func (m *Map[K, V]) Iter(f func(key K, value V)) {
|
return func(yield func(K, V) bool) {
|
||||||
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 {
|
||||||
f(key, value)
|
if !yield(key, value) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -101,3 +107,24 @@ 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
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user