using System; using System.Collections.Generic; using StardewValley; namespace StardewModdingAPI.Framework.Utilities { /// An in-memory dictionary cache that stores data for the duration of a game update tick. /// The dictionary key type. /// The dictionary value type. internal class TickCacheDictionary { /********* ** Fields *********/ /// The last game tick for which data was cached. private int LastGameTick = -1; /// The underlying cached data. private readonly Dictionary Cache = new(); /********* ** Public methods *********/ /// Get a value from the cache, fetching it first if it's not cached yet. /// The unique key for the cached value. /// Get the latest data if it's not in the cache yet. public TValue GetOrSet(TKey cacheKey, Func 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; } /// Remove an entry from the cache. /// The unique key for the cached value. /// Returns whether the key was present in the dictionary. public bool Remove(TKey cacheKey) { return this.Cache.Remove(cacheKey); } } }