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