~netlandish/gobwebs

f1463b0ed37a9c911f0d53be5354634482eeceb1 — Peter Sanchez 3 months ago 2540e45
Using generics for Cache interface.

References: https://todo.code.netlandish.com/~netlandish/gobwebs/7
1 files changed, 10 insertions(+), 10 deletions(-)

M cache/cache.go
M cache/cache.go => cache/cache.go +10 -10
@@ 7,26 7,26 @@
package cache

// Cache is the interface to work with caching backends
type Cache interface {
	Get(key string) (any, error)
	Set(key string, value any) (bool, error)
	Delete(key string) (bool, error)
type Cache[K comparable, V any] interface {
	Get(key K) (V, error)
	Set(key K, value V) (bool, error)
	Delete(key K) (bool, error)
}

// DummyCache is a super dumb in memory cache store.
type DummyCache struct {
type DummyCache[K comparable, V any] struct {
	cache map[string]any
	limit int
}

// Get fetches a specific key from the cache
func (d *DummyCache) Get(key string) (any, error) {
func (d *DummyCache[K, V]) Get(key string) (any, error) {
	val := d.cache[key]
	return val, nil
}

// Set will set a key/value in the cache backend.
func (d *DummyCache) Set(key string, value any) (bool, error) {
func (d *DummyCache[K, V]) Set(key string, value any) (bool, error) {
	var evicted bool
	if len(d.cache) >= d.limit {
		for k := range d.cache {


@@ 42,7 42,7 @@ func (d *DummyCache) Set(key string, value any) (bool, error) {
}

// Delete will delete a key from the cache
func (d *DummyCache) Delete(key string) (bool, error) {
func (d *DummyCache[K, V]) Delete(key string) (bool, error) {
	var present bool
	if _, ok := d.cache[key]; ok {
		present = true


@@ 54,11 54,11 @@ func (d *DummyCache) Delete(key string) (bool, error) {
// NewDummyCache will create a new DummyCache instance with the
// cache limit set to the value of `limit`. Default limit value
// is 10.
func NewDummyCache(limit int) *DummyCache {
func NewDummyCache[K comparable, V any](limit int) *DummyCache[K, V] {
	if limit == 0 {
		limit = 10
	}
	return &DummyCache{
	return &DummyCache[K, V]{
		cache: make(map[string]any),
		limit: limit,
	}