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