63 lines
863 B
Go
63 lines
863 B
Go
package abstract
|
|
|
|
import (
|
|
"sync"
|
|
"sync/atomic"
|
|
)
|
|
|
|
type IStore[K comparable, T any] interface {
|
|
Load(K) (T, bool)
|
|
Delete(K)
|
|
Store(K, T)
|
|
GetData() map[K]T
|
|
GetUID() int64
|
|
NewUID(int64) int64
|
|
Lock()
|
|
Unlock()
|
|
RLock()
|
|
RUnlock()
|
|
}
|
|
|
|
type Store[K comparable, V any] struct {
|
|
Data map[K]V
|
|
UID atomic.Int64
|
|
sync.RWMutex
|
|
}
|
|
|
|
func (c *Store[K, V]) GetUID() int64 {
|
|
return c.UID.Load()
|
|
}
|
|
|
|
func (c *Store[K, V]) NewUID(i int64) int64 {
|
|
return c.UID.Add(i)
|
|
}
|
|
|
|
func (c *Store[K, V]) GetData() map[K]V {
|
|
return c.Data
|
|
}
|
|
|
|
func (c *Store[K, V]) Load(key K) (V, bool) {
|
|
c.RLock()
|
|
if d, ok := c.Data[key]; ok {
|
|
c.RUnlock()
|
|
return d, true
|
|
}
|
|
c.RUnlock()
|
|
|
|
var empty V
|
|
|
|
return empty, false
|
|
}
|
|
|
|
func (c *Store[K, V]) Store(key K, d V) {
|
|
c.Lock()
|
|
c.Data[key] = d
|
|
c.Unlock()
|
|
}
|
|
|
|
func (c *Store[K, V]) Delete(key K) {
|
|
c.Lock()
|
|
delete(c.Data, key)
|
|
c.Unlock()
|
|
}
|