package pkg import "sync" // SafeMap is a type-safe wrapper around sync.Map type SafeMap[K comparable, V any] struct { m sync.Map } // Store sets the value for a key. func (t *SafeMap[K, V]) Store(key K, value V) { t.m.Store(key, value) } // Load returns the value for a key, and whether the key was found. func (t *SafeMap[K, V]) Load(key K) (V, bool) { value, ok := t.m.Load(key) if !ok { var zero V return zero, false } return value.(V), true } // LoadOrStore returns the existing value for the key if present. // Otherwise, it stores and returns the given value. func (t *SafeMap[K, V]) LoadOrStore(key K, value V) (V, bool) { actual, loaded := t.m.LoadOrStore(key, value) return actual.(V), loaded } // Delete removes the key and its value from the map. func (t *SafeMap[K, V]) Delete(key K) { t.m.Delete(key) } // Range iterates over all key-value pairs in the map. func (t *SafeMap[K, V]) Range(f func(key K, value V) bool) { t.m.Range(func(key, value interface{}) bool { return f(key.(K), value.(V)) }) }