lrucache

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 3 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package lrucache is a small bounded cache keyed by string: least recently used entries are evicted at capacity, and a value that is missing is built once even when many goroutines ask for it at the same moment.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache[V any] struct {
	// contains filtered or unexported fields
}

Cache holds up to max values. The zero value is not usable; call New or NewWeighted.

func New

func New[V any](max int) *Cache[V]

New returns a cache that keeps at most max entries.

func NewWeighted added in v2.3.0

func NewWeighted[V any](max int, maxWeight int64, weigh func(key string, v V) int64) *Cache[V]

NewWeighted returns a cache that keeps at most max entries whose weights, as weigh reports them, add up to at most maxWeight. A value heavier than maxWeight on its own is not stored.

func (*Cache[V]) Add

func (c *Cache[V]) Add(key string, v V)

Add stores v under key, replacing any previous value, and drops the least recently used entries until the cache is within capacity.

func (*Cache[V]) Do

func (c *Cache[V]) Do(key string, build func() (V, error)) (V, error)

Do returns the value for key, building and storing it with build when it is missing. Concurrent callers for the same missing key share one build; a build that fails stores nothing and every waiting caller sees the error.

func (*Cache[V]) Get

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

Get returns the value for key and marks it recently used.

func (*Cache[V]) Len

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

Len is the number of entries held.

func (*Cache[V]) Remove

func (c *Cache[V]) Remove(key string)

Remove drops key if present.

func (*Cache[V]) Reset

func (c *Cache[V]) Reset()

Reset drops every entry.

func (*Cache[V]) Weight added in v2.3.0

func (c *Cache[V]) Weight() int64

Weight is the total weight of the entries held (0 for a cache made with New).

Jump to

Keyboard shortcuts

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