all repos — volatile @ 1021d0d3cc981b13b9f74ba4bf68d78337a677ce

A (dead) simple volatile data storage written in Go.

add Clear() and Length()
Marco Andronaco andronacomarco@gmail.com
Fri, 14 Jun 2024 10:55:01 +0200
commit

1021d0d3cc981b13b9f74ba4bf68d78337a677ce

parent

7711e07c600847e0d27ed8730f254f501fb87f50

3 files changed, 76 insertions(+), 2 deletions(-)

jump to
M READMEREADME

@@ -7,13 +7,22 @@

FEATURES • Automatic cleanup via goroutines! -• Get, Set, Has and Remove methods! • Can be as fast (or slow) as you wish! • Does not use any external libraries, only native go! • Absolutely unsafe memory-wise and probably more resource-intensive than any other alternative. USAGE + +Use NewVolatile to create a new cache. +Then, you can use the following methods: +• Get +• Set +• Has +• Clear +• Remove +• Length + Check out 'volatile_test.go' for some examples.
M volatile.govolatile.go

@@ -38,9 +38,9 @@ }

func NewVolatile[K comparable, V any](timeToLive time.Duration, cleanupInterval time.Duration) *Volatile[K, V] { v := &Volatile[K, V]{ - data: make(map[K]Element[V]), timeToLive: timeToLive, } + v.Clear() go v.cleanupRoutine(cleanupInterval) return v }

@@ -72,6 +72,15 @@ }

delete(v.data, key) return value.value, nil +} + +func (v *Volatile[K, V]) Length() int { + v.clean() + return len(v.data) +} + +func (v *Volatile[K, V]) Clear() { + v.data = make(map[K]Element[V]) } func (v *Volatile[K, V]) Set(key K, value *V) {
M volatile_test.govolatile_test.go

@@ -45,6 +45,62 @@ t.Errorf("expected key %v to be removed", key)

} } +func TestVolatile_Length(t *testing.T) { + cache := NewVolatile[string, int](100*time.Millisecond, 50*time.Millisecond) + + if cache.Length() != 0 { + t.Errorf("expected length to be 0, got %d", cache.Length()) + } + + v1 := 1 + v2 := 2 + + cache.Set("key1", &v1) + cache.Set("key2", &v2) + + if cache.Length() != 2 { + t.Errorf("expected length to be 2, got %d", cache.Length()) + } + + // Wait for the elements to expire and be cleaned up + time.Sleep(300 * time.Millisecond) + + if cache.Length() != 0 { + t.Errorf("expected length to be 0 after expiration, got %d", cache.Length()) + } +} + +func TestVolatile_Clear(t *testing.T) { + cache := NewVolatile[string, int](2*time.Second, 1*time.Second) + + v1 := 1 + v2 := 2 + v3 := 3 + + // Insert multiple items + cache.Set("key1", &v1) + cache.Set("key2", &v2) + cache.Set("key3", &v3) + + // Ensure items are set + if !cache.Has("key1") || !cache.Has("key2") || !cache.Has("key3") { + t.Fatal("expected keys to be set") + } + + // Clear the cache + cache.Clear() + + // Ensure all items are cleared + if cache.Has("key1") || cache.Has("key2") || cache.Has("key3") { + t.Fatal("expected all keys to be cleared") + } + + // Ensure map is empty + if len(cache.data) != 0 { + t.Errorf("expected map to be empty, got %d elements", len(cache.data)) + } +} + func TestVolatile_Clean(t *testing.T) { cache := NewVolatile[string, string](100*time.Millisecond, 50*time.Millisecond)