Skip to content

Commit

Permalink
Add found in Get returned values
Browse files Browse the repository at this point in the history
  • Loading branch information
TheoBrigitte committed Nov 14, 2024
1 parent 0b92309 commit 413d60f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
5 changes: 3 additions & 2 deletions expiry-map.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,17 @@ func New[K comparable, V any](expiryDelay, gargabeCleanInterval time.Duration) *
}

// Get returns the value for a given key.
func (s *ExpiryMap[K, V]) Get(key K) V {
func (s *ExpiryMap[K, V]) Get(key K) (V, bool) {
s.mutex.Lock()
defer s.mutex.Unlock()

content, found := s.storedMap[key]

if !found {
content = &Content[V]{}
}

return content.Data
return content.Data, found
}

// Set sets the value for a given key and reset its expiry time.
Expand Down
15 changes: 10 additions & 5 deletions expiry-map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,14 @@ func TestGetUnset(t *testing.T) {

m := New[int, string](time.Minute, time.Minute)

if v := m.Get(key); !reflect.DeepEqual(v, "") {
v, found := m.Get(key)
if !reflect.DeepEqual(v, "") {
t.Fatalf("expected %v, got %v", "", v)
}

if found {
t.Fatalf("expected %v, got %v", false, found)
}
}

func TestSetGet(t *testing.T) {
Expand All @@ -30,7 +35,7 @@ func TestSetGet(t *testing.T) {
m := New[int, string](time.Minute, time.Minute)
m.Set(key, value)

if v := m.Get(key); !reflect.DeepEqual(v, value) {
if v, _ := m.Get(key); !reflect.DeepEqual(v, value) {
t.Fatalf("expected %v, got %v", value, v)
}
}
Expand All @@ -43,7 +48,7 @@ func TestSetDeleteGet(t *testing.T) {
m.Set(key, value)
m.Delete(key)

if v := m.Get(key); !reflect.DeepEqual(v, "") {
if v, _ := m.Get(key); !reflect.DeepEqual(v, "") {
t.Fatalf("expected %v, got %v", "", v)
}
}
Expand Down Expand Up @@ -124,13 +129,13 @@ func TestGargabeClean(t *testing.T) {
m := New[int, string](time.Nanosecond, time.Millisecond)
m.Set(key, value)

if v := m.Get(key); !reflect.DeepEqual(v, value) {
if v, _ := m.Get(key); !reflect.DeepEqual(v, value) {
t.Fatalf("expected %v, got %v", value, v)
}

time.Sleep(time.Millisecond * 2)

if v := m.Get(key); v != "" {
if v, _ := m.Get(key); v != "" {
t.Fatalf("expected nil, got %v", v)
}
}

0 comments on commit 413d60f

Please sign in to comment.