This commit is contained in:
2022-12-22 10:06:25 +01:00
parent d4994b8c8d
commit 1aaad66233
3 changed files with 32 additions and 42 deletions

View File

@@ -19,40 +19,38 @@ import (
// There are also a bunch of unit tests to ensure that the cache is always in a consistent state
//
type LRUData interface{}
type LRUMap struct {
type LRUMap[TData any] struct {
maxsize int
lock sync.Mutex
cache map[string]*cacheNode
cache map[string]*cacheNode[TData]
lfuHead *cacheNode
lfuTail *cacheNode
lfuHead *cacheNode[TData]
lfuTail *cacheNode[TData]
}
type cacheNode struct {
type cacheNode[TData any] struct {
key string
data LRUData
parent *cacheNode
child *cacheNode
data TData
parent *cacheNode[TData]
child *cacheNode[TData]
}
func NewLRUMap(size int) *LRUMap {
func NewLRUMap[TData any](size int) *LRUMap[TData] {
if size <= 2 && size != 0 {
panic("Size must be > 2 (or 0)")
}
return &LRUMap{
return &LRUMap[TData]{
maxsize: size,
lock: sync.Mutex{},
cache: make(map[string]*cacheNode, size+1),
cache: make(map[string]*cacheNode[TData], size+1),
lfuHead: nil,
lfuTail: nil,
}
}
func (c *LRUMap) Put(key string, value LRUData) {
func (c *LRUMap[TData]) Put(key string, value TData) {
if c.maxsize == 0 {
return // cache disabled
}
@@ -70,7 +68,7 @@ func (c *LRUMap) Put(key string, value LRUData) {
}
// key does not exist: insert into map and add to top of LFU
node = &cacheNode{
node = &cacheNode[TData]{
key: key,
data: value,
parent: nil,
@@ -95,9 +93,9 @@ func (c *LRUMap) Put(key string, value LRUData) {
}
}
func (c *LRUMap) TryGet(key string) (LRUData, bool) {
func (c *LRUMap[TData]) TryGet(key string) (TData, bool) {
if c.maxsize == 0 {
return nil, false // cache disabled
return *new(TData), false // cache disabled
}
c.lock.Lock()
@@ -105,13 +103,13 @@ func (c *LRUMap) TryGet(key string) (LRUData, bool) {
val, ok := c.cache[key]
if !ok {
return nil, false
return *new(TData), false
}
c.moveNodeToTop(val)
return val.data, ok
}
func (c *LRUMap) moveNodeToTop(node *cacheNode) {
func (c *LRUMap[TData]) moveNodeToTop(node *cacheNode[TData]) {
// (only called in critical section !)
if c.lfuHead == node { // fast case
@@ -144,7 +142,7 @@ func (c *LRUMap) moveNodeToTop(node *cacheNode) {
}
}
func (c *LRUMap) Size() int {
func (c *LRUMap[TData]) Size() int {
c.lock.Lock()
defer c.lock.Unlock()
return len(c.cache)