Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add function to check if cache contains a key #382

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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()
Darkheir marked this conversation as resolved.
Show resolved Hide resolved
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
Loading