package q5 import ( "sync" "sync/atomic" ) type ConcurrentMap[T1 string | int | int32 | int64, T2 any] struct { kvHash sync.Map } func (this *ConcurrentMap[T1, T2]) CompareAndDelete(key T1, old *T2) bool { return this.kvHash.CompareAndDelete(key, old) } func (this *ConcurrentMap[T1, T2]) CompareAndSwap(key T1, old T2, new T2) bool { return this.kvHash.CompareAndSwap(key, old, new) } func (this *ConcurrentMap[T1, T2]) Delete(key T1) { this.kvHash.Delete(key) } func (this *ConcurrentMap[T1, T2]) Load(key T1) (*T2, bool) { value, ok := this.kvHash.Load(key) if ok { tmpValue := value.(T2) return &tmpValue, ok } else { return nil, ok } } func (this *ConcurrentMap[T1, T2]) LoadAndDelete(key T1) (*T2, bool) { value, loaded := this.kvHash.LoadAndDelete(key) if loaded { tmpValue := value.(T2) return &tmpValue, loaded } else { return nil, loaded } } func (this *ConcurrentMap[T1, T2]) LoadOrStore(key T1, value T2) (*T2, bool) { actual, loaded := this.kvHash.LoadOrStore(key, value) if loaded { tmpActual := actual.(T2) return &tmpActual, loaded } else { return nil, loaded } } func (this *ConcurrentMap[T1, T2]) Range(f func(key T1, value T2) bool) { this.kvHash.Range(func (key, value interface{}) bool { return f(key.(T1), value.(T2)) }) } func (this *ConcurrentMap[T1, T2]) GetSize() int { var size int this.kvHash.Range(func (key, value interface{}) bool { size += 1 return true }) return size } func (this *ConcurrentMap[T1, T2]) Store(key T1, value T2) { this.kvHash.Store(key, value) } func (this *ConcurrentMap[T1, T2]) Swap(key T1, value T2) (*T2, bool) { previous, loaded := this.kvHash.Swap(key, value) if loaded { tmpPrevious := previous.(T2) return &tmpPrevious, loaded } else { return nil, loaded } } func AtomicStoreInt64WhenGreater(srcVal *int64, trgVal *int64) { tmpVal := atomic.LoadInt64(srcVal) if tmpVal > *trgVal { atomic.StoreInt64(trgVal, tmpVal) } }