github.com/m4gshm/gollections@v0.0.13-0.20240331203319-a34a86e58a24/collection/mutable/sync/map.go (about) 1 // Package sync provides parametrized Map implementation 2 package sync 3 4 import ( 5 "sync" 6 7 "github.com/m4gshm/gollections/c" 8 ) 9 10 // NewMap sync Map constructor 11 func NewMap[K comparable, V any]() Map[K, V] { 12 return Map[K, V]{} 13 } 14 15 // Map is typed wrapper of sync.Map 16 type Map[K comparable, V any] struct { 17 m sync.Map 18 } 19 20 var ( 21 _ c.Settable[int, any] = (*Map[int, any])(nil) 22 _ c.Deleteable[int] = (*Map[int, any])(nil) 23 _ c.Removable[int, any] = (*Map[int, any])(nil) 24 _ c.TrackEach[int, any] = (*Map[int, any])(nil) 25 _ c.Access[int, any] = (*Map[int, any])(nil) 26 ) 27 28 // TrackEach applies the 'consumer' function for every key/value pairs 29 func (m *Map[K, V]) TrackEach(traker func(key K, value V)) { 30 m.m.Range(func(key, value any) bool { 31 traker(key.(K), value.(V)) 32 return true 33 }) 34 } 35 36 // Set sets the value for a key 37 func (m *Map[K, V]) Set(key K, value V) { 38 m.m.Store(key, value) 39 } 40 41 // Get returns the value for a key. 42 // If ok==false, then the map does not contain the key. 43 func (m *Map[K, V]) Get(key K) (V, bool) { 44 value, ok := m.m.Load(key) 45 return value.(V), ok 46 } 47 48 // Delete removes value by their keys from the map 49 func (m *Map[K, V]) Delete(keys ...K) { 50 for _, key := range keys { 51 m.m.Delete(key) 52 } 53 } 54 55 // DeleteOne removes an value by the key from the map 56 func (m *Map[K, V]) DeleteOne(key K) { 57 m.m.Delete(key) 58 } 59 60 // Remove removes value by key and return it 61 func (m *Map[K, V]) Remove(key K) (V, bool) { 62 rawVal, ok := m.m.LoadAndDelete(key) 63 return rawVal.(V), ok 64 }