|
| 1 | +// A typed, thread-safe map built on top of sync.Map, using generics. |
| 2 | +package syncmap |
| 3 | + |
| 4 | +import "sync" |
| 5 | + |
| 6 | +// SyncMap provides a thread-safe generic map built on top of sync.Map. |
| 7 | +type SyncMap[K comparable, V any] struct { |
| 8 | + m sync.Map |
| 9 | +} |
| 10 | + |
| 11 | +// NewSyncMap creates a new thread-safe generic map |
| 12 | +func NewSyncMap[K comparable, V any]() *SyncMap[K, V] { |
| 13 | + return &SyncMap[K, V]{} |
| 14 | +} |
| 15 | + |
| 16 | +// Store sets a key-value pair |
| 17 | +func (sm *SyncMap[K, V]) Store(key K, value V) { |
| 18 | + sm.m.Store(key, value) |
| 19 | +} |
| 20 | + |
| 21 | +// Load gets a value by key, returns value and whether it was found |
| 22 | +func (sm *SyncMap[K, V]) Load(key K) (V, bool) { |
| 23 | + if val, ok := sm.m.Load(key); ok { |
| 24 | + return val.(V), true |
| 25 | + } |
| 26 | + var zero V |
| 27 | + return zero, false |
| 28 | +} |
| 29 | + |
| 30 | +// LoadOrStore gets existing value or stores new one, returns actual value and whether it was loaded |
| 31 | +func (sm *SyncMap[K, V]) LoadOrStore(key K, value V) (V, bool) { |
| 32 | + actual, loaded := sm.m.LoadOrStore(key, value) |
| 33 | + return actual.(V), loaded |
| 34 | +} |
| 35 | + |
| 36 | +// Delete removes a key |
| 37 | +func (sm *SyncMap[K, V]) Delete(key K) { |
| 38 | + sm.m.Delete(key) |
| 39 | +} |
| 40 | + |
| 41 | +// Range calls fn for each key-value pair. Returning false quits the iteration |
| 42 | +func (sm *SyncMap[K, V]) Range(fn func(key K, value V) bool) { |
| 43 | + sm.m.Range(func(key, value any) bool { |
| 44 | + return fn(key.(K), value.(V)) |
| 45 | + }) |
| 46 | +} |
| 47 | + |
| 48 | +// Keys returns all keys as a slice |
| 49 | +func (sm *SyncMap[K, V]) Keys() []K { |
| 50 | + var keys []K |
| 51 | + sm.Range(func(key K, value V) bool { |
| 52 | + keys = append(keys, key) |
| 53 | + return true |
| 54 | + }) |
| 55 | + return keys |
| 56 | +} |
| 57 | + |
| 58 | +// Values returns all values as a slice |
| 59 | +func (sm *SyncMap[K, V]) Values() []V { |
| 60 | + var values []V |
| 61 | + sm.Range(func(key K, value V) bool { |
| 62 | + values = append(values, value) |
| 63 | + return true |
| 64 | + }) |
| 65 | + return values |
| 66 | +} |
| 67 | + |
| 68 | +// Len returns the number of items (expensive operation) |
| 69 | +func (sm *SyncMap[K, V]) Len() int { |
| 70 | + count := 0 |
| 71 | + sm.Range(func(key K, value V) bool { |
| 72 | + count++ |
| 73 | + return true |
| 74 | + }) |
| 75 | + return count |
| 76 | +} |
0 commit comments