cache

package module
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2022 License: MIT Imports: 4 Imported by: 0

README

cache Go Reference Go Report Card GitHub go.mod Go version GitHub release (latest SemVer) LICENSE

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.
  • Supports time expiration.
Installation
go get github.com/gozeloglu/cache
Example

Here, there is an example usage of the package.

You can import like this.

import "github.com/gozeloglu/cache"

Then, you need to create a cache variable with New() function. It takes one parameter to specify cache capacity.

Add new data
cache.Add("foo", "bar", 0) // Without expiration time
cache.Add("key", "value", time.Hour * 2) // With expiration time
Get data
val, found := cache.Get("foo")
if !found {
    fmt.Println("key does not exist. val is nil.")
}
fmt.Println(val)
Get all keys
keys := cache.Keys()
for _, k := range keys {
    fmt.Println(k)
}
Contains, Peek and Remove
found := cache.Contains("foo")
if found {
    val, _ := cache.Peek("foo")
    cache.Remove("foo")
}
Remove Oldest
k, v, ok := cache.RemoveOldest()
if ok {
    fmt.Printf("Oldest key-value pair removed: %s-%s", k, v)
}
Resize
cache.Resize(20) // Capacity will be 20
Update value, update expiration date, and replace
newItem, err := cache.UpdateVal("foo", "foobar") // Cache data order is also updated
if err != nil {
    fmt.Printf("New item key and value is %s-%s", newItem.Key, newItem.Val)
}
newItem, err := c.UpdateExpirationDate("foo", time.Hour * 4) // Cache data order is also updated
if err != nil {
    fmt.Printf("%v", newItem.Expiration)
}

err = c.Replace("foo", "fuzz")  // Change value of the key without updating cache access order
if err != nil {
	fmt.Printf(err.Error())
}
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)

It takes one parameter that 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 gcache 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 {
	// contains filtered or unexported fields
}

Cache is the main cache type.

func New

func New(cap int) (*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. Calling Replace function does not change the cache order.

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.

func (*Cache) UpdateExpirationDate added in v0.7.0

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

UpdateExpirationDate updates the expiration date of the given key. If there is no such a data, error will be returned. Cache data order is updated after updating the expiration time. It returns updated item.

func (*Cache) UpdateVal added in v0.7.0

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

UpdateVal updates the value of the given key. If there is no such a data, error will be returned. Cache data order is updated after updating the value. It returns updated item.

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.

func (Item) Expired added in v0.7.0

func (i Item) Expired() bool

Expired returns true if the item expired.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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