Files
2026-11-07 10:47:32 +08:00

87 lines
1.4 KiB
Go

package lock
import (
"sync"
)
type IIdent interface {
GetID() int64
}
type Cache[T IIdent] struct {
dict map[int64]T
lock sync.RWMutex
}
func NewCache[T IIdent]() *Cache[T] {
return &Cache[T]{
dict: make(map[int64]T),
}
}
func (c *Cache[T]) Get(Id int64) (T, bool) {
c.lock.RLock()
defer c.lock.RUnlock()
t, ok := c.dict[Id]
return t, ok
}
func (c *Cache[T]) Keys() []int64 {
c.lock.RLock()
defer c.lock.RUnlock()
keys := make([]int64, 0, len(c.dict))
for k := range c.dict {
keys = append(keys, k)
}
return keys
}
func (c *Cache[T]) Set(items ...T) {
c.lock.Lock()
defer c.lock.Unlock()
for _, item := range items {
c.dict[item.GetID()] = item
}
}
func (c *Cache[T]) Del(items ...T) {
c.lock.Lock()
defer c.lock.Unlock()
for _, item := range items {
delete(c.dict, item.GetID())
}
}
func (c *Cache[T]) Update(dict map[int64]T) {
c.lock.Lock()
defer c.lock.Unlock()
c.dict = dict
}
func (c *Cache[T]) SetItems(items []T) {
c.lock.Lock()
defer c.lock.Unlock()
for _, item := range items {
c.dict[item.GetID()] = item
}
}
func (c *Cache[T]) Has(Id int64) bool {
c.lock.RLock()
defer c.lock.RUnlock()
_, ok := c.dict[Id]
return ok
}
func (c *Cache[T]) GetItems(Ids []int64) []T {
ret := make([]T, 0)
c.lock.RLock()
defer c.lock.RUnlock()
for _, id := range Ids {
if item, ok := c.dict[id]; ok {
ret = append(ret, item)
}
}
return ret
}