cache

package
v1.0.3 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2023 License: MIT Imports: 6 Imported by: 0

README

cache

import "github.com/esimov/gogu/cache"

Package cache implements a basic in memory key-value storage system using map as storing mechanism. The cache and the cache items also have an expiration time. The cache will be invalidated once the expiration time is reached. On cache initialization a cleanup interval is also required. The scope of the cleanup method is to run at a predefined interval and to remove all the expired cache items.

Example

{
	c := New[string, string](DefaultExpiration, 1*time.Minute)
	item, err := c.Get("foo")
	fmt.Println(err)
	fmt.Println(item)

	c.Set("foo", "bar", DefaultExpiration)
	item, _ = c.Get("foo")
	fmt.Println(item.Val())

	err = c.Set("foo", "", DefaultExpiration)
	fmt.Println(err)
	fmt.Println(c.IsExpired("foo"))

	c.Update("foo", "baz", DefaultExpiration)
	item, _ = c.Get("foo")
	fmt.Println(item.Val())

	list := c.List()
	fmt.Println(len(list))

	c.Flush()
	fmt.Println(c.Count())

	c.Set("foo", "bar", DefaultExpiration)
	item, _ = c.Get("foo")
	fmt.Println(item.Val())

	err = c.Delete("foo")
	fmt.Println(err)
	fmt.Println(c.Count())

}
Output
item with key 'foo' not found
<nil>
bar
item with key 'foo' already exists. Use the Update method
false
baz
1
0
bar
<nil>
0

Example (Expiration Time)

{
	c1 := New[string, string](NoExpiration, 0)
	c1.Set("item1", "a", DefaultExpiration)
	item, _ := c1.Get("item1")
	fmt.Println(item.expiration)

	c1.Update("item1", "b", NoExpiration)
	item, _ = c1.Get("item1")
	fmt.Println(item.expiration)

	err := c1.DeleteExpired()
	fmt.Println(err)

	c1.Set("item1", "a", 10*time.Millisecond)
	<-time.After(20 * time.Millisecond)
	c1.DeleteExpired()
	fmt.Println(c1.Count())

	c1.Set("item1", "b", 1*time.Millisecond)
	c1.Set("item2", "b", 50*time.Millisecond)
	<-time.After(20 * time.Millisecond)
	c1.DeleteExpired()
	fmt.Println(c1.Count())

	<-time.After(70 * time.Millisecond)
	c1.DeleteExpired()
	fmt.Println(c1.Count())

	c2 := New[string, int](5*time.Millisecond, 100*time.Millisecond)
	c2.Set("a", 1, DefaultExpiration)
	c2.Set("b", 2, NoExpiration)
	c2.Set("c", 3, 50*time.Millisecond)
	c2.Set("d", 4, 200*time.Millisecond)
	<-time.After(150 * time.Millisecond)
	fmt.Println(c2.Count())
	<-time.After(300 * time.Millisecond)
	fmt.Println(c2.Count())

}
Output
-1
-1
<nil>
1
2
1
2
1

Example (LRU Cache)

{
	c, _ := NewLRU[string, string](3)
	item, available := c.Get("foo")
	fmt.Println(available)

	c.Add("foo", "bar")
	item, available = c.Get("foo")
	fmt.Println(available)
	fmt.Println(item)

	c.Add("foo2", "bar2")
	c.Add("foo3", "bar3")
	c.Add("foo4", "baz")

	fmt.Println(c.Count())
	fmt.Println()

	oldestKey, oldestValue, oldestAvailable := c.GetOldest()
	fmt.Println(oldestAvailable)
	fmt.Println(oldestKey)
	fmt.Println(oldestValue)
	fmt.Println()

	youngestKey, youngestValue, youngestAvailable := c.GetYoungest()
	fmt.Println(youngestAvailable)
	fmt.Println(youngestKey)
	fmt.Println(youngestValue)
	fmt.Println()

	oldestKey, oldestValue, oldestAvailable = c.RemoveOldest()
	fmt.Println(oldestAvailable)
	fmt.Println(oldestKey)
	fmt.Println(oldestValue)
	fmt.Println()

}
Output
false
true
bar
3

true
foo2
bar2

true
foo2
bar2

true
foo3
bar3

Index

Constants

const (
    NoExpiration      time.Duration = -1
    DefaultExpiration time.Duration = 0
)

type Cache

Cache is a publicly available struct type, which incorporates the unexported cache struct type holding the cache components.

type Cache[T ~string, V any] struct {
    // contains filtered or unexported fields
}
func New
func New[T ~string, V any](expTime, cleanupTime time.Duration) *Cache[T, V]

New instantiates a cache struct which requires an expiration time and a cleanup interval. The cache will be invalidated once the expiration time is reached. If the expiration time is less than zero (or NoExpiration) the cache items will never expire and should be deleted manually. A cleanup method is running in the background and removes the expired caches at a predefined interval.

func (*Cache[T, V]) Count
func (c *Cache[T, V]) Count() int

Count returns the number of existing items in the cache.

func (*Cache[T, V]) Delete
func (c *Cache[T, V]) Delete(key T) error

Delete removes a cache item.

func (*Cache[T, V]) Flush
func (c *Cache[T, V]) Flush()

Flush removes all the existing items in the cache.

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

Get returns a cache item defined by its key. If the item is expired an error is returned. If an item is expired it's considered as nonexistent, it will be evicted from the cache when the purge method is invoked at the predefined interval.

func (*Cache[T, V]) IsExpired
func (c *Cache[T, V]) IsExpired(key T) bool

IsExpired checks if a cache item is expired.

func (*Cache[T, V]) List
func (c *Cache[T, V]) List() map[T]*Item[V]

List returns the cache items which are not expired.

func (*Cache[T, V]) MapToCache
func (c *Cache[T, V]) MapToCache(m map[T]V, d time.Duration) error

MapToCache transfers the map values into the cache.

func (*Cache[T, V]) Set
func (c *Cache[T, V]) Set(key T, val V, d time.Duration) error

Set inserts a new item into the cache, but first verifies if an item with the same key already exists in the cache. In case an item with the specified key already exists in the cache it will return an error.

func (*Cache[T, V]) SetDefault
func (c *Cache[T, V]) SetDefault(key T, val V) error

SetDefault adds a new item into the cache with the default expiration time.

func (*Cache[T, V]) Update
func (c *Cache[T, V]) Update(key T, val V, d time.Duration) error

Update replaces a cache item with the new value.

type Item

Item holds the cache object (which could be of any type) and an expiration time. The expiration time defines the object lifetime.

type Item[V any] struct {
    // contains filtered or unexported fields
}
func (*Item[V]) Val
func (it *Item[V]) Val() V

Val returns the effective value of the cache item.

type LRUCache

LRUCache implements a fixed size LRU cache using a map and a double linked list

type LRUCache[K comparable, V any] struct {
    // contains filtered or unexported fields
}
func NewLRU
func NewLRU[K comparable, V any](size int) (*LRUCache[K, V], error)

NewLRU initializes a new LRU cache

func (*LRUCache[K, V]) Add
func (c *LRUCache[K, V]) Add(key K, value V) (oldestKey K, oldestValue V, removed bool)

Add adds a value to the cache. If the oldest value is evicted, this value and they key for it is returned.

func (*LRUCache[K, V]) Count
func (c *LRUCache[K, V]) Count() int

Count return the number of the current values from the cache. It should be LE then the initial size of the cache

func (*LRUCache[K, V]) Flush
func (c *LRUCache[K, V]) Flush()

Flush clears all values from the cache

func (*LRUCache[K, V]) Get
func (c *LRUCache[K, V]) Get(key K) (value V, available bool)

Get return the element for the key if the element is present in the cache

func (*LRUCache[K, V]) GetOldest
func (c *LRUCache[K, V]) GetOldest() (key K, value V, available bool)

GetOldest returns the oldest key/value pair from the cache if the cache has any values

func (*LRUCache[K, V]) GetYoungest
func (c *LRUCache[K, V]) GetYoungest() (key K, value V, available bool)

GetYoungest returns the youngest key/value pair from the cache if the cache has any values

func (*LRUCache[K, V]) Remove
func (c *LRUCache[K, V]) Remove(key K) (value V, removed bool)

Remove removes an element form the cache denoted by the key. The value removed is returned

func (*LRUCache[K, V]) RemoveOldest
func (c *LRUCache[K, V]) RemoveOldest() (key K, value V, removed bool)

RemoveOldest removes the oldest value from the cache. It returns he key/value pair which was removed

func (*LRUCache[K, V]) RemoveYoungest
func (c *LRUCache[K, V]) RemoveYoungest() (key K, value V, removed bool)

RemoveYoungest removes the youngest value from the cache. The key/value pair removed is returned

Documentation

Overview

Package cache implements a basic in memory key-value storage system using map as storing mechanism. The cache and the cache items also have an expiration time. The cache will be invalidated once the expiration time is reached. On cache initialization a cleanup interval is also required. The scope of the cleanup method is to run at a predefined interval and to remove all the expired cache items.

Example (ExpirationTime)
c1 := New[string, string](NoExpiration, 0)
c1.Set("item1", "a", DefaultExpiration)
item, _ := c1.Get("item1")
fmt.Println(item.expiration)

c1.Update("item1", "b", NoExpiration)
item, _ = c1.Get("item1")
fmt.Println(item.expiration)

err := c1.DeleteExpired()
fmt.Println(err)

c1.Set("item1", "a", 10*time.Millisecond)
<-time.After(20 * time.Millisecond)
c1.DeleteExpired()
fmt.Println(c1.Count())

c1.Set("item1", "b", 1*time.Millisecond)
c1.Set("item2", "b", 50*time.Millisecond)
<-time.After(20 * time.Millisecond)
c1.DeleteExpired()
fmt.Println(c1.Count())

<-time.After(70 * time.Millisecond)
c1.DeleteExpired()
fmt.Println(c1.Count())

c2 := New[string, int](5*time.Millisecond, 100*time.Millisecond)
c2.Set("a", 1, DefaultExpiration)
c2.Set("b", 2, NoExpiration)
c2.Set("c", 3, 50*time.Millisecond)
c2.Set("d", 4, 200*time.Millisecond)
<-time.After(150 * time.Millisecond)
fmt.Println(c2.Count())
<-time.After(300 * time.Millisecond)
fmt.Println(c2.Count())
Output:

-1
-1
<nil>
1
2
1
2
1
Example (LRUCache)
c, _ := NewLRU[string, string](3)
item, available := c.Get("foo")
fmt.Println(available)

c.Add("foo", "bar")
item, available = c.Get("foo")
fmt.Println(available)
fmt.Println(item)

c.Add("foo2", "bar2")
c.Add("foo3", "bar3")
c.Add("foo4", "baz")

fmt.Println(c.Count())
fmt.Println()

oldestKey, oldestValue, oldestAvailable := c.GetOldest()
fmt.Println(oldestAvailable)
fmt.Println(oldestKey)
fmt.Println(oldestValue)
fmt.Println()

youngestKey, youngestValue, youngestAvailable := c.GetYoungest()
fmt.Println(youngestAvailable)
fmt.Println(youngestKey)
fmt.Println(youngestValue)
fmt.Println()

oldestKey, oldestValue, oldestAvailable = c.RemoveOldest()
fmt.Println(oldestAvailable)
fmt.Println(oldestKey)
fmt.Println(oldestValue)
fmt.Println()
Output:

false
true
bar
3

true
foo2
bar2

true
foo2
bar2

true
foo3
bar3

Index

Examples

Constants

View Source
const (
	NoExpiration      time.Duration = -1
	DefaultExpiration time.Duration = 0
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache is a publicly available struct type, which incorporates the unexported cache struct type holding the cache components.

Example
c := New[string, string](DefaultExpiration, 1*time.Minute)
item, err := c.Get("foo")
fmt.Println(err)
fmt.Println(item)

c.Set("foo", "bar", DefaultExpiration)
item, _ = c.Get("foo")
fmt.Println(item.Val())

err = c.Set("foo", "", DefaultExpiration)
fmt.Println(err)
fmt.Println(c.IsExpired("foo"))

c.Update("foo", "baz", DefaultExpiration)
item, _ = c.Get("foo")
fmt.Println(item.Val())

list := c.List()
fmt.Println(len(list))

c.Flush()
fmt.Println(c.Count())

c.Set("foo", "bar", DefaultExpiration)
item, _ = c.Get("foo")
fmt.Println(item.Val())

err = c.Delete("foo")
fmt.Println(err)
fmt.Println(c.Count())
Output:

item with key 'foo' not found
<nil>
bar
item with key 'foo' already exists. Use the Update method
false
baz
1
0
bar
<nil>
0

func New

func New[K ~string, V any](expTime, cleanupTime time.Duration) *Cache[K, V]

New instantiates a cache struct which requires an expiration time and a cleanup interval. The cache will be invalidated once the expiration time is reached. If the expiration time is less than zero (or NoExpiration) the cache items will never expire and should be deleted manually. A cleanup method is running in the background and removes the expired caches at a predefined interval.

func (*Cache[K, V]) Count

func (c *Cache[K, V]) Count() int

Count returns the number of existing items in the cache.

func (*Cache[K, V]) Delete

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

Delete removes a cache item.

func (Cache) DeleteExpired

func (c Cache) DeleteExpired() error

DeleteExpired removes all the expired items from the cache.

func (*Cache[K, V]) Flush

func (c *Cache[K, V]) Flush()

Flush removes all the existing items in the cache.

func (*Cache[K, V]) Get

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

Get returns a cache item defined by its key. If the item is expired an error is returned. If an item is expired it's considered as nonexistent, it will be evicted from the cache when the purge method is invoked at the predefined interval.

func (*Cache[K, V]) IsExpired

func (c *Cache[K, V]) IsExpired(key K) bool

IsExpired checks if a cache item is expired.

func (*Cache[K, V]) List

func (c *Cache[K, V]) List() map[K]*Item[V]

List returns the cache items which are not expired.

func (*Cache[K, V]) MapToCache

func (c *Cache[K, V]) MapToCache(m map[K]V, d time.Duration) error

MapToCache transfers the map values into the cache.

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(key K, val V, d time.Duration) error

Set inserts a new item into the cache, but first verifies if an item with the same key already exists in the cache. In case an item with the specified key already exists in the cache it will return an error.

func (*Cache[K, V]) SetDefault

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

SetDefault adds a new item into the cache with the default expiration time.

func (*Cache[K, V]) Update

func (c *Cache[K, V]) Update(key K, val V, d time.Duration) error

Update replaces a cache item with the new value.

type Item

type Item[V any] struct {
	// contains filtered or unexported fields
}

Item holds the cache object (which could be of any type) and an expiration time. The expiration time defines the object lifetime.

func (*Item[V]) Val

func (it *Item[V]) Val() V

Val returns the effective value of the cache item.

type LRUCache added in v1.0.3

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

LRUCache implements a fixed size LRU cache using a map and a double linked list.

func NewLRU added in v1.0.3

func NewLRU[K comparable, V any](size int) (*LRUCache[K, V], error)

NewLRU initializes a new LRU cache.

func (*LRUCache[K, V]) Add added in v1.0.3

func (c *LRUCache[K, V]) Add(key K, value V) (oldestKey K, oldestValue V, removed bool)

Add adds a value to the cache. If the oldest value is evicted, this value and they key for it is returned.

func (*LRUCache[K, V]) Count added in v1.0.3

func (c *LRUCache[K, V]) Count() int

Count return the number of the current values from the cache. It should be LE then the initial size of the cache.

func (*LRUCache[K, V]) Flush added in v1.0.3

func (c *LRUCache[K, V]) Flush()

Flush clears all values from the cache.

func (*LRUCache[K, V]) Get added in v1.0.3

func (c *LRUCache[K, V]) Get(key K) (value V, available bool)

Get return the element for the key if the element is present in the cache.

func (*LRUCache[K, V]) GetOldest added in v1.0.3

func (c *LRUCache[K, V]) GetOldest() (key K, value V, available bool)

GetOldest returns the oldest key/value pair from the cache if the cache has any values.

func (*LRUCache[K, V]) GetYoungest added in v1.0.3

func (c *LRUCache[K, V]) GetYoungest() (key K, value V, available bool)

GetYoungest returns the youngest key/value pair from the cache if the cache has any values.

func (*LRUCache[K, V]) Remove added in v1.0.3

func (c *LRUCache[K, V]) Remove(key K) (value V, removed bool)

Remove removes an element form the cache denoted by the key. The value removed is returned.

func (*LRUCache[K, V]) RemoveOldest added in v1.0.3

func (c *LRUCache[K, V]) RemoveOldest() (key K, value V, removed bool)

RemoveOldest removes the oldest value from the cache. It returns he key/value pair which was removed.

func (*LRUCache[K, V]) RemoveYoungest added in v1.0.3

func (c *LRUCache[K, V]) RemoveYoungest() (key K, value V, removed bool)

RemoveYoungest removes the youngest value from the cache. The key/value pair removed is returned.

Jump to

Keyboard shortcuts

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