diff options
author | Jesse Plamondon-Willard <Pathoschild@users.noreply.github.com> | 2022-03-22 23:00:18 -0400 |
---|---|---|
committer | Jesse Plamondon-Willard <Pathoschild@users.noreply.github.com> | 2022-03-22 23:00:18 -0400 |
commit | b07d2340a9a6da22ee0fd95f2c6ccca3939cb7ab (patch) | |
tree | c61a7108ff66071b9b6feb5446c6bd3e14ba8182 /src/SMAPI/Framework/Utilities | |
parent | d3fbdf484a4d90365a55fb5058d75a8623f17d0f (diff) | |
download | SMAPI-b07d2340a9a6da22ee0fd95f2c6ccca3939cb7ab.tar.gz SMAPI-b07d2340a9a6da22ee0fd95f2c6ccca3939cb7ab.tar.bz2 SMAPI-b07d2340a9a6da22ee0fd95f2c6ccca3939cb7ab.zip |
encapsulate & cache asset operation groups (#766)
This is needed for the upcoming Stardew Valley 1.6 to avoid duplicate checks between DoesAssetExist and Load calls, and to make sure the answer doesn't change between them.
Diffstat (limited to 'src/SMAPI/Framework/Utilities')
-rw-r--r-- | src/SMAPI/Framework/Utilities/TickCacheDictionary.cs | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs b/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs new file mode 100644 index 00000000..1613a480 --- /dev/null +++ b/src/SMAPI/Framework/Utilities/TickCacheDictionary.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using StardewValley; + +namespace StardewModdingAPI.Framework.Utilities +{ + /// <summary>An in-memory dictionary cache that stores data for the duration of a game update tick.</summary> + /// <typeparam name="TKey">The dictionary key type.</typeparam> + /// <typeparam name="TValue">The dictionary value type.</typeparam> + internal class TickCacheDictionary<TKey, TValue> + { + /********* + ** Fields + *********/ + /// <summary>The last game tick for which data was cached.</summary> + private int LastGameTick = -1; + + /// <summary>The underlying cached data.</summary> + private readonly Dictionary<TKey, TValue> Cache = new(); + + + /********* + ** Public methods + *********/ + /// <summary>Get a value from the cache, fetching it first if it's not cached yet.</summary> + /// <param name="cacheKey">The unique key for the cached value.</param> + /// <param name="get">Get the latest data if it's not in the cache yet.</param> + public TValue GetOrSet(TKey cacheKey, Func<TValue> get) + { + // clear cache on new tick + if (Game1.ticks != this.LastGameTick) + { + this.Cache.Clear(); + this.LastGameTick = Game1.ticks; + } + + // fetch value + if (!this.Cache.TryGetValue(cacheKey, out TValue cached)) + this.Cache[cacheKey] = cached = get(); + return cached; + } + + /// <summary>Remove an entry from the cache.</summary> + /// <param name="cacheKey">The unique key for the cached value.</param> + /// <returns>Returns whether the key was present in the dictionary.</returns> + public bool Remove(TKey cacheKey) + { + return this.Cache.Remove(cacheKey); + } + } +} |