Documentation ¶
Overview ¶
Package cache provides an implementation of a key-value store with a maximum size. Once the maximum size is reached, the cache uses a least-recently-used policy to evict old entries. The cache is implemented as a combined hashmap and linked list. This ensures all operations are constant-time.
Example ¶
package main import ( "fmt" "github.com/zyedidia/generic/cache" ) func main() { c := cache.New[int, int](2) c.Put(42, 42) c.Put(10, 10) c.Get(42) c.Put(0, 0) // evicts 10 c.Each(func(key int, val int) { fmt.Println(key) }) }
Output: 0 42
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[K comparable, V any] struct { // contains filtered or unexported fields }
A Cache is an LRU cache for keys and values. Each entry is put into the table with an associated key used for looking up the entry. The cache has a maximum size, and uses a least-recently-used eviction policy when there is not space for a new entry.
func New ¶
func New[K comparable, V any](capacity int) *Cache[K, V]
New returns a new Cache with the given capacity.
func (*Cache[K, V]) Each ¶
func (t *Cache[K, V]) Each(fn func(key K, val V))
Each calls 'fn' on every value in the cache, from most recently used to least recently used.
func (*Cache[K, V]) Get ¶
Get returns the entry associated with a given key, and a boolean indicating whether the key exists in the table.
func (*Cache[K, V]) Put ¶
func (t *Cache[K, V]) Put(k K, e V)
Put adds a new key-entry pair to the table.
func (*Cache[K, V]) Remove ¶
func (t *Cache[K, V]) Remove(k K)
Remove causes the entry associated with the given key to be immediately evicted from the cache.
type KV ¶
type KV[K comparable, V any] struct { Key K Val V }