cache

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2021 License: MIT Imports: 4 Imported by: 0

README

cache

cache is LRU-based cache package written in vanilla Go - with no package dependency. LRU stands for Least Recently Used and it is one of the famous cache replacement algorithm. It replaces newly added data with the least recently used one.

  • Written in Vanilla Go, with no dependencies.
  • Safe for concurrent use.
  • Supports any data type for keys and values.
Installation

You can install like this:

go get github.com/gozeloglu/cache
Example

Here, there is an example usage of the package.

package main

import (
	"fmt"
	"github.com/gozeloglu/cache"
	"log"
)

func main() {
	// Create a cache
	c, err := cache.New(5, cache.Config{})
	if err != nil {
		log.Fatalf(err.Error())
	}

	// Add key-value pairs to cache
	err = c.Add("foo", "bar", 0)
	if err != nil {
		log.Printf("%s\n", err.Error())
	}
	_ = c.Add("key", "val", 0)
	_ = c.Add("fuzz", "buzz", 0)

	// Retrieve value via key
	val, found := c.Get("foo")
	if !found {
		log.Printf("data not exists in cache.")
	}
	if val != nil {
		fmt.Printf("key: foo\nvalue: %s\n", val)
	}

	// Get all keys from cache
	fmt.Println("Keys:")
	keys := c.Keys()
	for _, k := range keys {
		fmt.Println(k)
	}
	fmt.Printf("cache length: %v\n", c.Len())

	// Remove data from cache via key
	err = c.Remove("foo")
	if err != nil {
		log.Printf("%s\n", err.Error())
	}

	// Check the given key whether exists.
	found = c.Contains("key")
	if found {
		fmt.Println("key found in cache.")
	} else {
		fmt.Println("key does not exist in cache.")
	}

	found = c.Contains("foo")
	if found {
		fmt.Println("foo found in cache.")
	} else {
		fmt.Println("foo does not exist in cache.")
	}

	// Peek one of the key without updating access order.
	val, found = c.Peek("key")
	if found {
		fmt.Println("key found in cache. value is", val)
	} else {
		fmt.Println("key does not exist in cache.")
	}

	// Remove the oldest element from the cache
	k, v, ok := c.RemoveOldest()
	if ok {
		fmt.Printf("Oldest data (%s-%s) pair is removed.\n", k, v)
	} else {
		fmt.Println("Oldest data in cache did not remove.")
	}

	// Change the capacity of the cache
	c.Resize(10)
	fmt.Println("new cache capacity is", c.Cap())

	err = c.Replace("fuzz", "fuzz_buzz")
	if err != nil {
		fmt.Println(err.Error())
	}
	val, found = c.Peek("fuzz")
	if !found {
		fmt.Println("not found.")
	}
	fmt.Printf("new value is %s\n", val)
	// Clear cache. Remove everything from cache.
	c.Clear()
	fmt.Printf("cache cleared. length is %v\n", c.Len())
	_, found = c.Get("foo")
	if !found {
		fmt.Println("key does not exist.")
	}
}
Testing

You can run the tests with the following command.

go test .
LICENSE

MIT

Documentation

Overview

Package cache is a cache package written in Go with no dependency. It uses Least-Recently Used (LRU) algorithm for replacement policy. Behind the package, it uses doubly-linked list which is built-in data structure that comes from container/list. Any data can be stored in cache.

Firstly, you need to create a new cache as follows.

c, err := cache.New(5, cache.Config{})

The first parameter is capacity of the cache. For the example, the cache can keep up to 5 data. If a new data is being tried to add when the cache is full, the cache removes the least-recently used one and adds the new data.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	// CleanInterval is the time duration to make cache empty.
	CleanInterval time.Duration

	// ExpirationTimeoutInterval indicates the time to delete expired items.
	ExpirationTimeoutInterval int64
	// contains filtered or unexported fields
}

Cache is the main cache type.

func New

func New(cap int, config Config) (*Cache, error)

New creates a new cache and returns it with error type. Capacity of the cache needs to be more than zero.

func (*Cache) Add

func (c *Cache) Add(key interface{}, val interface{}, exp time.Duration) error

Add saves data to cache if it is not saved yet. If the capacity is full, the least-recently used one will be removed and new data will be added. If you do not want to add an expired time for data, you need to pass 0.

func (*Cache) Cap

func (c *Cache) Cap() int

Cap returns capacity of the cache.

func (*Cache) Clear

func (c *Cache) Clear()

Clear deletes all items from the cache.

func (*Cache) ClearExpiredData added in v0.6.0

func (c *Cache) ClearExpiredData()

ClearExpiredData deletes the all expired data in cache.

func (*Cache) Contains

func (c *Cache) Contains(key interface{}) bool

Contains checks the given key and returns the information that it exists on cache or not. Calling this function doesn't change the access order of the cache.

func (*Cache) Get

func (c *Cache) Get(key interface{}) (interface{}, bool)

Get retrieves the data from list and returns it with bool information which indicates whether found. If there is no such data in cache, it returns nil and false.

func (*Cache) Keys

func (c *Cache) Keys() []interface{}

Keys returns all keys in cache. It does not change frequency of the item access.

func (*Cache) Len

func (c *Cache) Len() int

Len returns length of the cache.

func (*Cache) Peek added in v0.2.0

func (c *Cache) Peek(key interface{}) (interface{}, bool)

Peek returns the given key without updating access frequency of the item.

func (*Cache) Remove

func (c *Cache) Remove(key interface{}) error

Remove deletes the item from the cache. Updates the length of the cache decrementing by one.

func (*Cache) RemoveOldest added in v0.3.0

func (c *Cache) RemoveOldest() (k interface{}, v interface{}, ok bool)

RemoveOldest removes the least recently used one. Returns removed key, value, and bool value that indicates whether remove operation is done successfully.

func (*Cache) Replace added in v0.6.0

func (c *Cache) Replace(key interface{}, val interface{}) error

Replace changes the value of the given key, if the key exists. If the key does not exist, it returns error.

func (*Cache) Resize added in v0.3.0

func (c *Cache) Resize(size int) int

Resize changes the size of the capacity. If new capacity is lower than existing capacity, the oldest items will be removed. It returns the number of the removed oldest elements from the cache. If it is zero, means that no data removed from the cache.

type Config

type Config struct {
	// CleanInterval is the time duration to make cache empty.
	CleanInterval time.Duration

	// ExpirationTimeoutInterval indicates the time to delete expired items.
	ExpirationTimeoutInterval int64
}

Config keeps configuration variables.

type Item

type Item struct {
	// Key is the value's key.
	Key interface{}

	// Val is the value of the cached data.
	Val interface{}

	// Expiration is the amount of time to saved on memory.
	Expiration int64
}

Item is the cached data type.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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