From 31ff1b6a5cfd0105e13a772a880e827914495392 Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Mon, 23 Nov 2026 16:41:07 +0500 Subject: [PATCH] Add SetIfAbsent to every cache and wrapper SetIfAbsent(key, value) stores value unless key has an entry, and if it has, returns that entry's value with present true. The look and the store happen under the shard lock, so of the goroutines that race on one key, one stores its value and the rest get it back. The last three results are Set's: the entry that left the cache for the new one, if any. evict.Cache gains the method, which breaks types outside the module that implement it. A key that is present counts as an access, as Get does. stats counts only evictions for SetIfAbsent, no hit or miss, since a Get usually comes first. Each shard's set splits into set and add, the insert path, and inlinecheck covers both. expire takes an expired entry for none: SetIfAbsent stores the new one in its place and hands the expired one back, as Set does. Callers that find the same expired entry take turns under one of 64 locks of the Cache and look again with Peek. A value stored just after that look, by a Set or by a SetIfAbsent that found the expired entry gone, is replaced and handed back; the documentation says so. stats counts no eviction for an expired entry of the key that is replaced, as for Set. On an Apple M3 Max with one CPU, SetIfAbsent of a present key took 12 to 15 ns, about a Get hit, and one that evicts about as long as Set. Set stayed within noise, but for lru's Set that evicts: 3.5% slower in the median of six interleaved runs, 39.3 to 40.7 ns. Through expire, a present key took about 18 ns more, in one run: it reads the time for the entry it may store, as Set does. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 + evict.go | 16 ++ expire/bench_test.go | 26 ++ expire/expire.go | 93 ++++++- expire/expire_test.go | 268 +++++++++++++++++++- internal/cachetest/cachetest.go | 111 +++++++- internal/cachetest/compare.go | 22 +- internal/cachetest/concurrent.go | 98 +++++++ internal/inlinecheck/inline_test.go | 4 +- internal/inlinecheck/probe/expire/probe.go | 1 + internal/inlinecheck/probe/lru/probe.go | 1 + internal/inlinecheck/probe/s3fifo/probe.go | 1 + internal/inlinecheck/probe/sieve/probe.go | 1 + internal/inlinecheck/probe/stats/probe.go | 1 + internal/inlinecheck/probe/tinylfu/probe.go | 1 + internal/inlinecheck/probe/twoq/probe.go | 1 + lru/bench_test.go | 33 +++ lru/lru.go | 42 ++- lru/lru_test.go | 9 + s3fifo/bench_test.go | 33 +++ s3fifo/s3fifo.go | 45 +++- s3fifo/s3fifo_test.go | 9 + sieve/bench_test.go | 33 +++ sieve/sieve.go | 42 ++- sieve/sieve_test.go | 9 + stats/stats.go | 22 +- stats/stats_test.go | 41 ++- tinylfu/bench_test.go | 33 +++ tinylfu/example_test.go | 22 ++ tinylfu/tinylfu.go | 47 +++- tinylfu/tinylfu_test.go | 9 + twoq/bench_test.go | 29 +++ twoq/twoq.go | 74 +++++- twoq/twoq_test.go | 9 + 34 files changed, 1133 insertions(+), 55 deletions(-) diff --git a/README.md b/README.md index d6d505c..2e61480 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Fixed-capacity in-memory caches for Go. - **Nothing for the GC to scan** when keys and values hold no pointers. - **Batch lookups.** `GetMany` loads up to 32 entries from memory in parallel. - **Evictions handed back.** `Set` returns the entry it replaced or evicted. +- **Insert if absent.** `SetIfAbsent` stores a value only if the key has none; of goroutines + racing on one key, one stores its value and the rest get it back. - **Statistics.** `stats.Wrap` counts hits, misses and evictions. - **Expiry.** `expire.Wrap` gives entries a time to live. - **Safe for concurrent use**, and depends only on the standard library. diff --git a/evict.go b/evict.go index 5cdf542..d05329f 100644 --- a/evict.go +++ b/evict.go @@ -75,6 +75,22 @@ type Cache[K comparable, V any] interface { // returns the one it had. Set(key K, value V) (oldKey K, oldValue V, displaced bool) + // SetIfAbsent stores value under key unless the cache holds key + // already. If it does, SetIfAbsent changes nothing but records the + // access with the eviction policy, as Get does, and returns the value + // that key has, with present true. Otherwise it stores value as Set + // does, returns it with present false, and reports the entry that left + // the cache for it, if there is one: one evicted to make room, or, in an + // expire.Cache, the expired entry of key, with oldKey == key. A cache + // with no capacity keeps nothing and hands the new entry straight back + // as evicted. + // + // Looking for key and storing value happen at once: of the goroutines + // that call SetIfAbsent for one key at the same time, one stores its + // value and the others get it back as actual, unless it has left the + // cache in between. + SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) + // Delete removes key and returns the value it had. Delete(key K) (value V, ok bool) diff --git a/expire/bench_test.go b/expire/bench_test.go index 5c30c6a..b3619b8 100644 --- a/expire/bench_test.go +++ b/expire/bench_test.go @@ -117,6 +117,32 @@ func BenchmarkSet(b *testing.B) { }) } +// BenchmarkSetIfAbsent finds the key, with tinylfu and through the wrapper, +// which reads the time for the entry it may store, as Set does. +func BenchmarkSetIfAbsent(b *testing.B) { + b.Run("direct", func(b *testing.B) { + c := tinylfu.New[int, int](benchCapacity) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(i&(benchCapacity-1), i) + i++ + } + }) + + b.Run("expire", func(b *testing.B) { + c := expire.Wrap(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour) + fill(func(k, v int) { c.Set(k, v) }) + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(i&(benchCapacity-1), i) + i++ + } + }) +} + // BenchmarkGetMany looks up keys of a cache too large for the CPU's caches, on // every CPU at once: with the GetMany of s3fifo, and with that of the wrapper, // which looks them up in batches of its own. ns/key is the time per key. diff --git a/expire/expire.go b/expire/expire.go index fdc483d..143b836 100644 --- a/expire/expire.go +++ b/expire/expire.go @@ -10,15 +10,16 @@ // # Expired entries // // An entry that has expired is not found: Get, Peek, GetMany and Delete report -// it missing, and All passes it over. 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. +// 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. // -// Set hands an expired entry back when it pushes it out or replaces it, as it -// does 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. +// 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. // // 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 @@ -66,6 +67,7 @@ package expire import ( + "hash/maphash" "iter" "math" "sync" @@ -89,6 +91,10 @@ const ( // cacheLine is a size that no two CPUs' cache lines straddle on the // platforms Go runs on. cacheLine = 128 + + // stripes is how many locks the keys share for replacing expired + // entries in SetIfAbsent. + stripes = 64 ) // Entry is a value as the wrapped cache holds it, together with the time at @@ -114,6 +120,12 @@ type Cache[K comparable, V any] struct { // batches holds arrays that GetMany looks up entries in. Its own // would move to the heap, since the cache is behind an interface. batches sync.Pool + + // locks have the SetIfAbsent calls that find an expired entry of the + // same key take turns, and seed picks one for a key. They are apart + // from the fields that readers look at, since they are written to. + locks *[stripes]sync.Mutex + seed maphash.Seed } // manyGetter is a cache that looks up several keys at once, as sieve, s3fifo @@ -205,7 +217,9 @@ func (c *clock) deadline(ttl time.Duration) int64 { // // Using cache directly as well is fine: its entries are the ones the Cache // holds, and its methods do not look at the time. They return entries that -// have expired, which those of the Cache do not. +// have expired, which those of the Cache do not. The methods of a cache of your +// own must not call those of the Cache, though: SetIfAbsent holds a lock while +// it calls them. func Wrap[K comparable, V any](cache evict.Cache[K, Entry[V]], ttl time.Duration) *Cache[K, V] { if ttl <= 0 { panic("expire: Wrap: ttl must be positive") @@ -216,7 +230,10 @@ func Wrap[K comparable, V any](cache evict.Cache[K, Entry[V]], ttl time.Duration func wrap[K comparable, V any](cache evict.Cache[K, Entry[V]], ttl time.Duration, clock *clock) *Cache[K, V] { clock.begin() many, _ := cache.(manyGetter[K, Entry[V]]) - return &Cache[K, V]{cache: cache, many: many, clock: clock, ttl: ttl} + return &Cache[K, V]{ + cache: cache, many: many, clock: clock, ttl: ttl, + locks: new([stripes]sync.Mutex), seed: maphash.MakeSeed(), + } } // expired reports whether an entry that expires at deadline has. Neither the @@ -317,6 +334,62 @@ func (c *Cache[K, V]) SetWithTTL(key K, value V, ttl time.Duration) (oldKey K, o return oldKey, old.value, displaced } +// SetIfAbsent stores value under key, to expire after the time to live that +// the Cache was made with, unless key has an entry that has not expired. If it +// has, SetIfAbsent changes nothing but records the access with the eviction +// policy, and returns the value of the entry with present true. Otherwise it +// returns value with present false, and reports the entry that left the cache +// for it, if there is one: one of another key, evicted to make room, or the +// expired entry of key, which the new one replaces as Set would. See +// [evict.Cache]. +// +// Of the goroutines that call SetIfAbsent for one key at the same time, one +// stores its value and the others get it back, unless it leaves the cache or +// 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. +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) + if present && c.expired(a.deadline) { + return c.replace(key, e) + } + return a.value, present, oldKey, old.value, evicted +} + +// replace stores e under key for SetIfAbsent, which found an expired entry +// there, unless another goroutine has stored one that has not expired since. +// It looks again under a lock that goroutines doing the same for key share, +// with Peek, since SetIfAbsent has told the policy about the access already. +func (c *Cache[K, V]) replace(key K, e Entry[V]) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + mu := &c.locks[maphash.Comparable(c.seed, key)%stripes] + mu.Lock() + defer mu.Unlock() + + a, ok := c.cache.Peek(key) + if !ok { + // The expired entry has left, so e goes in as if there had been + // none, unless an entry has come in its place. + b, found, k, old, out := c.cache.SetIfAbsent(key, e) + if !found { + return e.value, false, k, old.value, out + } + a = b + } + if !c.expired(a.deadline) { + var none K + var zero V + return a.value, true, none, zero, false + } + // It has expired, as one that came in may have too: SetWithTTL stores + // such entries. + k, old, out := c.cache.Set(key, e) + return e.value, false, k, old.value, out +} + // Delete removes key and returns the value it had, unless that had expired. // An expired entry is removed all the same; delete it from the wrapped cache // to have its value back. diff --git a/expire/expire_test.go b/expire/expire_test.go index 99830c1..06f3e68 100644 --- a/expire/expire_test.go +++ b/expire/expire_test.go @@ -328,10 +328,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. +// or go between SetWithTTL's look and its Set, and another after each +// SetIfAbsent. type hooked struct { evict.Cache[string, expire.Entry[int]] - after func() + after, afterAbsent func() } func (h *hooked) Peek(key string) (expire.Entry[int], bool) { @@ -342,6 +343,14 @@ func (h *hooked) Peek(key string) (expire.Entry[int], bool) { return e, ok } +func (h *hooked) SetIfAbsent(key string, e expire.Entry[int]) (actual expire.Entry[int], present bool, oldKey string, oldValue expire.Entry[int], evicted bool) { + actual, present, oldKey, oldValue, evicted = h.Cache.SetIfAbsent(key, e) + if h.afterAbsent != nil { + h.afterAbsent() + } + return actual, present, oldKey, oldValue, evicted +} + // 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 @@ -381,6 +390,245 @@ func TestSetWithTTLRace(t *testing.T) { } } +// SetIfAbsent takes an expired entry for no entry, by any policy: it stores the +// new one in its place, with a time to live of its own, and hands the expired +// one back. +func TestSetIfAbsentExpired(t *testing.T) { + t.Parallel() + + type result struct { + actual int + present bool + oldKey string + oldValue int + displaced bool + } + setIfAbsent := func(c *expire.Cache[string, int], key string, value int) result { + var r result + r.actual, r.present, r.oldKey, r.oldValue, r.displaced = c.SetIfAbsent(key, value) + return r + } + + for name, newCache := range policies { + t.Run(name, func(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(newCache(), time.Second, clock) + + c.Set("a", 1) + clock.Advance(time.Second - 1) + if r, want := setIfAbsent(c, "a", 2), (result{1, true, "", 0, false}); r != want { + t.Errorf("SetIfAbsent(a, 2) before a expired = %+v, want %+v", r, want) + } + clock.Advance(1) + if r, want := setIfAbsent(c, "a", 3), (result{3, false, "a", 1, true}); r != want { + t.Errorf("SetIfAbsent(a, 3) after a expired = %+v, want %+v", r, want) + } + if !found(t, c, "a", 3) { + t.Fatal("a is not found after SetIfAbsent replaced it") + } + + clock.Advance(time.Second - 1) + if r, want := setIfAbsent(c, "a", 4), (result{3, true, "", 0, false}); r != want { + t.Errorf("SetIfAbsent(a, 4) before the new a expired = %+v, want %+v", r, want) + } + clock.Advance(1) + if found(t, c, "a", 3) { + t.Error("a is found when the second of the new entry is up") + } + + // One that SetWithTTL stored expired is no entry either. + c.SetWithTTL("a", 5, 0) + if r, want := setIfAbsent(c, "a", 6), (result{6, false, "a", 5, true}); r != want { + t.Errorf("SetIfAbsent(a, 6) over an entry set to expire at once = %+v, want %+v", r, want) + } + if n := c.Len(); n != 1 { + t.Errorf("Len() = %d, want 1", n) + } + }) + } +} + +// SetIfAbsent that finds an expired entry looks again before it replaces it. +// An entry that has not expired, stored in between, is found. If the expired +// one has left, before the second look or after, the new one is stored as if +// there had been none, with eviction if that is what it takes, and an entry +// that comes instead is found, or replaced if it has expired too. A Set just +// after the second look is replaced and handed back, as the documentation +// says. +func TestSetIfAbsentRace(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + h := &hooked{Cache: lru.New[string, expire.Entry[int]](2)} + c := expire.WrapWith(h, time.Second, clock) + + // Another SetIfAbsent replaces it first. + c.Set("a", 1) + clock.Advance(time.Second) + h.afterAbsent = func() { + h.afterAbsent = nil + if v, present, _, _, _ := c.SetIfAbsent("a", 2); v != 2 || present { + t.Errorf("the other SetIfAbsent(a, 2) = %d, %t; want 2, false", v, present) + } + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 3); v != 2 || !present || k != "" || old != 0 || evicted { + t.Errorf("SetIfAbsent(a, 3) = %d, %t, %q, %d, %t; want 2, true, \"\", 0, false", v, present, k, old, evicted) + } + + // The expired entry leaves, and another key takes its place, so the + // cache is full. + c.Set("live", 4) + clock.Advance(time.Second) + c.Set("live", 4) + h.afterAbsent = func() { + h.afterAbsent = nil + c.Delete("a") + c.Set("other", 5) + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 6); v != 6 || present || k != "live" || old != 4 || !evicted { + t.Errorf("SetIfAbsent(a, 6) as a left = %d, %t, %q, %d, %t; want 6, false, live, 4, true", v, present, k, old, evicted) + } + if !found(t, c, "a", 6) || !found(t, c, "other", 5) { + t.Fatal("a or other is gone") + } + + // The expired entry leaves, and one comes instead that expires too. + clock.Advance(time.Second) + h.afterAbsent = func() { + h.afterAbsent = nil + c.Delete("a") + h.after = func() { + h.after = nil + c.Set("a", 7) + clock.Advance(time.Second) + } + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 8); v != 8 || present || k != "a" || old != 7 || !evicted { + t.Errorf("SetIfAbsent(a, 8) as an entry came and expired = %d, %t, %q, %d, %t; want 8, false, a, 7, true", v, present, k, old, evicted) + } + + // A Set just after SetIfAbsent has looked again. + clock.Advance(time.Second) + h.after = func() { + h.after = nil + c.Set("a", 9) + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 10); v != 10 || present || k != "a" || old != 9 || !evicted { + t.Errorf("SetIfAbsent(a, 10) as a was set = %d, %t, %q, %d, %t; want 10, false, a, 9, true", v, present, k, old, evicted) + } + if !found(t, c, "a", 10) { + t.Error("a does not have the value of SetIfAbsent") + } + + // The expired entry leaves just after SetIfAbsent has looked again: + // nothing leaves for the new one while there is room, and the least + // recently used entry when there is not. + clock.Advance(time.Second) + h.after = func() { + h.after = nil + c.Delete("a") + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 11); v != 11 || present || k != "" || old != 0 || evicted { + t.Errorf("SetIfAbsent(a, 11) as a left = %d, %t, %q, %d, %t; want 11, false, \"\", 0, false", v, present, k, old, evicted) + } + clock.Advance(time.Second) + h.after = func() { + h.after = nil + c.Delete("a") + c.Set("live", 12) + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 13); v != 13 || present || k != "other" || old != 5 || !evicted { + t.Errorf("SetIfAbsent(a, 13) as a left a full cache = %d, %t, %q, %d, %t; want 13, false, other, 5, true", v, present, k, old, evicted) + } + + // The expired entry leaves, and one that has not expired comes before + // SetIfAbsent stores its own: that is found. + clock.Advance(time.Second) + h.afterAbsent = func() { + h.afterAbsent = nil + c.Delete("a") + h.after = func() { + h.after = nil + c.Set("a", 14) + } + } + if v, present, k, old, evicted := c.SetIfAbsent("a", 15); v != 14 || !present || k != "" || old != 0 || evicted { + t.Errorf("SetIfAbsent(a, 15) as a came back = %d, %t, %q, %d, %t; want 14, true, \"\", 0, false", v, present, k, old, evicted) + } + if !found(t, c, "a", 14) { + t.Error("a does not have the value that came in") + } +} + +// Of the goroutines that call SetIfAbsent for a key whose entry has expired, +// one replaces it and the others find what it stored. In each round the +// entries of several keys expire, and the goroutines go over them in the same +// order, so that they race for each. The keys are few enough for no shard to +// be full. +func TestSetIfAbsentExpiredOnce(t *testing.T) { + t.Parallel() + + rounds := 200 + if testing.Short() { + rounds = 20 + } + const goroutines, keys = 8, 16 + names := make([]string, keys) + for k := range names { + names[k] = "k" + strconv.Itoa(k) + } + for name, newCache := range policies { + t.Run(name, func(t *testing.T) { + t.Parallel() + + clock := expire.NewClock() + c := expire.WrapWith(newCache(), time.Second, clock) + for round := range rounds { + for _, key := range names { + c.Set(key, -1) + } + clock.Advance(time.Second) + + start := make(chan struct{}) + var stored [keys]atomic.Int32 + var actual [goroutines][keys]int + var wg sync.WaitGroup + for g := range goroutines { + wg.Go(func() { + <-start + for k, key := range names { + v, present, oldKey, old, evicted := c.SetIfAbsent(key, g) + if !present { + stored[k].Add(1) + if v != g || oldKey != key || old != -1 || !evicted { + t.Errorf("round %d: SetIfAbsent(%s, %d) stored it but returned %d, %q, %d, %t; want %d, %s, -1, true", round, key, g, v, oldKey, old, evicted, g, key) + } + } + actual[g][k] = v + } + }) + } + close(start) + wg.Wait() + + for k, key := range names { + if n := stored[k].Load(); n != 1 { + t.Fatalf("round %d: %d goroutines stored their value under %s, want 1", round, n, key) + } + want, _ := c.Get(key) + for g := range actual { + if actual[g][k] != want { + t.Fatalf("round %d: goroutine %d got %d for %s, but it has %d", round, g, actual[g][k], key, want) + } + } + } + } + }) + } +} + // Readers look at a copy of the time that may lag behind. An entry that is due // to expire within 50 ms of it is checked against the time itself, so a lag of // up to 50 ms changes nothing. With more than that, an entry is found for up to @@ -590,7 +838,11 @@ func TestConcurrent(t *testing.T) { key := strconv.Itoa(k) switch rng.IntN(4) { case 0: - c.SetWithTTL(key, k, time.Duration(rng.IntN(20))*time.Millisecond) + if rng.IntN(2) == 0 { + c.SetWithTTL(key, k, time.Duration(rng.IntN(20))*time.Millisecond) + } else if v, _, _, _, _ := c.SetIfAbsent(key, k); v != k { + t.Errorf("SetIfAbsent(%q) = %d", key, v) + } case 1: if v, ok := c.Delete(key); ok && v != k { t.Errorf("Delete(%q) = %d", key, v) @@ -648,6 +900,16 @@ func TestStats(t *testing.T) { if s := c.Stats(); s.Hits != 6 || s.Misses != 4 { t.Errorf("%d hits and %d misses, want 6 and 4", s.Hits, s.Misses) } + + // An expired entry that SetIfAbsent replaces is handed back, but was + // not evicted, as one that Set replaces was not. + if _, present, k, old, displaced := c.SetIfAbsent(5, 100); present || k != 5 || old != 5 || !displaced { + t.Errorf("SetIfAbsent(5, 100) over an expired 5 = %t, %d, %d, %t; want false, 5, 5, true", present, k, old, displaced) + } + c.Set(6, 101) + if s := c.Stats(); s.Evictions != 0 || s.Hits != 6 || s.Misses != 4 { + t.Errorf("%d evictions, %d hits and %d misses, want 0, 6 and 4", s.Evictions, s.Hits, s.Misses) + } } // Readers look at the copy of the time on every read. It has to have a cache diff --git a/internal/cachetest/cachetest.go b/internal/cachetest/cachetest.go index 8f8c891..014bacf 100644 --- a/internal/cachetest/cachetest.go +++ b/internal/cachetest/cachetest.go @@ -86,6 +86,8 @@ func Run(t *testing.T, f Factories) { t.Run("Empty", func(t *testing.T) { t.Parallel(); testEmpty(t, f.Int) }) t.Run("SetGet", func(t *testing.T) { t.Parallel(); testSetGet(t, f.Int) }) + t.Run("SetIfAbsent", func(t *testing.T) { t.Parallel(); testSetIfAbsent(t, f.Int) }) + t.Run("SetIfAbsentOnce", func(t *testing.T) { t.Parallel(); SetIfAbsentOnce(t, f.Int) }) t.Run("ZeroCapacity", func(t *testing.T) { t.Parallel(); testZeroCapacity(t, f.Int) }) 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) }) @@ -201,6 +203,56 @@ func testSetGet(t *testing.T, newCache Factory[int, int]) { } } +func testSetIfAbsent(t *testing.T, newCache Factory[int, int]) { + t.Helper() + + c := newCache(2, 1) + + // A key that is not there gets the value, which is a zero here: it is + // present that tells whether the key was there, not the value. + if a, present, k, v, evicted := c.SetIfAbsent(1, 0); present || a != 0 || evicted || k != 0 || v != 0 { + t.Errorf("SetIfAbsent(1, 0) = %d, %t, %d, %d, %t, want 0 stored and nothing evicted", a, present, k, v, evicted) + } + if a, present, k, v, evicted := c.SetIfAbsent(1, 10); !present || a != 0 || evicted || k != 0 || v != 0 { + t.Errorf("SetIfAbsent(1, 10) = %d, %t, %d, %d, %t, want the value 0 that 1 has", a, present, k, v, evicted) + } + if v, ok := c.Peek(1); !ok || v != 0 { + t.Errorf("Peek(1) = %d, %t after SetIfAbsent found it, want 0", v, ok) + } + + // What Set stores, SetIfAbsent finds. + c.Set(1, 11) + if a, present, _, _, _ := c.SetIfAbsent(1, 12); !present || a != 11 { + t.Errorf("SetIfAbsent(1, 12) = %d, %t after Set(1, 11), want 11, true", a, present) + } + + // A deleted key is absent again. + c.Delete(1) + if a, present, _, _, evicted := c.SetIfAbsent(1, 13); present || a != 13 || evicted { + t.Errorf("SetIfAbsent(1, 13) = %d, %t, evicted %t after Delete, want 13 stored", a, present, evicted) + } + if got := c.Len(); got != 1 { + t.Errorf("Len() = %d, want 1", got) + } + + // A full cache makes room as Set does, and says for whom. + c.SetIfAbsent(2, 20) + a, present, k, v, evicted := c.SetIfAbsent(3, 30) + held := k == 1 && v == 13 || k == 2 && v == 20 + if present || a != 30 || !evicted || !held { + t.Errorf("SetIfAbsent(3, 30) = %d, %t, %d, %d, %t, want 30 stored and 1=13 or 2=20 evicted", a, present, k, v, evicted) + } + if got := c.Len(); got != 2 { + t.Errorf("Len() = %d, want 2", got) + } + if _, ok := c.Peek(k); ok { + t.Errorf("Peek(%d) found the key that SetIfAbsent evicted", k) + } + if v, ok := c.Peek(3); !ok || v != 30 { + t.Errorf("Peek(3) = %d, %t, want 30", v, ok) + } +} + func testZeroCapacity(t *testing.T, newCache Factory[int, int]) { t.Helper() @@ -214,6 +266,9 @@ func testZeroCapacity(t *testing.T, newCache Factory[int, int]) { if k, v, displaced := c.Set(1, 2); !displaced || k != 1 || v != 2 { t.Errorf("capacity %d: Set(1, 2) = %d, %d, %t, want the entry handed back", capacity, k, v, displaced) } + if a, present, k, v, evicted := c.SetIfAbsent(1, 2); present || a != 2 || !evicted || k != 1 || v != 2 { + t.Errorf("capacity %d: SetIfAbsent(1, 2) = %d, %t, %d, %d, %t, want the entry handed back", capacity, a, present, k, v, evicted) + } if _, ok := c.Get(1); ok { t.Errorf("capacity %d: Get found a key", capacity) } @@ -466,6 +521,35 @@ func testModel(t *testing.T, newCache Factory[int, int]) { t.Fatalf("step %d: Peek(%d) = %d, %t, want %d, %t", step, key, v, ok, want, present) } + case op < 60: + actual, found, oldKey, oldValue, evicted := c.SetIfAbsent(key, step) + if present { + if !found || actual != want || evicted { + t.Fatalf("step %d: SetIfAbsent(%d) = %d, %t, %d, %d, %t, want the value %d that is there", + step, key, actual, found, oldKey, oldValue, evicted, want) + } + break + } + if found || actual != step { + t.Fatalf("step %d: SetIfAbsent(%d) = %d, %t for a key that is not there", step, key, actual, found) + } + if evicted { + if tt.shards == 1 && len(model) < tt.capacity { + t.Fatalf("step %d: SetIfAbsent(%d) evicted %d=%d from a cache that holds %d entries of %d", + step, key, oldKey, oldValue, len(model), tt.capacity) + } + gone, ok := model[oldKey] + if !ok || gone != oldValue || oldKey == key { + t.Fatalf("step %d: SetIfAbsent(%d) evicted %d=%d, which the cache did not hold (%d, %t)", + step, key, oldKey, oldValue, gone, ok) + } + delete(model, oldKey) + } + model[key] = step + if len(model) > tt.capacity { + t.Fatalf("step %d: SetIfAbsent(%d) took the cache past its capacity", step, key) + } + case op < 90: oldKey, oldValue, displaced := c.Set(key, step) switch { @@ -575,10 +659,16 @@ func testConcurrent(t *testing.T, newCache Factory[int, int]) { if v, ok := c.Peek(key); ok { check("Peek", key, v) } - case op < 900: + case op < 800: if k, v, displaced := c.Set(key, valueOf(key)); displaced { check("Set", k, v) } + case op < 900: + actual, _, k, v, evicted := c.SetIfAbsent(key, valueOf(key)) + check("SetIfAbsent", key, actual) + if evicted { + check("SetIfAbsent", k, v) + } case op < 990: if v, ok := c.Delete(key); ok { check("Delete", key, v) @@ -643,6 +733,16 @@ func testKeyIdentity(t *testing.T, newCache Factory[float64, int]) { t.Errorf("%d shards: Len() = %d, want 1", shards, got) } + // SetIfAbsent finds an equal key, and changes nothing about it. + if a, present, _, _, _ := c.SetIfAbsent(zero, 9); !present || a != 2 { + t.Errorf("%d shards: SetIfAbsent(+0) = %d, %t, want 2, true", shards, a, present) + } + for k := range c.All() { + if !math.Signbit(k) { + t.Errorf("%d shards: SetIfAbsent(+0) replaced the key -0", shards) + } + } + // A key that is not equal to itself is one that nobody can ask for. // Its entries take up room like any other until they are evicted. nan := math.NaN() @@ -665,6 +765,9 @@ func testKeyIdentity(t *testing.T, newCache Factory[float64, int]) { if nans != 2 || c.Len() != 3 { t.Errorf("%d shards: the cache holds %d entries, %d of them under NaN, want 3 and 2", shards, c.Len(), nans) } + if a, present, _, _, _ := c.SetIfAbsent(nan, 5); present || a != 5 { + t.Errorf("%d shards: SetIfAbsent(NaN) = %d, %t, want 5 stored", shards, a, present) + } for i := range 1000 { c.Set(float64(i), i) c.Set(nan, i) @@ -773,8 +876,11 @@ func NoAllocs(t *testing.T, f Factories) { c.Get(-key) // Misses. c.Peek(key) // Finds it again. if key%8 == 0 { - c.Delete(key - 1) // Deletes the one before. + c.Delete(key - 1) // Deletes the one before. + c.SetIfAbsent(key-1, key) // Stores it again. } + c.SetIfAbsent(key, key) // Finds it once more. + c.SetIfAbsent(-key, -key) // Stores an entry and evicts one. c.Len() } if c.Len() < capacity/2 { @@ -799,6 +905,7 @@ func NoAllocs(t *testing.T, f Factories) { c.Get(key) c.Get("missing") c.Peek(key) + c.SetIfAbsent(keys[(i+7)%len(keys)], key) if i%3 == 0 { c.Delete(key) } diff --git a/internal/cachetest/compare.go b/internal/cachetest/compare.go index d60f5b2..afedf4c 100644 --- a/internal/cachetest/compare.go +++ b/internal/cachetest/compare.go @@ -17,6 +17,7 @@ const ( Get Kind = iota Peek Set + SetIfAbsent Delete Clear ) @@ -28,18 +29,20 @@ type Op struct { } // RandomOps returns n operations on keys in [0, keys): mostly reads and -// writes, some deletions, and a rare Clear. +// writes, some of them with SetIfAbsent, some deletions, and a rare Clear. func RandomOps(rng *rand.Rand, keys, n int) iter.Seq[Op] { return func(yield func(Op) bool) { for i := range n { op := Op{Key: rng.IntN(keys), Value: i} switch p := rng.IntN(1000); { - case p < 400: + case p < 350: op.Kind = Get - case p < 500: + case p < 450: op.Kind = Peek - case p < 900: + case p < 800: op.Kind = Set + case p < 900: + op.Kind = SetIfAbsent case p < 999: op.Kind = Delete default: @@ -59,8 +62,10 @@ func BytesOps(data []byte) iter.Seq[Op] { for i, b := range data { op := Op{Key: int(b & 31), Value: i} switch b >> 5 { - case 0, 1, 2: + case 0, 1: op.Kind = Get + case 2: + op.Kind = SetIfAbsent case 3: op.Kind = Peek case 4, 5: @@ -120,6 +125,13 @@ func Compare(t *testing.T, got, want evict.Cache[int, int], ops iter.Seq[Op]) { t.Fatalf("step %d: Set(%d, %d) = %d, %d, %t, want %d, %d, %t", step, op.Key, op.Value, gk, gv, gok, wk, wv, wok) } + case SetIfAbsent: + ga, gp, gk, gv, gok := got.SetIfAbsent(op.Key, op.Value) + wa, wp, wk, wv, wok := want.SetIfAbsent(op.Key, op.Value) + if ga != wa || gp != wp || gk != wk || gv != wv || gok != wok { + t.Fatalf("step %d: SetIfAbsent(%d, %d) = %d, %t, %d, %d, %t, want %d, %t, %d, %d, %t", + step, op.Key, op.Value, ga, gp, gk, gv, gok, wa, wp, wk, wv, wok) + } case Delete: gv, gok := got.Delete(op.Key) wv, wok := want.Delete(op.Key) diff --git a/internal/cachetest/concurrent.go b/internal/cachetest/concurrent.go index 7d3f29a..4b9cdef 100644 --- a/internal/cachetest/concurrent.go +++ b/internal/cachetest/concurrent.go @@ -280,6 +280,104 @@ func Present(t *testing.T, newCache Factory[int, int]) { } } +// SetIfAbsentOnce checks that of the goroutines that call SetIfAbsent for one +// key at the same time, exactly one stores its value, and that the others and +// any reader get that one. +// +// Every shard has room for every key, so nothing that is stored leaves the +// cache. The writers go through the keys in the same order, so that they get +// to each key at about the same time, while readers look the keys up. +func SetIfAbsentOnce(t *testing.T, newCache Factory[int, int]) { + t.Helper() + + const ( + writers = 6 + readers = 2 + ) + rounds := 100 + if testing.Short() { + rounds = 10 + } + + for _, tt := range []struct{ keys, shards int }{{1, 1}, {7, 1}, {500, 1}, {500, 8}} { + t.Run(fmt.Sprintf("keys=%d/shards=%d", tt.keys, tt.shards), func(t *testing.T) { + t.Parallel() + + c := newCache(tt.keys*tt.shards, tt.shards) + for round := range rounds { + c.Clear() + + var ( + wg sync.WaitGroup + start = make(chan struct{}) + won = make([]atomic.Int32, tt.keys) + got = make([][]int, writers) // What SetIfAbsent returned to each writer. + seen = make([][]int, readers) // What Get returned to each reader, or -1. + ) + for w := range writers { + got[w] = make([]int, tt.keys) + wg.Go(func() { + <-start + for key := range tt.keys { + value := round*writers + w + actual, present, oldKey, _, evicted := c.SetIfAbsent(key, value) + if evicted { + t.Errorf("SetIfAbsent(%d) evicted %d from a cache with room for it", key, oldKey) + return + } + if !present { + if actual != value { + t.Errorf("SetIfAbsent(%d, %d) stored %d", key, value, actual) + return + } + won[key].Add(1) + } + got[w][key] = actual + } + }) + } + for r := range readers { + seen[r] = make([]int, tt.keys) + wg.Go(func() { + <-start + for key := range tt.keys { + seen[r][key] = -1 + if v, ok := c.Get(key); ok { + seen[r][key] = v + } + } + }) + } + close(start) + wg.Wait() + if t.Failed() { + return + } + + for key := range tt.keys { + if n := won[key].Load(); n != 1 { + t.Fatalf("round %d: %d goroutines stored a value for key %d, want 1", round, n, key) + } + want, ok := c.Peek(key) + if !ok { + t.Fatalf("round %d: key %d is missing", round, key) + } + for w := range writers { + if got[w][key] != want { + t.Fatalf("round %d: SetIfAbsent(%d) gave writer %d the value %d, want %d", round, key, w, got[w][key], want) + } + } + for r := range readers { + if v := seen[r][key]; v >= 0 && v != want { + t.Fatalf("round %d: Get(%d) gave reader %d the value %d, want %d", round, key, r, v, want) + } + } + } + } + }) + } +} + // ClearAtOnce checks that a shard is cleared in one go as far as anyone can // tell: once a reader has found a key gone, no reader finds another key that // was to go with it. diff --git a/internal/inlinecheck/inline_test.go b/internal/inlinecheck/inline_test.go index 3a2dc56..52a8d94 100644 --- a/internal/inlinecheck/inline_test.go +++ b/internal/inlinecheck/inline_test.go @@ -25,7 +25,7 @@ import ( ) // hot matches the functions that every operation on a cache goes through. -var hot = regexp.MustCompile(`/(lru|twoq|sieve|s3fifo|tinylfu|stats|expire)\.\(\*(Cache|shard)\[.*\]\)\.(Get|GetMany|Peek|Set|SetWithTTL|set|evict|Delete|look|victim|promote|asked)$|` + +var hot = regexp.MustCompile(`/(lru|twoq|sieve|s3fifo|tinylfu|stats|expire)\.\(\*(Cache|shard)\[.*\]\)\.(Get|GetMany|Peek|Set|SetWithTTL|set|SetIfAbsent|add|evict|Delete|look|victim|promote|asked)$|` + `/c?slab\.\(\*Slab\[.*\]\)\.(Find|Lookup|Insert|Replace|Remove)$`) // slow matches the calls that must not show up in them: functions that are @@ -135,7 +135,7 @@ func TestHotPathsAreInlined(t *testing.T) { // The test is only worth something if it has looked at the right code. for _, pkg := range []string{"lru", "twoq", "sieve", "s3fifo", "tinylfu", "stats", "expire"} { - for _, method := range []string{"Get", "Set", "Peek", "Delete"} { + for _, method := range []string{"Get", "Set", "SetIfAbsent", "Peek", "Delete"} { found := false for name := range seen { found = found || strings.Contains(name, "/"+pkg+".(*Cache[") && strings.HasSuffix(name, ")."+method) diff --git a/internal/inlinecheck/probe/expire/probe.go b/internal/inlinecheck/probe/expire/probe.go index 95e812f..5046aeb 100644 --- a/internal/inlinecheck/probe/expire/probe.go +++ b/internal/inlinecheck/probe/expire/probe.go @@ -20,6 +20,7 @@ type Value struct{ Size, Hits int } func Use(c *expire.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) c.SetWithTTL(k, v, time.Second) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) var values [2]Value diff --git a/internal/inlinecheck/probe/lru/probe.go b/internal/inlinecheck/probe/lru/probe.go index 864a938..bb36454 100644 --- a/internal/inlinecheck/probe/lru/probe.go +++ b/internal/inlinecheck/probe/lru/probe.go @@ -15,6 +15,7 @@ type Value struct{ Size, Hits int } // Use keeps the compiler from discarding the methods of the cache. func Use(c *lru.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) return c.Get(k) diff --git a/internal/inlinecheck/probe/s3fifo/probe.go b/internal/inlinecheck/probe/s3fifo/probe.go index b5e0016..25179a3 100644 --- a/internal/inlinecheck/probe/s3fifo/probe.go +++ b/internal/inlinecheck/probe/s3fifo/probe.go @@ -15,6 +15,7 @@ type Value struct{ Size, Hits int } // Use keeps the compiler from discarding the methods of the cache. func Use(c *s3fifo.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) var values [2]Value diff --git a/internal/inlinecheck/probe/sieve/probe.go b/internal/inlinecheck/probe/sieve/probe.go index 5383786..326d6b4 100644 --- a/internal/inlinecheck/probe/sieve/probe.go +++ b/internal/inlinecheck/probe/sieve/probe.go @@ -15,6 +15,7 @@ type Value struct{ Size, Hits int } // Use keeps the compiler from discarding the methods of the cache. func Use(c *sieve.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) var values [2]Value diff --git a/internal/inlinecheck/probe/stats/probe.go b/internal/inlinecheck/probe/stats/probe.go index bcee219..fba3b28 100644 --- a/internal/inlinecheck/probe/stats/probe.go +++ b/internal/inlinecheck/probe/stats/probe.go @@ -15,6 +15,7 @@ type Value struct{ Size, Hits int } // Use keeps the compiler from discarding the methods of the cache. func Use(c *stats.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) var values [2]Value diff --git a/internal/inlinecheck/probe/tinylfu/probe.go b/internal/inlinecheck/probe/tinylfu/probe.go index ae3a9cb..5c1749f 100644 --- a/internal/inlinecheck/probe/tinylfu/probe.go +++ b/internal/inlinecheck/probe/tinylfu/probe.go @@ -15,6 +15,7 @@ type Value struct{ Size, Hits int } // Use keeps the compiler from discarding the methods of the cache. func Use(c *tinylfu.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) var values [2]Value diff --git a/internal/inlinecheck/probe/twoq/probe.go b/internal/inlinecheck/probe/twoq/probe.go index 4254552..041dba0 100644 --- a/internal/inlinecheck/probe/twoq/probe.go +++ b/internal/inlinecheck/probe/twoq/probe.go @@ -15,6 +15,7 @@ type Value struct{ Size, Hits int } // Use keeps the compiler from discarding the methods of the cache. func Use(c *twoq.Cache[Key, Value], k Key, v Value) (Value, bool) { c.Set(k, v) + c.SetIfAbsent(k, v) c.Peek(k) c.Delete(k) return c.Get(k) diff --git a/lru/bench_test.go b/lru/bench_test.go index 1cb0a42..c7802a1 100644 --- a/lru/bench_test.go +++ b/lru/bench_test.go @@ -109,6 +109,39 @@ func BenchmarkSet(b *testing.B) { }) } +// BenchmarkSetIfAbsent is BenchmarkSet with SetIfAbsent: for keys that the +// cache holds, which it reads, and for new ones, which it stores. +func BenchmarkSetIfAbsent(b *testing.B) { + b.Run("present", func(b *testing.B) { + c := lru.New[int, int](benchCapacity, lru.WithShards(1)) + for key := range benchCapacity { + c.Set(key, key) + } + keys := benchKeys() + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(keys[i&(len(keys)-1)], i) + i++ + } + }) + + b.Run("evict", func(b *testing.B) { + c := lru.New[int, int](benchCapacity, lru.WithShards(1)) + for key := range benchCapacity { + c.Set(-key-1, key) + } + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(i, i) // Always a new key, so always an eviction. + i++ + } + }) +} + // BenchmarkParallel has every CPU working on the same cache: three reads for // every write, on keys of which a few are much more popular than the rest and // a quarter does not fit. diff --git a/lru/lru.go b/lru/lru.go index 0762897..c7aaae9 100644 --- a/lru/lru.go +++ b/lru/lru.go @@ -169,6 +169,43 @@ func (s *shard[K, V]) set(hash uint32, key K, value V) (oldKey K, oldValue V, di sl.MoveToFront(queue, idx) return oldKey, oldValue, displaced } + return s.add(hash, key, value) +} + +// SetIfAbsent stores value under key unless the cache holds key already. If +// it does, SetIfAbsent changes nothing but marks the entry as the most +// recently used, as Get does, and returns the value that key has, with +// present true. Otherwise it stores value as Set does, returns it with +// present false, and reports the least recently used entry of the key's +// shard if it was evicted to make room. A cache without capacity hands the +// new entry straight back as evicted. +// +// Looking for key and storing value happen at once, under the lock of the +// key's shard: of the goroutines that call SetIfAbsent for one key at the +// same time, one stores its value and the others get it back as actual, +// unless it has left the cache in between. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + h := maphash.Comparable(c.seed, key) + s, hash := &c.shards[uint32(h>>32)&c.mask], uint32(h) + + s.mu.Lock() + if idx := s.slab.Find(hash, key); idx != 0 { + s.slab.MoveToFront(queue, idx) + actual = s.slab.Nodes[idx].Value + s.mu.Unlock() + return actual, true, oldKey, oldValue, false + } + oldKey, oldValue, evicted = s.add(hash, key, value) + s.mu.Unlock() + + return value, false, oldKey, oldValue, evicted +} + +// add stores an entry for a key that the shard does not hold, and returns the +// entry that it evicted to make room, if any, or the new entry itself if the +// shard has no capacity. +func (s *shard[K, V]) add(hash uint32, key K, value V) (oldKey K, oldValue V, evicted bool) { + sl := &s.slab if sl.Len() == sl.Cap() { if sl.Cap() == 0 { @@ -176,13 +213,13 @@ func (s *shard[K, V]) set(hash uint32, key K, value V) (oldKey K, oldValue V, di } lru := sl.Nodes[queue].Prev n := &sl.Nodes[lru] - oldKey, oldValue, displaced = n.Key, n.Value, true + oldKey, oldValue, evicted = n.Key, n.Value, true sl.Unlink(lru) sl.Remove(lru) } sl.PushFront(queue, sl.Insert(hash, key, value)) - return oldKey, oldValue, displaced + return oldKey, oldValue, evicted } // Delete removes key and returns the value it had. @@ -273,6 +310,7 @@ var ( _ = (*Cache[int, int]).Get _ = (*Cache[int, int]).Peek _ = (*Cache[int, int]).Set + _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear diff --git a/lru/lru_test.go b/lru/lru_test.go index dc82a10..5eda30d 100644 --- a/lru/lru_test.go +++ b/lru/lru_test.go @@ -159,6 +159,15 @@ func (m *model) Set(key, value int) (oldKey, oldValue int, displaced bool) { return evicted.key, evicted.value, full } +// SetIfAbsent is Get for a key that is there and Set for one that is not. +func (m *model) SetIfAbsent(key, value int) (actual int, present bool, oldKey, oldValue int, evicted bool) { + if actual, ok := m.Get(key); ok { + return actual, true, 0, 0, false + } + oldKey, oldValue, evicted = m.Set(key, value) + return value, false, oldKey, oldValue, evicted +} + func (m *model) Delete(key int) (int, bool) { i := m.find(key) if i < 0 { diff --git a/s3fifo/bench_test.go b/s3fifo/bench_test.go index 2275917..152826b 100644 --- a/s3fifo/bench_test.go +++ b/s3fifo/bench_test.go @@ -109,6 +109,39 @@ func BenchmarkSet(b *testing.B) { }) } +// BenchmarkSetIfAbsent is BenchmarkSet with SetIfAbsent: for keys that the +// cache holds, which it reads, and for new ones, which it stores. +func BenchmarkSetIfAbsent(b *testing.B) { + b.Run("present", func(b *testing.B) { + c := s3fifo.New[int, int](benchCapacity, s3fifo.WithShards(1)) + for key := range benchCapacity { + c.Set(key, key) + } + keys := benchKeys() + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(keys[i&(len(keys)-1)], i) + i++ + } + }) + + b.Run("evict", func(b *testing.B) { + c := s3fifo.New[int, int](benchCapacity, s3fifo.WithShards(1)) + for key := range benchCapacity { + c.Set(-key-1, key) + } + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(i, i) // Always a new key, so always an eviction. + i++ + } + }) +} + // BenchmarkParallel has every CPU working on the same cache: three reads for // every write, on keys of which a few are much more popular than the rest and // a quarter does not fit. diff --git a/s3fifo/s3fifo.go b/s3fifo/s3fifo.go index 6dbee86..efcd756 100644 --- a/s3fifo/s3fifo.go +++ b/s3fifo/s3fifo.go @@ -159,7 +159,7 @@ type shard[K comparable, V any] struct { // evicted says that the shard has been full since it was made or last // cleared. Until then, new entries are not all sent through the small - // queue; see set. + // queue; see add. evicted bool } @@ -527,6 +527,44 @@ func (s *shard[K, V]) set(h uint64, key K, value V) (oldKey K, oldValue V, displ n.SetMeta(min(n.Meta()+1, maxFrequency)) return oldKey, oldValue, true } + return s.add(h, key, value) +} + +// SetIfAbsent stores value under key unless the cache holds key already. If +// it does, SetIfAbsent changes nothing but counts a read, as Get does, and +// returns the value that key has, with present true. Otherwise it stores value +// as Set does, returns it with present false, and reports the entry that the +// key's shard evicted to make room, if any. A cache without capacity hands the +// new entry straight back as evicted. +// +// Looking for key and storing value happen at once, under the lock of the +// key's shard: of the goroutines that call SetIfAbsent for one key at the +// same time, one stores its value and the others get it back as actual, +// unless it has left the cache in between. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + h := maphash.Comparable(c.seed, key) + s := &c.shards[uint32(h>>32)&c.mask] + + s.mu.Lock() + if idx := s.slab.Find(uint32(h), key); idx != 0 { + n := &s.slab.Nodes[idx] + n.SetMeta(min(n.Meta()+1, maxFrequency)) + actual = n.Value + s.mu.Unlock() + return actual, true, oldKey, oldValue, false + } + oldKey, oldValue, evicted = s.add(h, key, value) + s.mu.Unlock() + + return value, false, oldKey, oldValue, evicted +} + +// add stores an entry for a key that the shard does not hold, and returns the +// entry that it evicted to make room, if any, or the new entry itself if the +// shard has no capacity. +func (s *shard[K, V]) add(h uint64, key K, value V) (oldKey K, oldValue V, evicted bool) { + sl := &s.slab + hash := uint32(h) if s.capacity == 0 { return key, value, true @@ -537,7 +575,7 @@ func (s *shard[K, V]) set(h uint64, key K, value V) (oldKey K, oldValue V, displ remembered := s.ghosts.Recall(ghostOf(hash, tagOf(h, small)), s.returns) if s.smalls+s.mains == s.capacity { oldKey, oldValue = s.evict() - displaced = true + evicted = true } // A shard that has yet to fill up for the first time has nothing to @@ -557,7 +595,7 @@ func (s *shard[K, V]) set(h uint64, key K, value V) (oldKey K, oldValue V, displ sl.PushFront(small, idx) s.smalls++ } - return oldKey, oldValue, displaced + return oldKey, oldValue, evicted } // evict takes one entry out of the shard, which must not be empty, and @@ -736,6 +774,7 @@ var ( _ = (*Cache[int, int]).Peek _ = (*Cache[int, int]).GetMany _ = (*Cache[int, int]).Set + _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear diff --git a/s3fifo/s3fifo_test.go b/s3fifo/s3fifo_test.go index 6146a02..7741a06 100644 --- a/s3fifo/s3fifo_test.go +++ b/s3fifo/s3fifo_test.go @@ -650,6 +650,15 @@ func (m *model) evict() (key, value int) { } } +// SetIfAbsent is Get for a key that is there and Set for one that is not. +func (m *model) SetIfAbsent(key, value int) (actual int, present bool, oldKey, oldValue int, evicted bool) { + if actual, ok := m.Get(key); ok { + return actual, true, 0, 0, false + } + oldKey, oldValue, evicted = m.Set(key, value) + return value, false, oldKey, oldValue, evicted +} + func (m *model) Delete(key int) (int, bool) { // A key that is remembered is forgotten, with its entry or without. m.forget(key) diff --git a/sieve/bench_test.go b/sieve/bench_test.go index 699e28a..a4851f9 100644 --- a/sieve/bench_test.go +++ b/sieve/bench_test.go @@ -109,6 +109,39 @@ func BenchmarkSet(b *testing.B) { }) } +// BenchmarkSetIfAbsent is BenchmarkSet with SetIfAbsent: for keys that the +// cache holds, which it reads, and for new ones, which it stores. +func BenchmarkSetIfAbsent(b *testing.B) { + b.Run("present", func(b *testing.B) { + c := sieve.New[int, int](benchCapacity, sieve.WithShards(1)) + for key := range benchCapacity { + c.Set(key, key) + } + keys := benchKeys() + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(keys[i&(len(keys)-1)], i) + i++ + } + }) + + b.Run("evict", func(b *testing.B) { + c := sieve.New[int, int](benchCapacity, sieve.WithShards(1)) + for key := range benchCapacity { + c.Set(-key-1, key) + } + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(i, i) // Always a new key, so always an eviction. + i++ + } + }) +} + // BenchmarkParallel has every CPU working on the same cache: three reads for // every write, on keys of which a few are much more popular than the rest and // a quarter does not fit. diff --git a/sieve/sieve.go b/sieve/sieve.go index 784d80a..ed26ee8 100644 --- a/sieve/sieve.go +++ b/sieve/sieve.go @@ -355,6 +355,43 @@ func (s *shard[K, V]) set(hash uint32, key K, value V) (oldKey K, oldValue V, di } return oldKey, oldValue, true } + return s.add(hash, key, value) +} + +// SetIfAbsent stores value under key unless the cache holds key already. If +// it does, SetIfAbsent changes nothing but marks the entry as used, as Get +// does, and returns the value that key has, with present true. Otherwise it +// stores value as Set does, returns it with present false, and reports the +// entry that the key's shard evicted to make room, if any. A cache without +// capacity hands the new entry straight back as evicted. +// +// Looking for key and storing value happen at once, under the lock of the +// key's shard: of the goroutines that call SetIfAbsent for one key at the +// same time, one stores its value and the others get it back as actual, +// unless it has left the cache in between. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + h := maphash.Comparable(c.seed, key) + s, hash := &c.shards[uint32(h>>32)&c.mask], uint32(h) + + s.mu.Lock() + if idx := s.slab.Find(hash, key); idx != 0 { + n := &s.slab.Nodes[idx] + n.SetMeta(visited) + actual = n.Value + s.mu.Unlock() + return actual, true, oldKey, oldValue, false + } + oldKey, oldValue, evicted = s.add(hash, key, value) + s.mu.Unlock() + + return value, false, oldKey, oldValue, evicted +} + +// add stores an entry for a key that the shard does not hold, and returns the +// entry that it evicted to make room, if any, or the new entry itself if the +// shard has no capacity. +func (s *shard[K, V]) add(hash uint32, key K, value V) (oldKey K, oldValue V, evicted bool) { + sl := &s.slab if sl.Len() == sl.Cap() { if sl.Cap() == 0 { @@ -362,12 +399,12 @@ func (s *shard[K, V]) set(hash uint32, key K, value V) (oldKey K, oldValue V, di } victim := s.victim() n := &sl.Nodes[victim] - oldKey, oldValue, displaced = n.Key, n.Value, true + oldKey, oldValue, evicted = n.Key, n.Value, true s.remove(victim) } sl.PushFront(queue, sl.Insert(hash, key, value)) - return oldKey, oldValue, displaced + return oldKey, oldValue, evicted } // victim moves the hand to the first entry that has not been used since the @@ -505,6 +542,7 @@ var ( _ = (*Cache[int, int]).Peek _ = (*Cache[int, int]).GetMany _ = (*Cache[int, int]).Set + _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear diff --git a/sieve/sieve_test.go b/sieve/sieve_test.go index 846c85a..5015cb3 100644 --- a/sieve/sieve_test.go +++ b/sieve/sieve_test.go @@ -239,6 +239,15 @@ func (m *model) Set(key, value int) (oldKey, oldValue int, displaced bool) { return oldKey, oldValue, displaced } +// SetIfAbsent is Get for a key that is there and Set for one that is not. +func (m *model) SetIfAbsent(key, value int) (actual int, present bool, oldKey, oldValue int, evicted bool) { + if actual, ok := m.Get(key); ok { + return actual, true, 0, 0, false + } + oldKey, oldValue, evicted = m.Set(key, value) + return value, false, oldKey, oldValue, evicted +} + func (m *model) Delete(key int) (int, bool) { i := m.find(key) if i < 0 { diff --git a/stats/stats.go b/stats/stats.go index bd6fdc2..22be33f 100644 --- a/stats/stats.go +++ b/stats/stats.go @@ -15,6 +15,9 @@ // - Set: an eviction if it pushed out the entry of another key to make // room, or if the cache has no capacity and handed the new entry back. // Replacing the entry of a key is not an eviction. +// - 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. // // The counts only go up, and Clear does not reset them. For rates, take a @@ -62,8 +65,9 @@ type Snapshot struct { // that they did not. Hits, Misses uint64 - // Evictions counts the entries that Set pushed out to make room, and - // those that a cache without capacity handed straight back. + // Evictions counts the entries that Set and SetIfAbsent pushed out to + // make room, and those that a cache without capacity handed straight + // back. Evictions uint64 // Len is the number of entries in the cache, and Cap the number it can @@ -221,6 +225,20 @@ func (c *Cache[K, V]) Set(key K, value V) (oldKey K, oldValue V, displaced bool) return oldKey, oldValue, displaced } +// SetIfAbsent stores value under key unless the cache holds key already, and +// counts an eviction if the entry it reports is not one that key had, as Set +// does. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + actual, present, oldKey, oldValue, evicted = c.cache.SetIfAbsent(key, value) + // The caches of this module only report an entry of another key, or + // the new one itself if they have no capacity. An expire.Cache may also + // report the expired entry of key that the new one replaced. + if evicted && (oldKey != key || c.zero) { + atomic.AddUint64(&c.stripe().evictions, 1) + } + return actual, present, oldKey, oldValue, evicted +} + // 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) } diff --git a/stats/stats_test.go b/stats/stats_test.go index ce9e8df..6e27df9 100644 --- a/stats/stats_test.go +++ b/stats/stats_test.go @@ -110,16 +110,26 @@ func TestCounts(t *testing.T) { } want("an eviction", 2, 1, 1, 2) + if _, present, _, _, evicted := c.SetIfAbsent("a", 11); !present || evicted { + t.Fatalf("SetIfAbsent(a) = %t, evicted %t; want a found", present, evicted) + } + want("SetIfAbsent of a key that is there", 2, 1, 1, 2) + + if _, present, k, _, evicted := c.SetIfAbsent("d", 4); present || !evicted || k == "d" { + t.Fatalf("SetIfAbsent(d) = %t, evicted %q, %t; want an entry evicted for d", present, k, evicted) + } + want("SetIfAbsent with an eviction", 2, 1, 2, 2) + c.Peek("a") c.Peek("x") c.Delete("a") c.Delete("x") for range c.All() { } - want("Peek, Delete and All", 2, 1, 1, 1) + want("Peek, Delete and All", 2, 1, 2, 1) c.Clear() - want("Clear", 2, 1, 1, 0) + want("Clear", 2, 1, 2, 0) } // A cache without capacity hands every new entry straight back, with the key @@ -130,9 +140,10 @@ func TestZeroCapacity(t *testing.T) { c := stats.Wrap(lru.New[int, int](0)) c.Set(1, 1) c.Set(1, 1) + c.SetIfAbsent(1, 1) c.Get(1) - want := stats.Snapshot{Misses: 1, Evictions: 2} + want := stats.Snapshot{Misses: 1, Evictions: 3} if got := c.Stats(); got != want { t.Errorf("Stats() = %+v, want %+v", got, want) } @@ -176,23 +187,39 @@ func TestEveryPolicy(t *testing.T) { if s := c.Stats(); s.Evictions != 0 || s.Len != 1 { t.Fatalf("-0 replacing +0: %d evictions and %d entries, want 0 and 1", s.Evictions, s.Len) } + if _, present, _, _, _ := c.SetIfAbsent(0, 0); !present { + t.Fatal("SetIfAbsent(+0) did not find -0") + } // Some keys are read, so that the policies that promote entries // have some to promote, and twoq some to remember. - added := uint64(1) + // Every other key is written with SetIfAbsent, which counts no + // hit or miss. + added, gets := uint64(1), uint64(0) for i := 1; i < 20*capacity; i++ { key := float64(i % (3 * capacity)) - if _, ok := c.Get(key); !ok { - added++ + if i%2 == 0 { + if _, present, _, _, _ := c.SetIfAbsent(key, i); !present { + added++ + } + } else { + if _, ok := c.Get(key); !ok { + added++ + } + c.Set(key, i) + gets++ } - c.Set(key, i) c.Get(float64(i % 50)) + gets++ } s := c.Stats() if s.Evictions != added-uint64(s.Len) { t.Errorf("%d entries added, %d evicted and %d left", added, s.Evictions, s.Len) } + if s.Hits+s.Misses != gets { + t.Errorf("%d hits and %d misses for %d calls of Get", s.Hits, s.Misses, gets) + } }) } } diff --git a/tinylfu/bench_test.go b/tinylfu/bench_test.go index 03dbab9..db0a224 100644 --- a/tinylfu/bench_test.go +++ b/tinylfu/bench_test.go @@ -109,6 +109,39 @@ func BenchmarkSet(b *testing.B) { }) } +// BenchmarkSetIfAbsent is BenchmarkSet with SetIfAbsent: for keys that the +// cache holds, which it reads, and for new ones, which it stores. +func BenchmarkSetIfAbsent(b *testing.B) { + b.Run("present", func(b *testing.B) { + c := tinylfu.New[int, int](benchCapacity, tinylfu.WithShards(1)) + for key := range benchCapacity { + c.Set(key, key) + } + keys := benchKeys() + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(keys[i&(len(keys)-1)], i) + i++ + } + }) + + b.Run("evict", func(b *testing.B) { + c := tinylfu.New[int, int](benchCapacity, tinylfu.WithShards(1)) + for key := range benchCapacity { + c.Set(-key-1, key) + } + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(i, i) // Always a new key, so always an eviction. + i++ + } + }) +} + // BenchmarkParallel has every CPU working on the same cache: three reads for // every write, on keys of which a few are much more popular than the rest and // a quarter does not fit. diff --git a/tinylfu/example_test.go b/tinylfu/example_test.go index 364f6f1..9dc3e31 100644 --- a/tinylfu/example_test.go +++ b/tinylfu/example_test.go @@ -45,3 +45,25 @@ func ExampleCache_Set() { // replaced a=first // evicted a=second } + +// A value that is loaded after a miss is stored with SetIfAbsent, so that one +// that was stored in the meantime, which may be newer, is kept and used. +func ExampleCache_SetIfAbsent() { + cache := tinylfu.New[string, string](100) + + load := func(key string) string { + // While this goroutine loads the value, another one stores a newer + // one. + cache.Set(key, "newer") + return "loaded" + } + + value, ok := cache.Get("a") + if !ok { + value, _, _, _, _ = cache.SetIfAbsent("a", load("a")) + } + fmt.Println(value) + + // Output: + // newer +} diff --git a/tinylfu/tinylfu.go b/tinylfu/tinylfu.go index 88eaf3a..648a154 100644 --- a/tinylfu/tinylfu.go +++ b/tinylfu/tinylfu.go @@ -136,7 +136,7 @@ type shard[K comparable, V any] struct { // full says that the shard has been full since it was made or last // cleared. Until then, new entries are not all sent through the small - // queue; see set. + // queue; see add. full bool // win is the window of the cache. The shard tells it of the hits that it @@ -455,6 +455,46 @@ func (s *shard[K, V]) set(h uint64, key K, value V) (oldKey K, oldValue V, displ s.hits++ return oldKey, oldValue, true } + return s.add(h, key, value) +} + +// SetIfAbsent stores value under key unless the cache holds key already. If +// it does, SetIfAbsent changes nothing but counts a read, as Get does, and +// returns the value that key has, with present true. Otherwise it stores value +// as Set does, the sketch counts a request for key, and SetIfAbsent returns +// value with present false and reports the entry that the key's shard evicted +// to make room, if any. A cache without capacity hands the new entry straight +// back as evicted. +// +// Looking for key and storing value happen at once, under the lock of the +// key's shard: of the goroutines that call SetIfAbsent for one key at the +// same time, one stores its value and the others get it back as actual, +// unless it has left the cache in between. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + h := maphash.Comparable(c.seed, key) + s := &c.shards[uint32(h>>32)&c.mask] + + s.mu.Lock() + if idx := s.slab.Find(uint32(h), key); idx != 0 { + n := &s.slab.Nodes[idx] + n.SetMeta(min(n.Meta()+1, maxCount)) + s.hits++ + actual = n.Value + s.mu.Unlock() + return actual, true, oldKey, oldValue, false + } + oldKey, oldValue, evicted = s.add(h, key, value) + s.mu.Unlock() + + return value, false, oldKey, oldValue, evicted +} + +// add stores an entry for a key that the shard does not hold, and returns the +// entry that it evicted to make room, if any, or the new entry itself if the +// shard has no capacity. +func (s *shard[K, V]) add(h uint64, key K, value V) (oldKey K, oldValue V, evicted bool) { + sl := &s.slab + hash := uint32(h) if s.capacity == 0 { return key, value, true @@ -469,7 +509,7 @@ func (s *shard[K, V]) set(h uint64, key K, value V) (oldKey K, oldValue V, displ } if s.smalls+s.mains == s.capacity { oldKey, oldValue = s.evict() - displaced = true + evicted = true } // A shard that has yet to fill up for the first time has nothing to @@ -490,7 +530,7 @@ func (s *shard[K, V]) set(h uint64, key K, value V) (oldKey K, oldValue V, displ sl.PushFront(small, idx) s.smalls++ } - return oldKey, oldValue, displaced + return oldKey, oldValue, evicted } // look takes stock of the entry in node idx: it tells the sketch of the reads @@ -727,6 +767,7 @@ var ( _ = (*Cache[int, int]).Peek _ = (*Cache[int, int]).GetMany _ = (*Cache[int, int]).Set + _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear diff --git a/tinylfu/tinylfu_test.go b/tinylfu/tinylfu_test.go index 58fbb35..f4c1825 100644 --- a/tinylfu/tinylfu_test.go +++ b/tinylfu/tinylfu_test.go @@ -679,6 +679,15 @@ func (m *model) evict() (key, value int) { return against.key, against.value } +// SetIfAbsent is Get for a key that is there and Set for one that is not. +func (m *model) SetIfAbsent(key, value int) (actual int, present bool, oldKey, oldValue int, evicted bool) { + if actual, ok := m.Get(key); ok { + return actual, true, 0, 0, false + } + oldKey, oldValue, evicted = m.Set(key, value) + return value, false, oldKey, oldValue, evicted +} + func (m *model) Delete(key int) (int, bool) { e := m.find(key) if e == nil { diff --git a/twoq/bench_test.go b/twoq/bench_test.go index 3ef072e..2571345 100644 --- a/twoq/bench_test.go +++ b/twoq/bench_test.go @@ -120,6 +120,35 @@ func BenchmarkSet(b *testing.B) { }) } +// BenchmarkSetIfAbsent is BenchmarkSet with SetIfAbsent: for keys that the +// cache holds, which it reads, and for new ones, which it stores. +func BenchmarkSetIfAbsent(b *testing.B) { + number := func(i int) int { return i } + + b.Run("present", func(b *testing.B) { + c := steady(number) + keys := benchKeys(frequentFrom, frequentTo) + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(keys[i&(len(keys)-1)], i) + i++ + } + }) + + b.Run("evict", func(b *testing.B) { + c := steady(number) + + b.ReportAllocs() + i := 0 + for b.Loop() { + c.SetIfAbsent(-i-1, i) // Always a new key, so always an eviction. + i++ + } + }) +} + // BenchmarkParallel has every CPU working on the same cache: three reads for // every write, on keys of which a few are much more popular than the rest and // a quarter does not fit. diff --git a/twoq/twoq.go b/twoq/twoq.go index c149a36..ec8e0c5 100644 --- a/twoq/twoq.go +++ b/twoq/twoq.go @@ -270,18 +270,8 @@ func (s *shard[K, V]) set(hash uint32, key K, value V) (oldKey K, oldValue V, di sl := &s.slab idx := sl.Find(hash, key) - if idx == 0 { - if s.capacity == 0 { - return key, value, true - } - oldKey, oldValue, displaced = s.makeRoom() - sl.PushFront(recent, sl.Insert(hash, key, value)) // Meta is zero, which is recent. - s.recents++ - return oldKey, oldValue, displaced - } - - n := &sl.Nodes[idx] - if n.Meta != ghost { + if idx != 0 && sl.Nodes[idx].Meta != ghost { + n := &sl.Nodes[idx] oldKey, oldValue = n.Key, n.Value // The new key takes the place of the old one, although they are // equal: they may still differ in what they refer to, and the @@ -292,19 +282,74 @@ func (s *shard[K, V]) set(hash uint32, key K, value V) (oldKey K, oldValue V, di } return oldKey, oldValue, true } + return s.add(idx, hash, key, value) +} + +// SetIfAbsent stores value under key unless the cache holds an entry for key +// already. If it does, SetIfAbsent changes nothing but treats the entry as if +// it had been read, and returns the value that key has, with present true. +// Otherwise it stores value as Set does, returns it with present false, and +// reports the entry that the key's shard evicted to make room, if any. A key +// that the cache merely remembers having evicted counts as one that it does +// not hold. A cache without capacity hands the new entry straight back as +// evicted. +// +// Looking for key and storing value happen at once, under the lock of the +// key's shard: of the goroutines that call SetIfAbsent for one key at the +// same time, one stores its value and the others get it back as actual, +// unless it has left the cache in between. +func (c *Cache[K, V]) SetIfAbsent(key K, value V) (actual V, present bool, oldKey K, oldValue V, evicted bool) { + h := maphash.Comparable(c.seed, key) + s, hash := &c.shards[uint32(h>>32)&c.mask], uint32(h) + + s.mu.Lock() + idx := s.slab.Find(hash, key) + if idx != 0 { + if n := &s.slab.Nodes[idx]; n.Meta != ghost { + if n.Meta == frequent { + s.slab.MoveToFront(frequent, idx) + } + actual = n.Value + s.mu.Unlock() + return actual, true, oldKey, oldValue, false + } + } + oldKey, oldValue, evicted = s.add(idx, hash, key, value) + s.mu.Unlock() + + return value, false, oldKey, oldValue, evicted +} + +// add stores an entry for a key that the shard does not hold, and returns the +// entry that it evicted to make room, if any, or the new entry itself if the +// shard has no capacity. idx is the node that remembers the key, or zero if +// the shard does not remember it. +func (s *shard[K, V]) add(idx, hash uint32, key K, value V) (oldKey K, oldValue V, evicted bool) { + sl := &s.slab + + if idx == 0 { + if s.capacity == 0 { + return key, value, true + } + oldKey, oldValue, evicted = s.makeRoom() + sl.PushFront(recent, sl.Insert(hash, key, value)) // Meta is zero, which is recent. + s.recents++ + return oldKey, oldValue, evicted + } // The key was evicted from the recent queue not long ago, and here it // is again. Its node becomes an entry of the frequent queue. It leaves // the memory before room is made, so that the key of the entry evicted // for it can take its place there instead of pushing out another one. + n := &sl.Nodes[idx] sl.Unlink(idx) s.ghosts-- - oldKey, oldValue, displaced = s.makeRoom() + oldKey, oldValue, evicted = s.makeRoom() n.Key, n.Value = key, value n.Meta = frequent sl.PushFront(frequent, idx) s.frequents++ - return oldKey, oldValue, displaced + return oldKey, oldValue, evicted } // makeRoom evicts an entry if the shard is full, and returns it. @@ -449,6 +494,7 @@ var ( _ = (*Cache[int, int]).Get _ = (*Cache[int, int]).Peek _ = (*Cache[int, int]).Set + _ = (*Cache[int, int]).SetIfAbsent _ = (*Cache[int, int]).Delete _ = (*Cache[int, int]).Len _ = (*Cache[int, int]).Clear diff --git a/twoq/twoq_test.go b/twoq/twoq_test.go index f24bad0..fd862db 100644 --- a/twoq/twoq_test.go +++ b/twoq/twoq_test.go @@ -321,6 +321,15 @@ func (m *model) Set(key, value int) (oldKey, oldValue int, displaced bool) { return oldKey, oldValue, displaced } +// SetIfAbsent is Get for a key that is there and Set for one that is not. +func (m *model) SetIfAbsent(key, value int) (actual int, present bool, oldKey, oldValue int, evicted bool) { + if actual, ok := m.Get(key); ok { + return actual, true, 0, 0, false + } + oldKey, oldValue, evicted = m.Set(key, value) + return value, false, oldKey, oldValue, evicted +} + func (m *model) Delete(key int) (int, bool) { value, ok := m.Peek(key) m.frequent = slices.DeleteFunc(m.frequent, func(e entry) bool { return e.key == key })