Skip to content

Commit

Permalink
cache generalization
Browse files Browse the repository at this point in the history
make LRU pinning API no-op for non-pinned caches
make sure all operations on zero-size cache are sane
  • Loading branch information
paulnpdev committed Sep 2, 2021
1 parent daae48d commit 30b8b7f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
13 changes: 11 additions & 2 deletions common/cache/lru.go
Expand Up @@ -161,6 +161,9 @@ func NewLRUWithInitialCapacity(initialCapacity, maxSize int) Cache {

// Get retrieves the value stored under the given key
func (c *lru) Get(key interface{}) interface{} {
if c.maxSize == 0 { //
return nil
}
c.mut.Lock()
defer c.mut.Unlock()

Expand Down Expand Up @@ -210,6 +213,9 @@ func (c *lru) PutIfNotExist(key interface{}, value interface{}) (interface{}, er

// Delete deletes a key, value pair associated with a key
func (c *lru) Delete(key interface{}) {
if c.maxSize == 0 {
return
}
c.mut.Lock()
defer c.mut.Unlock()

Expand All @@ -221,7 +227,7 @@ func (c *lru) Delete(key interface{}) {

// Release decrements the ref count of a pinned element.
func (c *lru) Release(key interface{}) {
if !c.pin {
if c.maxSize == 0 || !c.pin {
return
}
c.mut.Lock()
Expand All @@ -244,8 +250,11 @@ func (c *lru) Size() int {
}

// Put puts a new value associated with a given key, returning the existing value (if present)
// allowUpdate flag is used to control overwrite behavior if the value exists
// allowUpdate flag is used to control overwrite behavior if the value exists.
func (c *lru) putInternal(key interface{}, value interface{}, allowUpdate bool) (interface{}, error) {
if c.maxSize == 0 {
return nil, nil
}
c.mut.Lock()
defer c.mut.Unlock()

Expand Down
17 changes: 17 additions & 0 deletions common/cache/lru_test.go
Expand Up @@ -303,3 +303,20 @@ func TestIterator(t *testing.T) {
it.Close()
assert.Equal(t, expected, actual)
}

func TestZeroSizeCache(t *testing.T) {
cache := NewLRU(0)
_, err := cache.PutIfNotExist("A", t)
assert.NoError(t, err)
assert.Equal(t, nil, cache.Get("A"))
assert.Equal(t, 0, cache.Size())
it := cache.Iterator()
assert.False(t, it.HasNext())
it.Close()
cache.Release("A")
cache.Delete("A")
v, err := cache.PutIfNotExist("A", t)
assert.Equal(t, v, t)
assert.Nil(t, err)
assert.Equal(t, 0, cache.Size())
}

0 comments on commit 30b8b7f

Please sign in to comment.