localcache

package
v0.0.0-...-afdce3f Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2026 License: Apache-2.0 Imports: 3 Imported by: 1

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Copier

type Copier[V any] func(V) V

Copier is a function that creates a deep copy of a value of type V. This is necessary for cache implementations that store reference types (e.g., maps, slices, pointers) to prevent race conditions when multiple goroutines access and modify cached data.

type LocalDataCache

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

LocalDataCache is an in-memory thread safe cache. It uses generics so that users of it can uses any type of data they want. The key K must be of type comparable. More infomration here: https://go.dev/blog/comparable The value V can be any type.

func NewLocalDataCache

func NewLocalDataCache[K comparable, V any](copier Copier[V]) *LocalDataCache[K, V]

NewLocalDataCache creates a new LocalDataCache instance. It accepts an optional copier function. If a copier is provided, the Get method will return a deep copy of the cached value. This is critical for ensuring thread safety when caching reference types that might be mutated by consumers. This design is chosen to provide type safety and performance, avoiding the use of reflection for deep copying. If the copier is nil, values will be returned by reference.

func (*LocalDataCache[K, V]) Cache

func (c *LocalDataCache[K, V]) Cache(
	_ context.Context,
	key K,
	in V,
) error

Cache stores a value in the cache.

func (*LocalDataCache[K, V]) Get

func (c *LocalDataCache[K, V]) Get(
	_ context.Context,
	key K,
) (V, error)

Get retrieves a value from the cache. If a copier function was provided to NewLocalDataCache, this method returns a deep copy of the value. Otherwise, it returns a direct reference. Returning a copy for reference types is crucial for preventing race conditions. It returns cachetypes.ErrCachedDataNotFound if the key does not exist. nolint: ireturn // V is not a interface always. Can ignore this.

Jump to

Keyboard shortcuts

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