Skip to content

Commit

Permalink
fix: add lru peek and update
Browse files Browse the repository at this point in the history
  • Loading branch information
shaj13 committed Sep 26, 2020
1 parent b69c1ab commit 710ff6e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
26 changes: 23 additions & 3 deletions store/lru.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,18 +104,38 @@ func (l *LRU) Load(key string, _ *http.Request) (interface{}, bool, error) {
return nil, false, nil
}

if ele, hit := l.cache[key]; hit {
if ele, ok := l.cache[key]; ok {
r := ele.Value.(*record)

if l.TTL > 0 {
if time.Now().UTC().After(r.Exp) {
l.removeElement(ele)
return nil, false, ErrCachedExp
return nil, ok, ErrCachedExp
}
}

l.ll.MoveToFront(ele)
return r.Value, true, nil
return r.Value, ok, nil
}

return nil, false, nil
}

// Peek returns the value stored in the Cache for a key
// without updating the "recently used", or nil if no value is present.
// The ok result indicates whether value was found in the Cache.
func (l *LRU) Peek(key string, _ *http.Request) (interface{}, bool, error) {
if ele, ok := l.cache[key]; ok {
r := ele.Value.(*record)

if l.TTL > 0 {
if time.Now().UTC().After(r.Exp) {
l.removeElement(ele)
return nil, ok, ErrCachedExp
}
}

return r.Value, ok, nil
}

return nil, false, nil
Expand Down
16 changes: 15 additions & 1 deletion store/lru_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,20 @@ func TestLRUUpdate(t *testing.T) {
assert.Equal(t, 0, r.Value)
}

func TestLRUPeek(t *testing.T) {
cache := New(2)
cache.Store("1", 1, nil)
cache.Store("2", 2, nil)

v, ok, err := cache.Peek("1", nil)
r := cache.ll.Back().Value.(*record)

assert.NoError(t, err)
assert.True(t, ok)
assert.Equal(t, 1, v)
assert.Equal(t, "1", r.Key)
}

func TestTTLLRU(t *testing.T) {
cache := New(2)
cache.TTL = time.Nanosecond * 100
Expand All @@ -114,7 +128,7 @@ func TestTTLLRU(t *testing.T) {
v, ok, err := cache.Load("key", nil)

assert.Equal(t, ErrCachedExp, err)
assert.False(t, ok)
assert.True(t, ok)
assert.Nil(t, v)
}

Expand Down

0 comments on commit 710ff6e

Please sign in to comment.