github.com/kaiya/goutils@v1.0.1-0.20230226104005-4ae4a4dc3688/cmap/cmap.go (about) 1 package cmap 2 3 import ( 4 "fmt" 5 "reflect" 6 "sync" 7 ) 8 9 type ConcurrentMap struct { 10 m sync.Map 11 keyType reflect.Type 12 valueType reflect.Type 13 } 14 15 func NewConcurrentMap(keyTyp, valueTyp reflect.Type) *ConcurrentMap { 16 return &ConcurrentMap{ 17 keyType: keyTyp, 18 valueType: valueTyp, 19 } 20 } 21 22 func (cm *ConcurrentMap) Load(key interface{}) (value interface{}, ok bool) { 23 if reflect.TypeOf(key) != cm.keyType { 24 return 25 } 26 return cm.m.Load(key) 27 } 28 29 func (cm *ConcurrentMap) Store(key, value interface{}) { 30 if reflect.TypeOf(key) != cm.keyType { 31 panic(fmt.Errorf("wrong key type: %v", reflect.TypeOf(key))) 32 } 33 if reflect.TypeOf(value) != cm.valueType { 34 panic(fmt.Errorf("wrong value type: %v", reflect.TypeOf(value))) 35 } 36 cm.m.Store(key, value) 37 }