From e3f6f688858530193bd136f2fb819bb3207c9525 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Fri, 19 Jan 2024 10:33:24 +0000 Subject: [PATCH] lib/cache: add PutErr to put a value with an error into the cache --- lib/cache/cache.go | 10 ++++++++-- lib/cache/cache_test.go | 16 ++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/cache/cache.go b/lib/cache/cache.go index cbcf78796..fc73eab68 100644 --- a/lib/cache/cache.go +++ b/lib/cache/cache.go @@ -124,8 +124,8 @@ func (c *Cache) Unpin(key string) { c.addPin(key, -1) } -// Put puts a value named key into the cache -func (c *Cache) Put(key string, value interface{}) { +// PutErr puts a value named key with err into the cache +func (c *Cache) PutErr(key string, value interface{}, err error) { c.mu.Lock() defer c.mu.Unlock() if c.noCache() { @@ -134,11 +134,17 @@ func (c *Cache) Put(key string, value interface{}) { entry := &cacheEntry{ value: value, key: key, + err: err, } c.used(entry) c.cache[key] = entry } +// Put puts a value named key into the cache +func (c *Cache) Put(key string, value interface{}) { + c.PutErr(key, value, nil) +} + // GetMaybe returns the key and true if found, nil and false if not func (c *Cache) GetMaybe(key string) (value interface{}, found bool) { c.mu.Lock() diff --git a/lib/cache/cache_test.go b/lib/cache/cache_test.go index 71e1a4dbb..b98dabb54 100644 --- a/lib/cache/cache_test.go +++ b/lib/cache/cache_test.go @@ -81,6 +81,22 @@ func TestGetError(t *testing.T) { assert.Equal(t, 0, len(c.cache)) } +func TestPutErr(t *testing.T) { + c, create := setup(t) + + assert.Equal(t, 0, len(c.cache)) + + c.PutErr("/alien", "slime", errSentinel) + + assert.Equal(t, 1, len(c.cache)) + + fNew, err := c.Get("/alien", create) + require.Equal(t, errSentinel, err) + require.Equal(t, "slime", fNew) + + assert.Equal(t, 1, len(c.cache)) +} + func TestPut(t *testing.T) { c, create := setup(t)