Skip to content

Commit

Permalink
Merge pull request #3 from mgnsk/feature/range
Browse files Browse the repository at this point in the history
Implement Range method
  • Loading branch information
mgnsk committed Feb 9, 2021
2 parents c2944d1 + a09c832 commit 4b4165b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,27 @@ func (c *Cache) Evict(key interface{}) {
}()
}

// Range calls f sequentially for each key and value present in the cache.
// If f returns false, range stops the iteration.
//
// Range does not necessarily correspond to any consistent snapshot of the cache's
// contents: no key will be visited more than once, but if the value for any key
// is stored or deleted concurrently, Range may reflect any mapping for that key
// from any point during the Range call.
func (c *Cache) Range(f func(key, value interface{}) bool) {
c.records.Range(func(key, value interface{}) bool {
r := value.(*record)
r.mu.RLock()
if !r.alive {
r.mu.RUnlock()
return true
}
v := r.value
r.mu.RUnlock()
return f(key, v)
})
}

func (c *Cache) runLoop() {
ticker := time.NewTicker(SyncInterval)
defer ticker.Stop()
Expand Down
37 changes: 37 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,43 @@ var _ = Describe("eviction callback", func() {
})
})

var _ = Describe("ranging over values", func() {
var (
evicted chan interface{}
c *evcache.Cache
)

BeforeEach(func() {
evicted = make(chan interface{})
c = evcache.New().
WithEvictionCallback(func(key, _ interface{}) {
defer GinkgoRecover()
evicted <- key
}).
Build()
})

AfterEach(func() {
c.Close()
Expect(c.Len()).To(BeZero())
})

Specify("callback does not block record", func() {
_, closer, _ := c.Fetch("key", 100*time.Millisecond, func() (interface{}, error) {
return "value", nil
})
closer.Close()
Expect(c.Len()).To(Equal(1))

c.Range(func(key, value interface{}) bool {
Expect(key).To(Equal("key"))
Expect(<-evicted).To(Equal("key"))
Expect(c.Len()).To(BeZero())
return true
})
})
})

var _ = Describe("Fetch fails with an error", func() {
var (
n = 10
Expand Down

0 comments on commit 4b4165b

Please sign in to comment.