Skip to content

Commit

Permalink
feat: Add function to check if cache contains a key
Browse files Browse the repository at this point in the history
  • Loading branch information
Darkheir committed Oct 28, 2023
1 parent 58fe2d2 commit 0086967
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
7 changes: 7 additions & 0 deletions bigcache.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,13 @@ func (c *BigCache) Iterator() *EntryInfoIterator {
return newIterator(c)
}

// Contains returns whether the given key exists in cache
func (c *BigCache) Contains(key string) bool {
hashedKey := c.hash.Sum64(key)
shard := c.getShard(hashedKey)
return shard.contains(key, hashedKey)
}

func (c *BigCache) onEvict(oldestEntry []byte, currentTimestamp uint64, evict func(reason RemoveReason) error) bool {
oldestTimestamp := readTimestampFromEntry(oldestEntry)
if currentTimestamp < oldestTimestamp {
Expand Down
28 changes: 28 additions & 0 deletions bigcache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1388,3 +1388,31 @@ func TestRemoveNonExpiredData(t *testing.T) {
noError(t, err)
}
}

func TestContainsExists(t *testing.T) {
t.Parallel()

// given
cache, _ := New(context.Background(), DefaultConfig(5*time.Second))
value := []byte("value")

// when
cache.Set("key", value)
exists := cache.Contains("key")

// then
assertEqual(t, true, exists)
}

func TestContainsNotExists(t *testing.T) {
t.Parallel()

// given
cache, _ := New(context.Background(), DefaultConfig(5*time.Second))

// when
exists := cache.Contains("key")

// then
assertEqual(t, false, exists)
}
10 changes: 10 additions & 0 deletions shard.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,16 @@ func (s *cacheShard) getValidWrapEntry(key string, hashedKey uint64) ([]byte, er
return wrappedEntry, nil
}

func (s *cacheShard) contains(key string, hashedKey uint64) bool {
s.lock.RLock()
defer s.lock.RUnlock()
wrappedEntry, err := s.getWrappedEntry(hashedKey)
if err != nil {
return false
}
return key == readKeyFromEntry(wrappedEntry)
}

func (s *cacheShard) set(key string, hashedKey uint64, entry []byte) error {
currentTimestamp := uint64(s.clock.Epoch())

Expand Down

0 comments on commit 0086967

Please sign in to comment.