Skip to content

Commit eb3ed48

Browse files
committed
feat: Add function to check if cache contains a key
1 parent 58fe2d2 commit eb3ed48

File tree

3 files changed

+45
-0
lines changed

3 files changed

+45
-0
lines changed

bigcache.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,13 @@ func (c *BigCache) Iterator() *EntryInfoIterator {
229229
return newIterator(c)
230230
}
231231

232+
// Contains returns whether the givzn kzy exists in cache
233+
func (c *BigCache) Contains(key string) bool {
234+
hashedKey := c.hash.Sum64(key)
235+
shard := c.getShard(hashedKey)
236+
return shard.contains(key, hashedKey)
237+
}
238+
232239
func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {
233240
oldestTimestamp := readTimestampFromEntry(oldestEntry)
234241
if currentTimestamp < oldestTimestamp {

bigcache_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1388,3 +1388,31 @@ func TestRemoveNonExpiredData(t *testing.T) {
13881388
noError(t, err)
13891389
}
13901390
}
1391+
1392+
func TestContainsExists(t *testing.T) {
1393+
t.Parallel()
1394+
1395+
// given
1396+
cache, _ := New(context.Background(), DefaultConfig(5*time.Second))
1397+
value := []byte("value")
1398+
1399+
// when
1400+
cache.Set("key", value)
1401+
exists := cache.Contains("key")
1402+
1403+
// then
1404+
assertEqual(t, true, exists)
1405+
}
1406+
1407+
func TestContainsNotExists(t *testing.T) {
1408+
t.Parallel()
1409+
1410+
// given
1411+
cache, _ := New(context.Background(), DefaultConfig(5*time.Second))
1412+
1413+
// when
1414+
exists := cache.Contains("key")
1415+
1416+
// then
1417+
assertEqual(t, false, exists)
1418+
}

shard.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,16 @@ func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, er
117117
return wrappedEntry, nil
118118
}
119119

120+
func (s *cacheShard) contains(key string, hashedKey uint64) bool {
121+
s.lock.RLock()
122+
defer s.lock.RUnlock()
123+
wrappedEntry, err := s.getWrappedEntry(hashedKey)
124+
if err != nil {
125+
return false
126+
}
127+
return key == readKeyFromEntry(wrappedEntry)
128+
}
129+
120130
func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error {
121131
currentTimestamp := uint64(s.clock.Epoch())
122132

0 commit comments

Comments
 (0)