versionedmap.go 1.2 KB

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