lru

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2023 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++ {
		var data []byte
		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 Cache

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

Cache is a LRU cache.

func NewCache

func NewCache[K comparable, V any](capacity int, f func(K) (V, error)) *Cache[K, V]

NewCache creates an LRU cache with the specified capacity; f - function to get value by key, which is called if there is no value in the cache

func (*Cache[K, V]) Get

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

Get returns the cached value for the key, or waits until f returns a value.

func (*Cache[K, V]) Reset

func (c *Cache[K, V]) Reset() error

Reset resets cache contents.

Jump to

Keyboard shortcuts

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