Skip to content

Commit

Permalink
add deferred timer close, add missing tests
Browse files Browse the repository at this point in the history
  • Loading branch information
paskal committed Aug 5, 2023
1 parent 73f395c commit f0d41e0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions simplelru/expirable_lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func NewExpirableLRU[K comparable, V any](size int, onEvict EvictCallback[K, V],
if res.ttl != noEvictionTTL {
go func(done <-chan struct{}) {
ticker := time.NewTicker(res.ttl / numBuckets)
defer ticker.Stop()
for {
select {
case <-done:
Expand Down
35 changes: 35 additions & 0 deletions simplelru/expirable_lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,41 @@ func TestExpirableLRUNoPurge(t *testing.T) {
}
}

func TestExpirableLRUEdgeCases(t *testing.T) {
lc := NewExpirableLRU[string, *string](2, nil, 0)

// Adding a nil value
lc.Add("key1", nil)

value, exists := lc.Get("key1")
if value != nil || !exists {
t.Fatalf("unexpected value or existence flag for key1: value=%v, exists=%v", value, exists)
}

// Adding an entry with the same key but different value
newVal := "val1"
lc.Add("key1", &newVal)

value, exists = lc.Get("key1")
if value != &newVal || !exists {
t.Fatalf("unexpected value or existence flag for key1: value=%v, exists=%v", value, exists)
}
}

func TestExpirableLRU_Values(t *testing.T) {
lc := NewExpirableLRU[string, string](3, nil, 0)
defer lc.Close()

lc.Add("key1", "val1")
lc.Add("key2", "val2")
lc.Add("key3", "val3")

values := lc.Values()
if !reflect.DeepEqual(values, []string{"val1", "val2", "val3"}) {
t.Fatalf("values differs from expected")
}
}

func TestExpirableMultipleClose(_ *testing.T) {
lc := NewExpirableLRU[string, string](10, nil, 0)
lc.Close()
Expand Down

0 comments on commit f0d41e0

Please sign in to comment.