github.com/Asutorufa/yuhaiin@v0.3.6-0.20240502055049-7984da7023a0/pkg/utils/syncmap/syncmap.go (about) 1 package syncmap 2 3 import ( 4 "sync" 5 ) 6 7 type SyncMap[key, value any] struct { 8 data sync.Map 9 } 10 11 func (a *SyncMap[T1, T2]) Load(key T1) (r T2, _ bool) { 12 v, ok := a.data.Load(key) 13 if !ok { 14 return r, false 15 } 16 return v.(T2), true 17 } 18 19 func (a *SyncMap[T1, T2]) Store(key T1, value T2) { 20 a.data.Store(key, value) 21 } 22 23 func (a *SyncMap[T1, T2]) LoadOrStore(key T1, value T2) (r T2, _ bool) { 24 v, ok := a.data.LoadOrStore(key, value) 25 return v.(T2), ok 26 } 27 28 func (a *SyncMap[T1, T2]) LoadAndDelete(key T1) (r T2, _ bool) { 29 v, ok := a.data.LoadAndDelete(key) 30 if !ok { 31 return r, false 32 } 33 return v.(T2), true 34 } 35 36 func (a *SyncMap[T1, T2]) Delete(key T1) { 37 a.data.Delete(key) 38 } 39 40 func (a *SyncMap[T1, T2]) Range(f func(key T1, value T2) bool) { 41 a.data.Range(func(key, value any) bool { 42 return f(key.(T1), value.(T2)) 43 }) 44 } 45 46 func (a *SyncMap[key, T2]) ValueSlice() (r []T2) { 47 a.data.Range(func(key, value any) bool { 48 r = append(r, value.(T2)) 49 return true 50 }) 51 52 return r 53 }