Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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 @@ -233,6 +233,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)
}
12 changes: 12 additions & 0 deletions shard.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,18 @@ 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()
wrappedEntry, err := s.getWrappedEntry(hashedKey)
if err != nil {
s.lock.RUnlock()
return false
}
entryKey := readKeyFromEntry(wrappedEntry)
s.lock.RUnlock()
Comment thread
janisz marked this conversation as resolved.
return key == entryKey
}

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

Expand Down