From 86fa77e77e9f317e098a66f2862463d59a5f0e08 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Sep 2023 16:13:31 +0200 Subject: [PATCH] Add DynamicCache type --- .../ComputeSharp.SourceGeneration.projitems | 1 + .../Helpers/DynamicCache{TKey,TValue}.cs | 234 ++++++++++++++++++ 2 files changed, 235 insertions(+) create mode 100644 src/ComputeSharp.SourceGeneration/Helpers/DynamicCache{TKey,TValue}.cs diff --git a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems index 0e4410f2..289de1ea 100644 --- a/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems +++ b/src/ComputeSharp.SourceGeneration/ComputeSharp.SourceGeneration.projitems @@ -17,6 +17,7 @@ + diff --git a/src/ComputeSharp.SourceGeneration/Helpers/DynamicCache{TKey,TValue}.cs b/src/ComputeSharp.SourceGeneration/Helpers/DynamicCache{TKey,TValue}.cs new file mode 100644 index 00000000..4e05eceb --- /dev/null +++ b/src/ComputeSharp.SourceGeneration/Helpers/DynamicCache{TKey,TValue}.cs @@ -0,0 +1,234 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Runtime.CompilerServices; + +namespace ComputeSharp.SourceGeneration.Helpers; + +/// +/// A dynamic cache that can be used to cache computed values within incremental models. +/// This automatically trims excess items, and relies on the incremental state tables +/// keeping values alive for at least one incremental step, in order to work correctly. +/// +/// The type of keys to use for the cache. +/// The type of values to store in the cache. +public sealed class DynamicCache + where TKey : class +{ + /// + /// The backing instance for the cache. + /// + private readonly ConcurrentDictionary map = new(); + + /// + /// Gets or creates a new value for a given key, using a supplied callback if needed. + /// + /// The key to use as lookup. + /// The callback to use to create new values, if needed. + /// The resulting value. + /// + /// This method might replace with a new instance that has the same + /// value according to its equality comparison logic. Callers should always use the last value of + /// after this method returns and discard the previous one, if different. + /// + public TValue GetOrCreate(ref TKey key, GetOrCreateCallback callback) + { + // Create a new entry that we will use to perform the lookup. + // Each entry simply forwards equality logic to the wrapped object. + Entry entry = new(key); + + while (true) + { + // We're performing a lookup on this temporary entry. We need it to + // track the value it will potentially match against, so we can + // return it to the caller. This ensures the same object is used. + entry.SetIsPerformingLookup(true); + + // Try to check whether we already have a value in the cache for + // this object. That is, we want to check whether there is an entry + // with a value equal to the one we have now (not necessarily the same + // object). If we find it, we return it and throw away the new entry. + if (this.map.TryGetValue(entry, out TValue? value)) + { + // We have a match, so replace the object with the one that actually matched. + // This guarantees that it will remain alive, so the entry will not die. + key = entry.GetLastMatchedValue(); + + return value; + } + + // Execute the slow fallback path, invoking the callback and trying to add a new + // value to the cache. If this succeeds, it means that the current key object has + // been added to the cache, so there is nothing left to do. If this fails, it means + // another thread has beat us to adding the key, so we should perform the initial + // lookup again to make sure we can find the exact instance that is in the cache. + // This is needed to ensure valid cache entries remain alive over time. + if (TryGetOrCreate(entry, key, callback, out value)) + { + return value; + } + } + } + + /// + /// Tries to get or create a new value for a given key, using a supplied callback. + /// + /// The instance to try to insert into the cache. + /// The key to use as lookup. + /// The callback to use to create new values, if needed. + /// The resulting value (should be ignored if the method fails). + /// Whether was successfully inserted into the cache. + [MethodImpl(MethodImplOptions.NoInlining)] + private bool TryGetOrCreate(Entry entry, TKey key, GetOrCreateCallback callback, out TValue value) + { + // No value is present, so we can create it now + value = callback(key); + + // We're about to try to add the item to the cache, so we no longer need to + // track the last matched value. We already have a reference to the object. + entry.SetIsPerformingLookup(false); + + // Try to add the value (this only fails if someone raced with this thread). + // In this case, our key will also be added to the cache. Callers will have + // a strong reference to it, which ensures the weak reference remains alive. + if (!this.map.TryAdd(entry, value)) + { + return false; + } + + // As part of the fallback step, traverse all items and remove dead keys + foreach (Entry candidateKey in this.map.Keys) + { + if (!candidateKey.IsAlive) + { + _ = this.map.TryRemove(candidateKey, out _); + } + } + + return true; + } + + /// + /// A callback to create a new value from a given key. + /// + /// The resulting instance. + /// + public delegate TValue GetOrCreateCallback(TKey key); + + /// + /// An entry to use in . + /// + private sealed class Entry + { + /// + /// A weak reference to the actual entry instance. + /// + private readonly WeakReference reference; + + /// + /// The last key matched from , if available. + /// + private TKey? lastMatchedKey; + + /// + /// Indicates whether the entry is currently in lookup mode. + /// + private bool isPerformingLookup; + + /// + /// Creates a new instance with the specified parameters. + /// + /// The key to use for the entry. + public Entry(TKey key) + { + this.reference = new WeakReference(key); + } + + /// + /// Gets whether or not the current entry is alive. + /// + public bool IsAlive => this.reference.TryGetTarget(out _); + + /// + /// Gets the last matched key retrieved during a lookup operation. + /// + /// The last matched key retrieved during a lookup operation. + /// Thrown if no key is available. + public TKey GetLastMatchedValue() + { + TKey? lastMatchedKey = this.lastMatchedKey; + + if (lastMatchedKey is null) + { + EntryHelper.ThrowInvalidOperationExceptionForLastMatchedKey(); + } + + return lastMatchedKey; + } + + /// + /// Sets whether the current instance is performing a lookup. + /// + /// The new value for the configuration. + public void SetIsPerformingLookup(bool value) + { + this.lastMatchedKey = null; + this.isPerformingLookup = value; + } + + /// + public override bool Equals(object? obj) + { + if (obj is not Entry entry) + { + return false; + } + + _ = this.reference.TryGetTarget(out TKey? left); + _ = entry.reference.TryGetTarget(out TKey? right); + + bool isMatch = EqualityComparer.Default.Equals(left, right); + + // If we have a match and we're in lookup mode, store the last item. + // Otherwise, clear it to also make sure not to accidentally root + // keys that are not actually in the cache anymore. + if (isMatch && this.isPerformingLookup) + { + this.lastMatchedKey = right; + } + else + { + this.lastMatchedKey = null; + } + + return isMatch; + } + + /// + public override int GetHashCode() + { + if (this.reference.TryGetTarget(out TKey? value)) + { + return EqualityComparer.Default.GetHashCode(value); + } + + return 0; + } + } +} + +/// +/// Private helpers for the type. +/// +file static class EntryHelper +{ + /// + /// Throws an when there is no last matching key. + /// + [DoesNotReturn] + public static void ThrowInvalidOperationExceptionForLastMatchedKey() + { + throw new InvalidOperationException("No last matching key has been found."); + } +} \ No newline at end of file