This commit is contained in:
Daniel Ponte 2025-01-16 08:25:32 -05:00
parent 40f10ce514
commit 65248448be
2 changed files with 67 additions and 0 deletions

34
internal/cache/cache.go vendored Normal file
View file

@ -0,0 +1,34 @@
package cache
import (
)
type Cache[K comparable, V any] interface {
Get(K) (V, bool)
Set(K, V)
Delete(K)
Clear()
}
type inMem[K comparable, V any] map[K]V
func New[K comparable, V any]() inMem[K, V] {
return make(inMem[K, V])
}
func (c inMem[K, V]) Get(key K) (V, bool) {
v, ok := c[key]
return v, ok
}
func (c inMem[K, V]) Set(key K, val V) {
c[key] = val
}
func (c inMem[K, V]) Delete(key K) {
delete(c, key)
}
func (c inMem[K, V]) Clear() {
clear(c)
}

33
internal/cache/cache_test.go vendored Normal file
View file

@ -0,0 +1,33 @@
package cache_test
import (
"testing"
"dynatron.me/x/stillbox/internal/cache"
"github.com/stretchr/testify/assert"
)
func TestCache(t *testing.T) {
c := cache.New[int, string]()
c.Set(4, "asd")
g, ok := c.Get(4)
assert.Equal(t, "asd", g)
assert.True(t, ok)
_, ok = c.Get(8)
assert.False(t, ok)
c.Set(7, "fg")
c.Delete(4)
g, ok = c.Get(4)
assert.False(t, ok)
assert.NotEqual(t, "asd", g)
c.Clear()
g, ok = c.Get(7)
assert.False(t, ok)
assert.NotEqual(t, "fg", g)
}