versionedmap.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // Copy returns a copy of the inner map.
  36. func (m *VersionedMap[K, V]) Copy() map[K]V {
  37. return m.m.Copy()
  38. }
  39. // Len returns the number of items in the map.
  40. func (m *VersionedMap[K, V]) Len() int {
  41. return m.m.Len()
  42. }
  43. // Version returns the current version of the map.
  44. func (m *VersionedMap[K, V]) Version() uint64 {
  45. return m.v.Load()
  46. }