lrucache

package
v1.63.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 21, 2026 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package lrucache provides a small generic Least-Recently-Used cache.

The cache is bounded to a fixed maximum number of entries and evicts the least recently used entry when full. It is NOT safe for concurrent use; callers must provide their own synchronization.

Note that Get is a mutating operation: it promotes the looked-up entry to most-recently-used. Callers using a sync.RWMutex must therefore acquire the write lock around Get, not the read lock.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LRU

type LRU[K comparable, V any] struct {
	// contains filtered or unexported fields
}

LRU is a generic LRU cache holding at most maxSize entries.

Front of the internal list is the most-recently-used entry; back is the least-recently-used and the next eviction candidate.

func New

func New[K comparable, V any](maxSize int) *LRU[K, V]

New creates an LRU cache that holds at most maxSize entries. A non-positive maxSize is clamped to 1 so the cache always retains at least one entry.

func (*LRU[K, V]) Clear

func (c *LRU[K, V]) Clear()

Clear removes all entries while retaining the underlying capacity.

func (*LRU[K, V]) Delete

func (c *LRU[K, V]) Delete(key K)

Delete removes the entry for key, if any.

func (*LRU[K, V]) Get

func (c *LRU[K, V]) Get(key K) (V, bool)

Get retrieves a value, promoting it to most-recently-used. Returns the value and true if found, or the zero value and false otherwise.

Get mutates the cache (it updates the recency list), so callers using an RWMutex must hold the write lock, not the read lock.

func (*LRU[K, V]) Len

func (c *LRU[K, V]) Len() int

Len returns the number of entries currently in the cache.

func (*LRU[K, V]) Put

func (c *LRU[K, V]) Put(key K, value V)

Put adds or updates a key-value pair. If the cache is at capacity the least recently used entry is evicted to make room.

func (*LRU[K, V]) Range

func (c *LRU[K, V]) Range(fn func(key K, value V) bool)

Range calls fn on every entry, from least-recently-used to most-recently-used. Iteration stops if fn returns false. Mutating the cache from fn is not supported.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL