Skip to content

Commit

Permalink
Add Has and Range helper methods
Browse files Browse the repository at this point in the history
  • Loading branch information
mgnsk committed Aug 9, 2024
1 parent 8f01c70 commit 7c407a6
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 2 deletions.
32 changes: 30 additions & 2 deletions internal/backend/backend.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,15 @@ func (b *Backend[K, V]) Len() int {
return b.list.Len()
}

// Has returns whether the element for key is initialized.
func (b *Backend[K, V]) Has(key K) bool {
b.mu.Lock()
defer b.mu.Unlock()

elem, ok := b.xmap[key]
return ok && elem.Value.state == stateInitialized
}

// Load an initialized element.
func (b *Backend[K, V]) Load(key K) (value V, ok bool) {
b.mu.Lock()
Expand All @@ -78,12 +87,12 @@ func (b *Backend[K, V]) Load(key K) (value V, ok bool) {
return zero, false
}

// Keys returns initialized cache keys in no particular order or consistency.
// Keys returns keys for initialized cache elements in no particular order or consistency.
func (b *Backend[K, V]) Keys() []K {
b.mu.Lock()
defer b.mu.Unlock()

keys := make([]K, 0, len(b.xmap))
keys := make([]K, 0, b.list.Len())
b.list.Do(func(elem *ringlist.Element[Record[K, V]]) bool {
keys = append(keys, elem.Value.Key)
return true
Expand All @@ -92,6 +101,25 @@ func (b *Backend[K, V]) Keys() []K {
return keys
}

// Range iterates over initialized cache elements in no particular order or consistency.
// If f returns false, range stops the iteration.
//
// f may modify the cache.
func (b *Backend[K, V]) Range(f func(key K, value V) bool) {
keys := b.Keys()

for _, key := range keys {
b.mu.Lock()
elem, ok := b.xmap[key]
initialized := ok && elem.Value.state == stateInitialized
b.mu.Unlock()

if initialized && !f(key, elem.Value.Value) {
return
}
}
}

// Evict an element.
func (b *Backend[K, V]) Evict(key K) (V, bool) {
b.mu.Lock()
Expand Down
22 changes: 22 additions & 0 deletions internal/backend/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,14 @@ func TestFetchCallbackBlocks(t *testing.T) {
})
})

t.Run("non-blocking Has", func(t *testing.T) {
b.Fetch("key1", func() (string, error) {
return "value1", nil
})

Equal(t, b.Has("key1"), true)
})

t.Run("non-blocking Keys", func(t *testing.T) {
b.Fetch("key1", func() (string, error) {
return "value1", nil
Expand All @@ -73,6 +81,20 @@ func TestFetchCallbackBlocks(t *testing.T) {
Equal(t, keys[0], "key1")
})

t.Run("non-blocking Range", func(t *testing.T) {
b.Fetch("key1", func() (string, error) {
return "value1", nil
})

var keys []string
b.Range(func(key string, _ string) bool {
keys = append(keys, key)
return true
})
Equal(t, len(keys), 1)
Equal(t, keys[0], "key1")
})

t.Run("Store discards the key", func(t *testing.T) {
b.Store("key", "value1")

Expand Down

0 comments on commit 7c407a6

Please sign in to comment.