Skip to content

Commit

Permalink
added SetDontTouch()
Browse files Browse the repository at this point in the history
  • Loading branch information
latitov committed Oct 7, 2022
1 parent 40f09cf commit 281c8fa
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
19 changes: 16 additions & 3 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ func (c *Cache[K, V]) updateExpirations(fresh bool, elem *list.Element) {

// set creates a new item, adds it to the cache and then returns it.
// Not concurrently safe.
func (c *Cache[K, V]) set(key K, value V, ttl time.Duration) *Item[K, V] {
func (c *Cache[K, V]) set(key K, value V, ttl time.Duration, touch bool) *Item[K, V] {
if ttl == DefaultTTL {
ttl = c.options.ttl
}
Expand All @@ -136,7 +136,9 @@ func (c *Cache[K, V]) set(key K, value V, ttl time.Duration) *Item[K, V] {
// update/overwrite an existing item
item := elem.Value.(*Item[K, V])
item.update(value, ttl)
c.updateExpirations(false, elem)
if touch {
c.updateExpirations(false, elem)
}

return item
}
Expand Down Expand Up @@ -242,7 +244,18 @@ func (c *Cache[K, V]) Set(key K, value V, ttl time.Duration) *Item[K, V] {
c.items.mu.Lock()
defer c.items.mu.Unlock()

return c.set(key, value, ttl)
return c.set(key, value, ttl, true)
}

// Set creates a new item from the provided key and value, adds
// it to the cache and then returns it. If an item associated with the
// provided key already exists, the new item overwrites the existing one.
// DOES NOT UPDATE EXPIRATIONS
func (c *Cache[K, V]) SetDontTouch(key K, value V, ttl time.Duration) *Item[K, V] {
c.items.mu.Lock()
defer c.items.mu.Unlock()

return c.set(key, value, ttl, false)
}

// Get retrieves an item from the cache by the provided key.
Expand Down
2 changes: 1 addition & 1 deletion cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ func Test_Cache_set(t *testing.T) {
total++
}

item := cache.set(c.Key, "value123", c.TTL)
item := cache.set(c.Key, "value123", c.TTL, true)

if c.ExpectFns {
assert.Equal(t, 2, insertFnsCalls)
Expand Down

0 comments on commit 281c8fa

Please sign in to comment.