108 lines
1.8 KiB
Go
108 lines
1.8 KiB
Go
package inmemory
|
|
|
|
import (
|
|
"log/slog"
|
|
"sync/atomic"
|
|
"unsafe"
|
|
)
|
|
|
|
type Cache[K comparable, V any] interface {
|
|
Name() string
|
|
GetAll() map[K]V
|
|
GetList() []V
|
|
Get(key K) (value V, ok bool)
|
|
Find(predicate func(K, V) bool) []V
|
|
}
|
|
|
|
type CopyAndWriteCache[K comparable, V any] struct {
|
|
name string
|
|
data unsafe.Pointer
|
|
}
|
|
|
|
func NewCopyAndWriteCache[K comparable, V any](
|
|
name string,
|
|
) *CopyAndWriteCache[K, V] {
|
|
c := CopyAndWriteCache[K, V]{
|
|
name: name,
|
|
}
|
|
|
|
emptyMap := make(map[K]V)
|
|
atomic.StorePointer(&c.data, unsafe.Pointer(&emptyMap))
|
|
|
|
slog.Info("cache initialized", "name", name)
|
|
|
|
return &c
|
|
}
|
|
|
|
func (c *CopyAndWriteCache[K, V]) Name() string {
|
|
return c.name
|
|
}
|
|
|
|
func (c *CopyAndWriteCache[K, V]) GetAll() map[K]V {
|
|
ptr := atomic.LoadPointer(&c.data)
|
|
if ptr == nil {
|
|
return make(map[K]V)
|
|
}
|
|
|
|
m := *(*map[K]V)(ptr)
|
|
|
|
out := make(map[K]V, len(m))
|
|
for k, v := range m {
|
|
out[k] = v
|
|
}
|
|
return out
|
|
}
|
|
|
|
func (c *CopyAndWriteCache[K, V]) GetList() []V {
|
|
records := c.GetAll()
|
|
out := make([]V, 0, len(records))
|
|
for _, record := range records {
|
|
out = append(out, record)
|
|
}
|
|
|
|
return out
|
|
}
|
|
|
|
func (c *CopyAndWriteCache[K, V]) Get(key K) (value V, ok bool) {
|
|
ptr := atomic.LoadPointer(&c.data)
|
|
if ptr == nil {
|
|
var zero V
|
|
return zero, false
|
|
}
|
|
|
|
m := *(*map[K]V)(ptr)
|
|
v, ok := m[key]
|
|
return v, ok
|
|
}
|
|
|
|
func (c *CopyAndWriteCache[K, V]) Find(predicate func(K, V) bool) []V {
|
|
ptr := atomic.LoadPointer(&c.data)
|
|
if ptr == nil {
|
|
return []V{}
|
|
}
|
|
|
|
m := *(*map[K]V)(ptr)
|
|
|
|
var result []V
|
|
for key, value := range m {
|
|
if predicate(key, value) {
|
|
result = append(result, value)
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
func (c *CopyAndWriteCache[K, V]) Store(key K, value V) bool {
|
|
ptr := atomic.LoadPointer(&c.data)
|
|
if ptr == nil {
|
|
return false
|
|
}
|
|
|
|
m := *(*map[K]V)(ptr)
|
|
|
|
m[key] = value
|
|
|
|
return true
|
|
}
|