sync.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package mapping
  2. import (
  3. "sync"
  4. "sync/atomic"
  5. )
  6. type Map[K comparable, V any] struct {
  7. len int32
  8. store sync.Map
  9. mu sync.RWMutex
  10. }
  11. func (m *Map[K, V]) Load(key K) (value V, ok bool) {
  12. m.mu.RLock()
  13. defer m.mu.RUnlock()
  14. v, ok := m.store.Load(key)
  15. if !ok {
  16. return
  17. }
  18. value, ok = v.(V)
  19. return
  20. }
  21. func (m *Map[K, V]) Store(key K, value V) {
  22. m.mu.Lock()
  23. defer m.mu.Unlock()
  24. // If the key already exists, we don't want to increment the length
  25. _, loaded := m.store.Load(key)
  26. if !loaded {
  27. atomic.AddInt32(&m.len, 1)
  28. }
  29. m.store.Store(key, value)
  30. }
  31. func (m *Map[K, V]) Delete(key K) {
  32. m.mu.Lock()
  33. defer m.mu.Unlock()
  34. _, loaded := m.store.Load(key)
  35. // If the key exists, we want to decrement the length
  36. // If the key does not exist, we don't want to decrement the length
  37. if loaded {
  38. atomic.AddInt32(&m.len, -1)
  39. }
  40. m.store.Delete(key)
  41. }
  42. func (m *Map[K, V]) Range(f func(key K, value V) bool) {
  43. m.store.Range(func(key, value interface{}) bool {
  44. return f(key.(K), value.(V))
  45. })
  46. }
  47. func (m *Map[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) {
  48. m.mu.Lock()
  49. defer m.mu.Unlock()
  50. v, loaded := m.store.LoadOrStore(key, value)
  51. actual = v.(V)
  52. if !loaded {
  53. atomic.AddInt32(&m.len, 1)
  54. }
  55. return
  56. }
  57. func (m *Map[K, V]) LoadAndDelete(key K) (value V, loaded bool) {
  58. m.mu.Lock()
  59. defer m.mu.Unlock()
  60. v, loaded := m.store.LoadAndDelete(key)
  61. value = v.(V)
  62. if loaded {
  63. atomic.AddInt32(&m.len, -1)
  64. }
  65. return
  66. }
  67. func (m *Map[K, V]) Swap(key K, value V) (actual V, swapped bool) {
  68. m.mu.Lock()
  69. defer m.mu.Unlock()
  70. v, swapped := m.store.Swap(key, value)
  71. actual = v.(V)
  72. return
  73. }
  74. func (m *Map[K, V]) Clear() {
  75. m.mu.Lock()
  76. defer m.mu.Unlock()
  77. // Clear the map
  78. m.store.Range(func(key, value interface{}) bool {
  79. m.store.Delete(key)
  80. return true
  81. })
  82. atomic.StoreInt32(&m.len, 0)
  83. }
  84. func (m *Map[K, V]) Len() int {
  85. return int(atomic.LoadInt32(&m.len))
  86. }
  87. func (m *Map[K, V]) Exists(key K) bool {
  88. _, ok := m.Load(key)
  89. return ok
  90. }