Documentation
¶
Overview ¶
Package lru provides an LRU cache that evicts the least recently used entry when capacity is reached.
NOT safe for concurrent use. Callers must synchronize access externally.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[K any] struct { // contains filtered or unexported fields }
Cache is an LRU cache that evicts the least recently used entry when capacity is reached.
func NewLRUCache ¶
NewLRUCache creates a new Cache with the given maximum capacity.
Example ¶
package main
import (
"fmt"
"github.com/FrogoAI/memory/lru"
)
func main() {
cache := lru.NewLRUCache[string](3)
cache.Put("a", "alpha")
cache.Put("b", "beta")
fmt.Println(cache.Len())
}
Output: 2
func (*Cache[K]) Clear ¶
func (c *Cache[K]) Clear()
Clear removes all items from the cache.
Example ¶
package main
import (
"fmt"
"github.com/FrogoAI/memory/lru"
)
func main() {
cache := lru.NewLRUCache[string](3)
cache.Put("a", "alpha")
cache.Put("b", "beta")
fmt.Println(cache.Len())
cache.Clear()
fmt.Println(cache.Len())
}
Output: 2 0
func (*Cache[K]) Copy ¶
Copy returns a deep copy of the cache. The new cache has independent storage but shares the same value references. Eviction order is preserved.
func (*Cache[K]) Get ¶
Get returns the value associated with key and promotes it to the front of the eviction list. The second return value reports whether the key was found.
Example ¶
package main
import (
"fmt"
"github.com/FrogoAI/memory/lru"
)
func main() {
cache := lru.NewLRUCache[int](3)
cache.Put("x", 42)
val, ok := cache.Get("x")
fmt.Println(val, ok)
val, ok = cache.Get("missing")
fmt.Println(val, ok)
}
Output: 42 true 0 false
func (*Cache[K]) Iterator ¶
Iterator returns an iterator over cache entries from most recently used to least recently used. It can be used directly in a for-range loop:
for key, value := range cache.Iterator() {
// ...
}
Example ¶
package main
import (
"fmt"
"github.com/FrogoAI/memory/lru"
)
func main() {
cache := lru.NewLRUCache[string](3)
cache.Put("a", "alpha")
cache.Put("b", "beta")
cache.Put("c", "gamma")
for key, val := range cache.Iterator() {
fmt.Printf("%s=%s ", key, val)
}
fmt.Println()
}
Output: c=gamma b=beta a=alpha
func (*Cache[K]) Put ¶
Put adds or updates an entry in the cache and evicts the least recently used entry if the cache is at capacity.
Example ¶
package main
import (
"fmt"
"github.com/FrogoAI/memory/lru"
)
func main() {
cache := lru.NewLRUCache[string](2)
cache.Put("a", "alpha")
cache.Put("b", "beta")
cache.Put("c", "gamma") // evicts "a"
_, found := cache.Get("a")
fmt.Println("a found:", found)
val, found := cache.Get("c")
fmt.Println("c found:", found, "value:", val)
}
Output: a found: false c found: true value: gamma