lru

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2024 License: MIT Imports: 2 Imported by: 2

README

lru

A lru is an asynchronous LRU cache (generic version).

GoDoc

  • based on golang map structure
  • prevents infinite cache growth
  • designed for asynchronous use

Usage

For example, caching the output of the ioutil.ReadFile function to reduce disk I/O.

package main

import (
	"log"
	"os"

	"github.com/codeation/lru"
)

func readFileContent(key string) ([]byte, error) {
	log.Println("read once")
	return os.ReadFile(key)
}

func main() {
	cache := lru.NewCache(1024, readFileContent)
	for i := 0; i < 10; i++ {
		data, err := cache.Get("input.txt")
		if err != nil {
			log.Fatal(err)
		}
		log.Printf("file size is %d\n", len(data))
	}
}

The lru.NewCache parameter is the number of cache items until the last used item is removed from the cache. The second parameter is a func to get the value for the specified key and error.

The parameter of cache.Get func is a key (filename in this case). An error is returned when the function returns an error.

Documentation

Overview

Package lru implements asynchronous LRU cache.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LRU added in v1.3.0

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

LRU is a plain LRU cache.

func New added in v1.3.0

func New[K comparable, V any](capacity int, fn func(K) (V, error)) *LRU[K, V]

New creates an LRU cache with the specified capacity. f is a callback function for getting a value by key, which is called if there is no value in the cache.

func (*LRU[K, V]) Get added in v1.3.0

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

Get returns the cached value for the key, or waits for the callback function to return a value.

func (*LRU[K, V]) Reset added in v1.3.0

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

Reset resets cache contents.

type SyncLRU added in v1.3.0

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

SyncLRU is a LRU cache for concurrent use.

func NewSyncLRU added in v1.3.0

func NewSyncLRU[K comparable, V any](capacity int, fn func(K) (V, error)) *SyncLRU[K, V]

NewSyncLRU creates an LRU cache with the specified capacity. f is a callback function for getting a value by key, which is called if there is no value in the cache. The callback function will be called once for concurrent Get requests with the same key.

func (*SyncLRU[K, V]) Get added in v1.3.0

func (c *SyncLRU[K, V]) Get(key K) (V, error)

Get returns the cached value for the key, or waits for the callback function to return a value.

func (*SyncLRU[K, V]) Reset added in v1.3.0

func (c *SyncLRU[K, V]) Reset()

Reset resets cache contents.

Jump to

Keyboard shortcuts

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