File size: 1,319 Bytes
6932c8c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | package csync
import (
"iter"
"sync/atomic"
)
// NewVersionedMap creates a new versioned, thread-safe map.
func NewVersionedMap[K comparable, V any]() *VersionedMap[K, V] {
return &VersionedMap[K, V]{
m: NewMap[K, V](),
}
}
// VersionedMap is a thread-safe map that keeps track of its version.
type VersionedMap[K comparable, V any] struct {
m *Map[K, V]
v atomic.Uint64
}
// Get gets the value for the specified key from the map.
func (m *VersionedMap[K, V]) Get(key K) (V, bool) {
return m.m.Get(key)
}
// Set sets the value for the specified key in the map and increments the version.
func (m *VersionedMap[K, V]) Set(key K, value V) {
m.m.Set(key, value)
m.v.Add(1)
}
// Del deletes the specified key from the map and increments the version.
func (m *VersionedMap[K, V]) Del(key K) {
m.m.Del(key)
m.v.Add(1)
}
// Seq2 returns an iter.Seq2 that yields key-value pairs from the map.
func (m *VersionedMap[K, V]) Seq2() iter.Seq2[K, V] {
return m.m.Seq2()
}
// Copy returns a copy of the inner map.
func (m *VersionedMap[K, V]) Copy() map[K]V {
return m.m.Copy()
}
// Len returns the number of items in the map.
func (m *VersionedMap[K, V]) Len() int {
return m.m.Len()
}
// Version returns the current version of the map.
func (m *VersionedMap[K, V]) Version() uint64 {
return m.v.Load()
}
|