From 65248448bed003b2d06f375132fc8b772a24c3f9 Mon Sep 17 00:00:00 2001 From: Daniel Ponte Date: Thu, 16 Jan 2025 08:25:32 -0500 Subject: [PATCH] cache --- internal/cache/cache.go | 34 ++++++++++++++++++++++++++++++++++ internal/cache/cache_test.go | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 internal/cache/cache.go create mode 100644 internal/cache/cache_test.go diff --git a/internal/cache/cache.go b/internal/cache/cache.go new file mode 100644 index 0000000..0ce70d8 --- /dev/null +++ b/internal/cache/cache.go @@ -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) +} diff --git a/internal/cache/cache_test.go b/internal/cache/cache_test.go new file mode 100644 index 0000000..23079f1 --- /dev/null +++ b/internal/cache/cache_test.go @@ -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) +}