lrucache

package
v1.106.0-rc Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2024 License: AGPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

Package lrucache provides a LRU cache implementation with an optional key expiration time.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ExpiringLRU

type ExpiringLRU = ExpiringLRUOf[any]

ExpiringLRU is a backwards compatible implementation of ExpiringLRU.

func New

func New(opts Options) *ExpiringLRU

New constructs an ExpiringLRU with the given options.

type ExpiringLRUOf

type ExpiringLRUOf[T any] struct {
	// contains filtered or unexported fields
}

ExpiringLRUOf caches values for string keys with a time based expiration and an LRU based eviciton policy.

func NewOf

func NewOf[T any](opts Options) *ExpiringLRUOf[T]

NewOf constructs an ExpiringLRU with the given options.

func (*ExpiringLRUOf[T]) Add

func (e *ExpiringLRUOf[T]) Add(ctx context.Context, key string, value T) (replaced bool)

Add adds a value to the cache.

replaced is true if the key already existed in the cache and was valid, hence the value is replaced.

func (*ExpiringLRUOf[T]) Delete

func (e *ExpiringLRUOf[T]) Delete(ctx context.Context, key string)

Delete explicitly removes a key from the cache if it exists.

func (*ExpiringLRUOf[T]) Get

func (e *ExpiringLRUOf[T]) Get(ctx context.Context, key string, fn func() (T, error)) (value T, err error)

Get returns the value for some key if it exists and is valid. If not it will call the provided function. Concurrent calls will dedupe as best as they are able. If the function returns an error, it is not cached and further calls will try again.

func (*ExpiringLRUOf[T]) GetCached

func (e *ExpiringLRUOf[T]) GetCached(ctx context.Context, key string) (value T, cached bool)

GetCached returns the value associated with key and true if it exists and hasn't expired, otherwise nil and false.

type Options

type Options struct {
	// Expiration is how long an entry will be valid. It is not
	// affected by LRU or anything: after this duration, the object
	// is invalidated. A non-positive value means no expiration.
	Expiration time.Duration

	// Capacity is how many objects to keep in memory.
	Capacity int

	// Name is used to differentiate cache in monkit stat.
	Name string
}

Options controls the details of the expiration policy.

Jump to

Keyboard shortcuts

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