gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/container/sync-map.go (about) 1 package container 2 3 import ( 4 "gitee.com/sy_183/go-common/maps" 5 "sync" 6 ) 7 8 type SyncMap[K comparable, V any] struct { 9 m sync.Map 10 } 11 12 func (s *SyncMap[K, V]) Load(key K) (value V, ok bool) { 13 var v any 14 v, ok = s.m.Load(key) 15 if ok { 16 value = v.(V) 17 } 18 return 19 } 20 21 func (s *SyncMap[K, V]) Store(key K, value V) { 22 s.m.Store(key, value) 23 } 24 25 func (s *SyncMap[K, V]) LoadOrStore(key K, value V) (actual V, loaded bool) { 26 var v any 27 v, loaded = s.m.LoadOrStore(key, value) 28 if loaded { 29 actual = v.(V) 30 } 31 return 32 } 33 34 func (s *SyncMap[K, V]) LoadAndDelete(key K) (value V, loaded bool) { 35 var v any 36 v, loaded = s.m.LoadAndDelete(key) 37 if loaded { 38 value = v.(V) 39 } 40 return 41 } 42 43 func (s *SyncMap[K, V]) Delete(key K) { 44 s.m.Delete(key) 45 } 46 47 func (s *SyncMap[K, V]) Range(f func(key K, value V) bool) { 48 s.m.Range(func(key, value any) bool { return f(key.(K), value.(V)) }) 49 } 50 51 func (s *SyncMap[K, V]) Map() map[K]V { 52 m := make(map[K]V) 53 s.Range(func(key K, value V) bool { 54 m[key] = value 55 return true 56 }) 57 return m 58 } 59 60 func (s *SyncMap[K, V]) Keys() (keys []K) { 61 s.Range(func(key K, value V) bool { 62 keys = append(keys, key) 63 return true 64 }) 65 return 66 } 67 68 func (s *SyncMap[K, V]) Values() (values []V) { 69 s.Range(func(key K, value V) bool { 70 values = append(values, value) 71 return true 72 }) 73 return 74 } 75 76 func (s *SyncMap[K, V]) Entries() (entries []maps.Entry[K, V]) { 77 s.Range(func(key K, value V) bool { 78 entries = append(entries, maps.NewEntry(key, value)) 79 return true 80 }) 81 return 82 } 83 84 func (s *SyncMap[K, V]) AppendKeys(keys []K) []K { 85 s.Range(func(key K, value V) bool { 86 keys = append(keys, key) 87 return true 88 }) 89 return keys 90 } 91 92 func (s *SyncMap[K, V]) AppendValues(values []V) []V { 93 s.Range(func(key K, value V) bool { 94 values = append(values, value) 95 return true 96 }) 97 return values 98 } 99 100 func (s *SyncMap[K, V]) AppendEntries(entries []maps.Entry[K, V]) []maps.Entry[K, V] { 101 s.Range(func(key K, value V) bool { 102 entries = append(entries, maps.NewEntry(key, value)) 103 return true 104 }) 105 return entries 106 }