lrucache

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2026 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package lrucache implements a small bounded LRU cache safe for concurrent use. It exists so the enricher's per-process memoization caches (album → release-MBID, artist → MBID, etc.) have a hard size ceiling instead of growing for the lifetime of the process.

The cache is keyed by `comparable` and stores any value type. Map capacity is pre-allocated at construction so the bulk-ingestion phase of a 50k-track scan doesn't trigger Go map bucket resizing mid-flight; the doubly-linked list grows naturally.

We don't pull in `hashicorp/golang-lru` because the dependency surface isn't worth ~120 LOC of generics. Reads on empty buckets short-circuit cheaply.

**Zero `interface{}` boxing on the hot path** (PR-F audit follow-up). The prior implementation used `container/list`, whose `Element.Value` is `any` — every Get/Set required a type assertion to `*entry[K, V]`, and every PushFront allocated a `list.Element` value-box. This package replaces that with a struct-based generic doubly-linked list. Public API is unchanged: `Get`/`Set`/`Has`/`Len`.

Index

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
}

Cache is a bounded, mutex-protected LRU. Zero value is NOT usable — always construct via New. The internal doubly-linked list is circular-with-sentinel: `root.next` is the MRU element, `root.prev` is the LRU tail. This idiom eliminates per-method nil checks for "empty list" vs "single element" cases.

func New

func New[K comparable, V any](capacity int) *Cache[K, V]

New returns a Cache with the given capacity. Capacity <= 0 is silently treated as 1 — a zero-cap cache would never store anything, which is almost certainly a configuration bug we'd rather surface as "very small" than "silently broken".

func (*Cache[K, V]) Get

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

Get returns the cached value and true on hit; the zero value and false on miss. A hit moves the entry to the front (most-recently- used).

func (*Cache[K, V]) Has

func (c *Cache[K, V]) Has(key K) bool

Has returns true if key is present, without promoting it to MRU. Useful for negative-cache checks where the caller doesn't want the lookup itself to keep the entry alive.

func (*Cache[K, V]) Len

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

Len returns the current number of entries.

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, value V)

Set inserts or updates the entry for key. On overflow the oldest entry is evicted from the tail. Updates move the entry to the front and overwrite the value in place — no node churn.

Jump to

Keyboard shortcuts

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