1package csync
2
3import (
4 "sync/atomic"
5)
6
7// NewVersionedMap creates a new versioned, thread-safe map.
8func NewVersionedMap[K comparable, V any]() *VersionedMap[K, V] {
9 return &VersionedMap[K, V]{
10 Map: NewMap[K, V](),
11 }
12}
13
14// VersionedMap is a thread-safe map that keeps track of its version.
15type VersionedMap[K comparable, V any] struct {
16 *Map[K, V]
17 v atomic.Uint64
18}
19
20// Set sets the value for the specified key in the map and increments the version.
21func (m *VersionedMap[K, V]) Set(key K, value V) {
22 m.Map.Set(key, value)
23 m.v.Add(1)
24}
25
26// Del deletes the specified key from the map and increments the version.
27func (m *VersionedMap[K, V]) Del(key K) {
28 m.Map.Del(key)
29 m.v.Add(1)
30}
31
32// Version returns the current version of the map.
33func (m *VersionedMap[K, V]) Version() uint64 {
34 return m.v.Load()
35}