diff --git a/README.md b/README.md index 018eea8..94c13f6 100644 --- a/README.md +++ b/README.md @@ -85,10 +85,12 @@ cache.Set("a", 1) // Expires in a minute, cache.SetWithTTL("b", 2, 10*time.Second) // and this one in ten seconds. ``` -An expired entry is a miss, but takes up room until it is evicted, set again, deleted or -cleared, and reads of it still count with the policy. Reads look at a copy of the time that a -timer updates every 10 ms, and at the time itself near a deadline. A `Get` that hits took -11–15% longer through the wrapper, and a `Set` 17 ns longer (`tinylfu`, Apple M3 Max). +Expired entries are misses but still count toward `Len`. Call `cache.PurgeExpired(nil)` to +remove them, or pass a function that releases what they hold. + +Reads still count with the policy, even for expired entries. They look at a copy of the time +that a timer updates every 10 ms, and at the time itself near a deadline. A `Get` that hits +took 11–15% longer through the wrapper, and a `Set` 17 ns longer (`tinylfu`, Apple M3 Max). ## Benchmarks @@ -163,7 +165,7 @@ own. - **No sizes in bytes or weights.** Capacity counts entries; set it from a typical entry size. - **No loader** that fetches a missing key once for all the callers that ask for it. -- **No cleanup of expired entries**; see [Expiry](#expiry). +- **No background expiry**: call `PurgeExpired` yourself ([Expiry](#expiry)). - **Overwrites do not scale with CPUs**; otter's do ([Benchmarks](#benchmarks)). For any of these, use [otter](https://github.com/maypok86/otter). diff --git a/evict.go b/evict.go index d05329f..6294d97 100644 --- a/evict.go +++ b/evict.go @@ -29,7 +29,8 @@ // // Keys are compared with ==, as in a map. A key that is not equal to itself, // which is to say one with a NaN in it, can be set but not found again: its -// entry is out of reach until it is evicted or the cache is cleared. +// entry stays until it is evicted, removed by DeleteFunc, or the cache is +// cleared. // // # Capacity and shards // @@ -94,6 +95,16 @@ type Cache[K comparable, V any] interface { // Delete removes key and returns the value it had. Delete(key K) (value V, ok bool) + // DeleteFunc removes the entries for which del returns true and reports + // how many it removed. It visits one shard at a time, without recording + // accesses, and tests and removes each entry at once with respect to + // writes to its key; the pass as a whole is not a snapshot. + // + // del runs with the shard locked: it must not call back into the cache, + // and should return promptly. If it panics, the entries removed before + // stay removed. + DeleteFunc(del func(K, V) bool) int + // Len returns the number of entries in the cache. While the cache is // being written to, the shards are counted one after the other and // the sum may be one that the cache never held at any one moment. diff --git a/expire/expire.go b/expire/expire.go index 143b836..2db6e26 100644 --- a/expire/expire.go +++ b/expire/expire.go @@ -11,22 +11,24 @@ // // An entry that has expired is not found: Get, Peek, GetMany and Delete report // it missing, All passes it over, and SetIfAbsent stores a new entry in its -// place. It stays in the cache all the same, until it is evicted, replaced or -// deleted, or the cache is cleared. Until then it takes up room, Len counts -// it, and what it holds on to is not garbage. +// place. It stays in the cache all the same, until it is evicted, replaced, +// deleted or purged, or the cache is cleared. Until then it takes up room and +// Len counts it. Call [Cache.PurgeExpired] to remove expired entries; the +// cache does not run a background sweep. // // Set and SetIfAbsent hand an expired entry back when they push it out or -// replace it, as they do any entry, so that what it holds on to can be -// released. Delete and Clear do not. Where values have to be released, use the -// wrapped cache for those: its Delete and All return entries whether they have -// expired or not, and [Entry.Value] gives their values. +// replace it, as they do any entry, and PurgeExpired hands those it removes to +// a function of yours, so that what they hold on to can be released. Delete +// and Clear do not. Where values have to be released, use the wrapped cache +// for those: its Delete and All return entries whether they have expired or +// not, and [Entry.Value] gives their values. // // A read that finds an expired entry leaves it there, for the Set that usually // follows: that replaces the entry in place, and the policy goes on treating -// it as the entry it was, which it would not after a Delete. Reads count with -// the policy, expired or not, so an entry that is still asked for but never set -// again stays; delete its key when there is no new value for it. Expired or -// not, there are never more entries than the capacity of the cache. +// it as the entry it was, which it would not after a Delete or a purge. Reads +// count with the policy, expired or not, so an entry that is still asked for +// but never set again stays until it is deleted or purged. Expired or not, +// there are never more entries than the capacity of the cache. // // # Time // @@ -46,9 +48,10 @@ // # Statistics // // Wrapped in stats, as stats.Wrap(expire.Wrap(...)), a cache counts a read of -// an expired entry as a miss. The stats.Cache has no SetWithTTL: call that of -// the expire.Cache, and the entries it evicts go uncounted. Wrapped the other -// way around, a read of an expired entry counts as a hit. +// an expired entry as a miss. The stats.Cache has no SetWithTTL or +// PurgeExpired: call those of the expire.Cache, and the entries that +// SetWithTTL evicts go uncounted. Wrapped the other way around, a read of an +// expired entry counts as a hit. // // # Cost // @@ -348,9 +351,9 @@ func (c *Cache[K, V]) SetWithTTL(key K, value V, ttl time.Duration) (oldKey K, o // expires in between. Those that find an expired entry take turns replacing // it, and look again first. The exception is a value stored just after one of // them has looked: by a Set of key, or by a SetIfAbsent that found no entry -// because the expired one had just left the cache. That value is replaced and -// handed back, with oldKey == key, so two goroutines may each be told that -// they stored theirs. +// because the expired one had just left the cache, which PurgeExpired makes +// more likely. That value is replaced and handed back, with oldKey == key, so +// two goroutines may each be told that they stored theirs. func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { e := Entry[V]{value: value, deadline: c.clock.deadline(c.ttl)} a, present, oldKey, old, evicted := c.cache.SetIfAbsent(key, e) @@ -401,6 +404,42 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { return e.value, true } +// DeleteFunc calls del only for entries that have not expired, removing those +// for which it returns true, and reports how many it removed. Expired entries +// are left for [Cache.PurgeExpired]. del runs with a shard of the wrapped +// cache locked; see [evict.Cache]. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + return c.cache.DeleteFunc(func(k K, e Entry[V]) bool { + return !c.expired(e.deadline) && del(k, e.value) + }) +} + +// PurgeExpired removes entries whose deadlines are at or before the time the +// call began and returns the number removed. It checks the current entry as +// it visits each shard: a value refreshed past the cutoff is not removed. +// Entries that expire during the scan are left for the next call. A key that +// is set again after its entry was purged comes in as a new entry, as after +// Delete. +// +// Unless removed is nil, PurgeExpired calls it with the key and the value of +// each entry it removes, so that what they hold on to can be released. It +// runs with a shard of the wrapped cache locked, as the del of DeleteFunc +// does: it must not call back into the cache, and should return promptly; +// collect what takes longer and deal with it after PurgeExpired returns. If +// it panics, the entry it was called with stays. +func (c *Cache[K, V]) PurgeExpired(removed func(K, V)) int { + cutoff := c.clock.read() + return c.cache.DeleteFunc(func(k K, e Entry[V]) bool { + if e.deadline > cutoff { + return false + } + if removed != nil { + removed(k, e.value) + } + return true + }) +} + // Len returns the number of entries in the cache, those that have expired // included. func (c *Cache[K, V]) Len() int { return c.cache.Len() } diff --git a/expire/expire_test.go b/expire/expire_test.go index 06f3e68..d684bcc 100644 --- a/expire/expire_test.go +++ b/expire/expire_test.go @@ -1,6 +1,7 @@ package expire_test import ( + "maps" "math" "math/rand/v2" "runtime" @@ -247,6 +248,71 @@ func TestExpiry(t *testing.T) { } } +func TestPurgeExpired(t *testing.T) { + t.Parallel() + + for name, newCache := range policies { + t.Run(name, func(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + inner := stats.Wrap(newCache()) + c := expire.WrapWith(inner, time.Second, clock) + c.Set("due", 1) + c.SetWithTTL("later", 2, time.Second+1) + inner.Set("zero", expire.Entry[int]{}) // A zero Entry is already expired. + clock.Advance(time.Second) + clock.Lag(time.Second) // Purging must use the clock, not the readers' copy. + + removed := map[string]int{} + n := c.PurgeExpired(func(k string, v int) { + if _, ok := removed[k]; ok { + t.Errorf("PurgeExpired handed over %q twice", k) + } + removed[k] = v + }) + if n != 2 { + t.Fatalf("PurgeExpired = %d, want 2", n) + } + if want := map[string]int{"due": 1, "zero": 0}; !maps.Equal(removed, want) { + t.Errorf("PurgeExpired handed over %v, want %v", removed, want) + } + if s := inner.Stats(); s.Len != 1 || s.Evictions != 0 || s.Hits != 0 || s.Misses != 0 { + t.Errorf("stats after purge = %+v, want one entry and no hits, misses or evictions", s) + } + if v, ok := c.Peek("later"); !ok || v != 2 { + t.Errorf("Peek(later) = %d, %t, want 2, true", v, ok) + } + if n := c.PurgeExpired(nil); n != 0 { + t.Errorf("repeat PurgeExpired = %d, want 0", n) + } + }) + } +} + +func TestDeleteFuncSkipsExpired(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + inner := lru.New[string, expire.Entry[int]](2) + c := stats.Wrap(expire.WrapWith(inner, time.Second, clock)) + c.Set("expired", 1) + clock.Advance(time.Second) + c.Set("live", 2) + n := c.DeleteFunc(func(k string, v int) bool { + if k != "live" || v != 2 { + t.Errorf("DeleteFunc visited %s=%d, want live=2", k, v) + } + return true + }) + if n != 1 { + t.Errorf("DeleteFunc = %d, want 1", n) + } + if e, ok := inner.Peek("expired"); !ok || e.Value() != 1 || inner.Len() != 1 { + t.Error("DeleteFunc did not leave just the expired entry") + } +} + // An expired entry that leaves the cache is handed back by Set, as any entry // is, whether it is replaced or evicted. func TestExpiredLeave(t *testing.T) { @@ -328,11 +394,11 @@ func TestTTLBounds(t *testing.T) { } // hooked is a cache that runs a function after each Peek, to let an entry come -// or go between SetWithTTL's look and its Set, and another after each -// SetIfAbsent. +// or go between SetWithTTL's look and its Set. It can also interpose after a +// SetIfAbsent or before a DeleteFunc scan. type hooked struct { evict.Cache[string, expire.Entry[int]] - after, afterAbsent func() + after, afterAbsent, beforeScan func() } func (h *hooked) Peek(key string) (expire.Entry[int], bool) { @@ -351,6 +417,72 @@ func (h *hooked) SetIfAbsent(key string, e expire.Entry[int]) (actual expire.Ent return actual, present, oldKey, oldValue, evicted } +func (h *hooked) DeleteFunc(del func(string, expire.Entry[int]) bool) int { + if h.beforeScan != nil { + h.beforeScan() + } + return h.Cache.DeleteFunc(del) +} + +// A refresh between taking the cutoff and scanning a shard must survive. +// A deadline that passes in that interval belongs to the next purge. +func TestPurgeExpiredCutoff(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + h := &hooked{Cache: lru.New[string, expire.Entry[int]](3)} + c := expire.WrapWith(h, time.Second, clock) + c.Set("expired", 1) + c.Set("refresh", 2) + c.SetWithTTL("later", 3, 2*time.Second) + clock.Advance(time.Second) + h.beforeScan = func() { + clock.Advance(time.Second) + c.Set("refresh", 4) + } + if n := c.PurgeExpired(nil); n != 1 { + t.Fatalf("PurgeExpired = %d, want 1", n) + } + if v, ok := c.Peek("refresh"); !ok || v != 4 { + t.Error("purge removed the refreshed value") + } + if _, ok := h.Peek("later"); !ok { + t.Error("purge removed an entry that expired during the scan") + } + h.beforeScan = nil + if n := c.PurgeExpired(nil); n != 1 { + t.Errorf("next PurgeExpired = %d, want 1", n) + } +} + +// A panic in the function that PurgeExpired hands entries to stops the purge, +// and the entry it was handed stays. +func TestPurgeExpiredPanics(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + inner := lru.New[string, expire.Entry[int]](2, lru.WithShards(1)) + c := expire.WrapWith(inner, time.Second, clock) + c.Set("a", 1) + c.Set("b", 2) + clock.Advance(time.Second) + const stop = "stop the purge" + func() { + defer func() { + if p := recover(); p != stop { + t.Errorf("PurgeExpired panic = %v, want %q", p, stop) + } + }() + c.PurgeExpired(func(string, int) { panic(stop) }) + }() + if inner.Len() != 2 { + t.Errorf("Len() = %d after a panic in the first call, want 2", inner.Len()) + } + if n := c.PurgeExpired(nil); n != 2 { + t.Errorf("PurgeExpired after a panic = %d, want 2", n) + } +} + // SetWithTTL with a time to live of zero or less decides by what it sees when // it looks. An entry of key that leaves in between is stored as Set would // store it: with eviction, if that is what it takes. One that comes in between @@ -825,6 +957,16 @@ func TestConcurrent(t *testing.T) { wg.Go(func() { for !done.Load() { clock.Advance(time.Millisecond) + calls := 0 + n := c.PurgeExpired(func(k string, v int) { + calls++ + if strconv.Itoa(v) != k { + t.Errorf("PurgeExpired handed over %q=%d", k, v) + } + }) + if calls != n { + t.Errorf("PurgeExpired removed %d entries and handed over %d", n, calls) + } time.Sleep(time.Microsecond) } }) @@ -873,6 +1015,10 @@ func TestConcurrent(t *testing.T) { for k, v := range c.All() { t.Errorf("All yields %q=%d after every entry expired", k, v) } + c.PurgeExpired(nil) + if c.Len() != 0 { + t.Errorf("Len() = %d after purging every entry", c.Len()) + } }) } } diff --git a/internal/cachetest/cachetest.go b/internal/cachetest/cachetest.go index 014bacf..6852371 100644 --- a/internal/cachetest/cachetest.go +++ b/internal/cachetest/cachetest.go @@ -92,6 +92,7 @@ func Run(t *testing.T, f Factories) { t.Run("Full", func(t *testing.T) { t.Parallel(); testFull(t, f.Int) }) t.Run("Clear", func(t *testing.T) { t.Parallel(); testClear(t, f.Int) }) t.Run("All", func(t *testing.T) { t.Parallel(); testAll(t, f.Int) }) + t.Run("DeleteFunc", func(t *testing.T) { t.Parallel(); testDeleteFunc(t, f.Int) }) t.Run("Strings", func(t *testing.T) { t.Parallel(); testStrings(t, f.String) }) t.Run("Model", func(t *testing.T) { t.Parallel(); testModel(t, f.Int) }) t.Run("Concurrent", func(t *testing.T) { t.Parallel(); testConcurrent(t, f.Int) }) @@ -424,6 +425,62 @@ func testAll(t *testing.T, newCache Factory[int, int]) { } } +func testDeleteFunc(t *testing.T, newCache Factory[int, int]) { + t.Helper() + + for _, shards := range []int{1, 8} { + c := newCache(80, shards) + // Fill the queues and give policies that keep ghosts some keys to + // remember. Only resident entries should be passed to del. + for key := range 300 { + c.Set(key, -key) + } + want := maps.Collect(c.All()) + seen := map[int]int{} + n := c.DeleteFunc(func(k, v int) bool { + if _, ok := seen[k]; ok { + t.Errorf("DeleteFunc visited %d twice", k) + } + seen[k] = v + return k%2 == 0 + }) + if !maps.Equal(seen, want) { + t.Fatalf("DeleteFunc visited %v, want %v", seen, want) + } + maps.DeleteFunc(want, func(k, _ int) bool { return k%2 == 0 }) + if removed := len(seen) - len(want); n != removed { + t.Errorf("DeleteFunc = %d, want %d", n, removed) + } + if c.Len() != len(want) || !maps.Equal(maps.Collect(c.All()), want) { + t.Fatal("DeleteFunc did not leave just the nonmatching entries") + } + } + + // A panic leaves the earlier deletions in place and the shard unlocked. + c := newCache(2, 1) + c.Set(1, 1) + c.Set(2, 2) + const stop = "stop the scan" + func() { + defer func() { + if p := recover(); p != stop { + t.Errorf("DeleteFunc panic = %v, want %q", p, stop) + } + }() + first := true + c.DeleteFunc(func(_, _ int) bool { + if !first { + panic(stop) + } + first = false + return true + }) + }() + if n := c.DeleteFunc(func(_, _ int) bool { return true }); n != 1 { + t.Errorf("DeleteFunc after panic = %d, want 1", n) + } +} + func testStrings(t *testing.T, newCache Factory[string, string]) { t.Helper() @@ -677,6 +734,13 @@ func testConcurrent(t *testing.T, newCache Factory[int, int]) { if n := c.Len(); n < 0 || n > tt.capacity { t.Errorf("Len() = %d with capacity %d", n, tt.capacity) } + case op < 996: + if n := c.DeleteFunc(func(k, v int) bool { + check("DeleteFunc", k, v) + return k == key + }); n > 1 { + t.Errorf("DeleteFunc removed %d entries of key %d", n, key) + } case op < 999: n := 0 for k, v := range c.All() { @@ -768,6 +832,9 @@ func testKeyIdentity(t *testing.T, newCache Factory[float64, int]) { if a, present, _, _, _ := c.SetIfAbsent(nan, 5); present || a != 5 { t.Errorf("%d shards: SetIfAbsent(NaN) = %d, %t, want 5 stored", shards, a, present) } + if n := c.DeleteFunc(func(k float64, _ int) bool { return math.IsNaN(k) }); n != 3 || c.Len() != 1 { + t.Errorf("%d shards: DeleteFunc(NaN) = %d, Len() = %d, want 3, 1", shards, n, c.Len()) + } for i := range 1000 { c.Set(float64(i), i) c.Set(nan, i) @@ -840,6 +907,18 @@ func letsGo[K comparable, V any](t *testing.T, newCache Factory[K, V], ghosts fl t.Errorf("capacity %d, %d shards: %d blobs are alive after Clear", tt.capacity, tt.shards, got) } + // With no readers to wait for, a sweep releases even a single + // removed entry; it need not wait for the next batch of writes. + key, value, blob := entry(0) + c.Set(key, value) + ref := weak.Make(blob) + if n := c.DeleteFunc(func(K, V) bool { return true }); n != 1 { + t.Fatalf("DeleteFunc = %d, want 1", n) + } + if got := Alive([]weak.Pointer[Blob]{ref}, 0); got != 0 { + t.Error("DeleteFunc kept a removed entry alive") + } + // Keep the cache itself reachable until here; otherwise there // would be nothing to check. runtime.KeepAlive(c) diff --git a/internal/cachetest/compare.go b/internal/cachetest/compare.go index afedf4c..94dac4d 100644 --- a/internal/cachetest/compare.go +++ b/internal/cachetest/compare.go @@ -19,6 +19,7 @@ const ( Set SetIfAbsent Delete + DeleteFunc Clear ) @@ -43,8 +44,10 @@ func RandomOps(rng *rand.Rand, keys, n int) iter.Seq[Op] { op.Kind = Set case p < 900: op.Kind = SetIfAbsent - case p < 999: + case p < 998: op.Kind = Delete + case p < 999: + op.Kind = DeleteFunc default: op.Kind = Clear } @@ -74,7 +77,11 @@ func BytesOps(data []byte) iter.Seq[Op] { op.Kind = Delete default: // One byte in eight would be too many. - if op.Kind = Delete; b == 255 { + op.Kind = Delete + switch b { + case 254: + op.Kind = DeleteFunc + case 255: op.Kind = Clear } } @@ -85,6 +92,22 @@ func BytesOps(data []byte) iter.Seq[Op] { } } +// DeleteEach is DeleteFunc for a model: it goes over All and deletes the +// entries that del matches one by one, which is as good as at once for a +// cache that only one goroutine uses. +func DeleteEach[K comparable, V any](c evict.Cache[K, V], del func(K, V) bool) int { + var keys []K + for k, v := range c.All() { + if del(k, v) { + keys = append(keys, k) + } + } + for _, k := range keys { + c.Delete(k) + } + return len(keys) +} + // Compare applies the operations to both caches and fails the test as soon as // they disagree: about what an operation returns, about how many entries // there are, or about the entries that All yields and their order. @@ -138,6 +161,11 @@ func Compare(t *testing.T, got, want evict.Cache[int, int], ops iter.Seq[Op]) { if gv != wv || gok != wok { t.Fatalf("step %d: Delete(%d) = %d, %t, want %d, %t", step, op.Key, gv, gok, wv, wok) } + case DeleteFunc: + del := func(k, v int) bool { return (k+v)%8 == op.Key%8 } + if g, w := got.DeleteFunc(del), want.DeleteFunc(del); g != w { + t.Fatalf("step %d: DeleteFunc = %d, want %d", step, g, w) + } case Clear: got.Clear() want.Clear() diff --git a/internal/cslab/cslab.go b/internal/cslab/cslab.go index 4d261a7..11546a8 100644 --- a/internal/cslab/cslab.go +++ b/internal/cslab/cslab.go @@ -892,6 +892,22 @@ func (s *Slab[K, V]) Reset() (mark uint64) { return s.readers.time.Load() } +// DeleteFunc visits the entries in the list at head and calls remove on those +// for which del returns true. remove must unlink and remove just that node. +// The caller holds the shard lock. +func (s *Slab[K, V]) DeleteFunc(head uint32, del func(K, V) bool, remove func(uint32)) int { + n := 0 + for idx := s.Links[head].Next; idx != head; { + next := s.Links[idx].Next // remove reuses the link. + if e := &s.Nodes[idx]; del(e.Key, e.Value) { + remove(idx) + n++ + } + idx = next + } + return n +} + // PushFront links node idx in as the first node of the list at head. It is // for writers. func (s *Slab[K, V]) PushFront(head, idx uint32) { diff --git a/internal/slab/slab.go b/internal/slab/slab.go index 2224157..70a7dfc 100644 --- a/internal/slab/slab.go +++ b/internal/slab/slab.go @@ -251,6 +251,22 @@ func (s *Slab[K, V]) Reset() { s.resetLists() } +// DeleteFunc visits the entries in the list at head and calls remove on those +// for which del returns true. remove must unlink and remove just that node. +// The caller holds the shard lock. +func (s *Slab[K, V]) DeleteFunc(head uint32, del func(K, V) bool, remove func(uint32)) int { + n := 0 + for idx := s.Nodes[head].Next; idx != head; { + next := s.Nodes[idx].Next // remove reuses the link. + if e := &s.Nodes[idx]; del(e.Key, e.Value) { + remove(idx) + n++ + } + idx = next + } + return n +} + // PushFront links node idx in as the first node of the list at head. func (s *Slab[K, V]) PushFront(head, idx uint32) { nodes := s.Nodes diff --git a/lru/lru.go b/lru/lru.go index c7aaae9..02497c7 100644 --- a/lru/lru.go +++ b/lru/lru.go @@ -230,14 +230,36 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { s.mu.Lock() if idx := s.slab.Find(hash, key); idx != 0 { value, ok = s.slab.Nodes[idx].Value, true - s.slab.Unlink(idx) - s.slab.Remove(idx) + s.remove(idx) } s.mu.Unlock() return value, ok } +func (s *shard[K, V]) remove(idx uint32) { + s.slab.Unlink(idx) + s.slab.Remove(idx) +} + +// DeleteFunc removes the entries for which del returns true and reports how +// many it removed. del runs under one shard's lock at a time and must not +// call back into the cache. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + n := 0 + for i := range c.shards { + n += c.shards[i].deleteFunc(del) + } + return n +} + +func (s *shard[K, V]) deleteFunc(del func(K, V) bool) int { + s.mu.Lock() + defer s.mu.Unlock() + + return s.slab.DeleteFunc(queue, del, s.remove) +} + // Len returns the number of entries in the cache. func (c *Cache[K, V]) Len() int { n := 0 @@ -312,6 +334,7 @@ var ( _ = (*Cache[int, int]).Set _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete + _ = (*Cache[int, int]).DeleteFunc _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear _ = (*Cache[int, int]).All diff --git a/lru/lru_test.go b/lru/lru_test.go index 5eda30d..7eb0533 100644 --- a/lru/lru_test.go +++ b/lru/lru_test.go @@ -178,6 +178,8 @@ func (m *model) Delete(key int) (int, bool) { return value, true } +func (m *model) DeleteFunc(del func(int, int) bool) int { return cachetest.DeleteEach(m, del) } + func (m *model) Len() int { return len(m.entries) } func (m *model) Cap() int { return m.capacity } func (m *model) Clear() { m.entries = nil } diff --git a/s3fifo/s3fifo.go b/s3fifo/s3fifo.go index efcd756..71c6323 100644 --- a/s3fifo/s3fifo.go +++ b/s3fifo/s3fifo.go @@ -675,17 +675,8 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { s.mu.Lock() if idx := s.slab.Find(hash, key); idx != 0 { value, ok = s.slab.Nodes[idx].Value, true - if s.slab.Links[idx].Tag&1 == main { - s.mains-- - } else { - s.smalls-- - } - s.slab.Unlink(idx) - s.slab.Remove(idx) - } - // An entry has no ghost, unless ghosts have to come back more than - // once and this one has only come back. - if !ok || s.returns > 1 { + s.remove(idx) + } else { s.ghosts.Remove(ghostOf(hash, tagOf(h, small))) } s.mu.Unlock() @@ -693,6 +684,41 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { return value, ok } +func (s *shard[K, V]) remove(idx uint32) { + tag := s.slab.Links[idx].Tag + if tag&1 == main { + s.mains-- + } else { + s.smalls-- + } + // An entry has no ghost, unless ghosts have to come back more than + // once and this one has only come back. + if s.returns > 1 { + s.ghosts.Remove(ghostOf(s.slab.Hash(idx), tag)) + } + s.slab.Unlink(idx) + s.slab.Remove(idx) +} + +// DeleteFunc removes the entries for which del returns true and reports how +// many it removed. del runs under one shard's lock at a time and must not +// call back into the cache. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + n := 0 + for i := range c.shards { + n += c.shards[i].deleteFunc(del) + } + return n +} + +func (s *shard[K, V]) deleteFunc(del func(K, V) bool) int { + s.mu.Lock() + defer s.mu.Unlock() + defer s.slab.Reclaim() + + return s.slab.DeleteFunc(main, del, s.remove) + s.slab.DeleteFunc(small, del, s.remove) +} + // Len returns the number of entries in the cache. func (c *Cache[K, V]) Len() int { n := 0 @@ -776,6 +802,7 @@ var ( _ = (*Cache[int, int]).Set _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete + _ = (*Cache[int, int]).DeleteFunc _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear _ = (*Cache[int, int]).All diff --git a/s3fifo/s3fifo_test.go b/s3fifo/s3fifo_test.go index 7741a06..8efa5e3 100644 --- a/s3fifo/s3fifo_test.go +++ b/s3fifo/s3fifo_test.go @@ -672,6 +672,8 @@ func (m *model) Delete(key int) (int, bool) { return e.value, true } +func (m *model) DeleteFunc(del func(int, int) bool) int { return cachetest.DeleteEach(m, del) } + func (m *model) Len() int { return len(m.small) + len(m.main) } func (m *model) Cap() int { return m.capacity } diff --git a/sieve/sieve.go b/sieve/sieve.go index ed26ee8..29e493c 100644 --- a/sieve/sieve.go +++ b/sieve/sieve.go @@ -462,6 +462,25 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { return value, ok } +// DeleteFunc removes the entries for which del returns true and reports how +// many it removed. del runs under one shard's lock at a time and must not +// call back into the cache. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + n := 0 + for i := range c.shards { + n += c.shards[i].deleteFunc(del) + } + return n +} + +func (s *shard[K, V]) deleteFunc(del func(K, V) bool) int { + s.mu.Lock() + defer s.mu.Unlock() + defer s.slab.Reclaim() + + return s.slab.DeleteFunc(queue, del, s.remove) +} + // Len returns the number of entries in the cache. func (c *Cache[K, V]) Len() int { n := 0 @@ -544,6 +563,7 @@ var ( _ = (*Cache[int, int]).Set _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete + _ = (*Cache[int, int]).DeleteFunc _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear _ = (*Cache[int, int]).All diff --git a/sieve/sieve_test.go b/sieve/sieve_test.go index 5015cb3..ebf345e 100644 --- a/sieve/sieve_test.go +++ b/sieve/sieve_test.go @@ -258,6 +258,8 @@ func (m *model) Delete(key int) (int, bool) { return value, true } +func (m *model) DeleteFunc(del func(int, int) bool) int { return cachetest.DeleteEach(m, del) } + func (m *model) Len() int { return len(m.entries) } func (m *model) Cap() int { return m.capacity } diff --git a/stats/stats.go b/stats/stats.go index f1bd92f..de27bc0 100644 --- a/stats/stats.go +++ b/stats/stats.go @@ -18,7 +18,7 @@ // - SetIfAbsent: the same as Set if it stores the value, nothing if the // key was there. It counts no hit or miss either way: a caller that // loads what a Get missed has had the miss counted already. -// - Peek, Delete, Clear and All: nothing. +// - Peek, Delete, DeleteFunc, Clear and All: nothing. // // The counts only go up, and Clear does not reset them. For rates, take a // [Snapshot] at intervals and subtract the one before with [Snapshot.Sub]. @@ -245,6 +245,10 @@ func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKe // Delete removes key and returns the value it had, and counts nothing. func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { return c.cache.Delete(key) } +// DeleteFunc removes the entries for which del returns true, reports how many +// it removed, and counts nothing. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { return c.cache.DeleteFunc(del) } + // Len returns the number of entries in the cache. func (c *Cache[K, V]) Len() int { return c.cache.Len() } diff --git a/tinylfu/tinylfu.go b/tinylfu/tinylfu.go index 648a154..af164cf 100644 --- a/tinylfu/tinylfu.go +++ b/tinylfu/tinylfu.go @@ -654,20 +654,43 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { s.mu.Lock() if idx := s.slab.Find(hash, key); idx != 0 { value, ok = s.slab.Nodes[idx].Value, true - s.look(idx) - if s.slab.Links[idx].Tag&1 == main { - s.mains-- - } else { - s.smalls-- - } - s.slab.Unlink(idx) - s.slab.Remove(idx) + s.remove(idx) } s.mu.Unlock() return value, ok } +func (s *shard[K, V]) remove(idx uint32) { + s.look(idx) + if s.slab.Links[idx].Tag&1 == main { + s.mains-- + } else { + s.smalls-- + } + s.slab.Unlink(idx) + s.slab.Remove(idx) +} + +// DeleteFunc removes the entries for which del returns true and reports how +// many it removed. del runs under one shard's lock at a time and must not +// call back into the cache. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + n := 0 + for i := range c.shards { + n += c.shards[i].deleteFunc(del) + } + return n +} + +func (s *shard[K, V]) deleteFunc(del func(K, V) bool) int { + s.mu.Lock() + defer s.mu.Unlock() + defer s.slab.Reclaim() + + return s.slab.DeleteFunc(main, del, s.remove) + s.slab.DeleteFunc(small, del, s.remove) +} + // Len returns the number of entries in the cache. func (c *Cache[K, V]) Len() int { n := 0 @@ -769,6 +792,7 @@ var ( _ = (*Cache[int, int]).Set _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete + _ = (*Cache[int, int]).DeleteFunc _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear _ = (*Cache[int, int]).All diff --git a/tinylfu/tinylfu_test.go b/tinylfu/tinylfu_test.go index f4c1825..882cf34 100644 --- a/tinylfu/tinylfu_test.go +++ b/tinylfu/tinylfu_test.go @@ -700,6 +700,8 @@ func (m *model) Delete(key int) (int, bool) { return e.value, true } +func (m *model) DeleteFunc(del func(int, int) bool) int { return cachetest.DeleteEach(m, del) } + func (m *model) Len() int { return len(m.small) + len(m.main) } func (m *model) Cap() int { return m.capacity } diff --git a/twoq/twoq.go b/twoq/twoq.go index ec8e0c5..1b3e547 100644 --- a/twoq/twoq.go +++ b/twoq/twoq.go @@ -404,23 +404,44 @@ func (c *Cache[K, V]) Delete(key K) (value V, ok bool) { s, hash := &c.shards[uint32(h>>32)&c.mask], uint32(h) s.mu.Lock() - if idx := s.slab.Find(hash, key); idx != 0 { - if n := &s.slab.Nodes[idx]; n.Meta != ghost { - if n.Meta == frequent { - s.frequents-- - } else { - s.recents-- - } - value, ok = n.Value, true - s.slab.Unlink(idx) - s.slab.Remove(idx) - } + if idx := s.slab.Find(hash, key); idx != 0 && s.slab.Nodes[idx].Meta != ghost { + value, ok = s.slab.Nodes[idx].Value, true + s.remove(idx) } s.mu.Unlock() return value, ok } +// remove deletes a resident entry, not a ghost. +func (s *shard[K, V]) remove(idx uint32) { + if s.slab.Nodes[idx].Meta == frequent { + s.frequents-- + } else { + s.recents-- + } + s.slab.Unlink(idx) + s.slab.Remove(idx) +} + +// DeleteFunc removes the entries for which del returns true and reports how +// many it removed. del runs under one shard's lock at a time and must not +// call back into the cache. +func (c *Cache[K, V]) DeleteFunc(del func(K, V) bool) int { + n := 0 + for i := range c.shards { + n += c.shards[i].deleteFunc(del) + } + return n +} + +func (s *shard[K, V]) deleteFunc(del func(K, V) bool) int { + s.mu.Lock() + defer s.mu.Unlock() + + return s.slab.DeleteFunc(frequent, del, s.remove) + s.slab.DeleteFunc(recent, del, s.remove) +} + // Len returns the number of entries in the cache. func (c *Cache[K, V]) Len() int { n := 0 @@ -496,6 +517,7 @@ var ( _ = (*Cache[int, int]).Set _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete + _ = (*Cache[int, int]).DeleteFunc _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear _ = (*Cache[int, int]).All diff --git a/twoq/twoq_test.go b/twoq/twoq_test.go index fd862db..7bc4fb9 100644 --- a/twoq/twoq_test.go +++ b/twoq/twoq_test.go @@ -337,6 +337,8 @@ func (m *model) Delete(key int) (int, bool) { return value, ok } +func (m *model) DeleteFunc(del func(int, int) bool) int { return cachetest.DeleteEach(m, del) } + func (m *model) Len() int { return len(m.recent) + len(m.frequent) } func (m *model) Cap() int { return m.capacity }