using Newtonsoft.Json; using OWML.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; namespace NewHorizons.Utility { public class Cache { string filepath; IModBehaviour mod; Dictionary data = new Dictionary(); HashSet accessedKeys = new HashSet(); public Cache(IModBehaviour mod, string cacheFilePath) { this.mod = mod; this.filepath = cacheFilePath; var fullPath = mod.ModHelper.Manifest.ModFolderPath + cacheFilePath; if (!File.Exists(fullPath)) { Logger.LogWarning("Cache file not found! Cache path: " + cacheFilePath); data = new Dictionary(); return; } var json = File.ReadAllText(fullPath); data = JsonConvert.DeserializeObject>(json); // the code above does exactly the same thing that the code below does, but the below for some reason always returns null. no clue why // data = mod.ModHelper.Storage.Load>(filepath); } public void WriteToFile() { if (data.Count <= 0) return; // don't write empty caches mod.ModHelper.Storage.Save>(data, filepath); } public bool ContainsKey(string key) { return data.ContainsKey(key); } public T Get(string key) { accessedKeys.Add(key); var json = data[key]; return JsonConvert.DeserializeObject(json); } public void Set(string key, T value) { accessedKeys.Add(key); data[key] = JsonConvert.SerializeObject(value); } public void ClearUnaccessed() { var keys = data.Keys.ToList(); foreach(var key in keys) { if (accessedKeys.Contains(key)) continue; data.Remove(key); } } } }