cache

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 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 values.
Installation

You can install like this:

go get github.com/gozeloglu/cache
Example
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)

	// 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.")
	}
}

LICENSE

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {

	// Cap is the maximum capacity of the cache.
	Cap int

	// CleanInterval is the time duration to make cache empty.
	CleanInterval time.Duration

	// ExpirationTimeoutInterval indicates the time to delete expired items.
	ExpirationTimeoutInterval time.Duration
	// 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 string, val interface{}, exp time.Duration) error

Add saves data to cache if it is not saved yet.

func (*Cache) Clear

func (c *Cache) Clear()

Clear deletes all items from the cache.

func (*Cache) Contains

func (c *Cache) Contains(key string) 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 string) (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() []string

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 string) (interface{}, bool)

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

func (*Cache) Remove

func (c *Cache) Remove(key string) 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 string, 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) 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 time.Duration
}

Config keeps configuration variables.

type Item

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

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

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

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