sinmai-mods/ImproveLoadTimes/Manager/patch_DataManager.cs
2024-08-08 13:32:25 +07:00

100 lines
2.7 KiB
C#

// ReSharper disable CheckNamespace
// ReSharper disable InconsistentNaming
using System.Runtime.Serialization.Formatters.Binary;
namespace Manager;
public class patch_DataManager : DataManager
{
private const string _cacheFilename = "data_cache.bin";
private static Dictionary<string, object>? _cache;
private static bool _cacheBusted;
private static extern bool orig_Deserialize<T>(string filePath, out T dsr) where T : new();
private static bool Deserialize<T>(string filePath, out T dsr) where T : new()
{
try
{
_cache ??= LoadCache(_cacheFilename);
}
catch (Exception e)
{
System.Console.WriteLine("[ImproveLoadTimes] Could not load data cache: {0}", e);
_cache ??= new Dictionary<string, object>();
}
try
{
if (_cache.TryGetValue(filePath, out var dsrObject))
{
dsr = (T)dsrObject;
return true;
}
if (!orig_Deserialize(filePath, out dsr))
{
return false;
}
// ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
if (filePath == null || dsr == null)
{
return true;
}
_cache.Add(filePath, dsr);
_cacheBusted = true;
return true;
}
catch (Exception e)
{
System.Console.WriteLine("[ImproveLoadTimes] [ERROR] Could not load from cache: {0}", e);
return orig_Deserialize(filePath, out dsr);
}
}
private extern bool orig_IsLoaded();
public new bool IsLoaded()
{
var loaded = orig_IsLoaded();
if (!loaded || !_cacheBusted || _cache == null)
{
return loaded;
}
try
{
SaveCache(_cacheFilename, _cache);
}
catch (Exception e)
{
System.Console.WriteLine("[ImproveLoadTimes] [ERROR] Could not save to cache: {0}", e);
}
_cacheBusted = false;
return true;
}
private static Dictionary<string, object> LoadCache(string fileName)
{
if (!File.Exists(fileName))
{
return new Dictionary<string, object>();
}
System.Console.WriteLine("[ImproveLoadTimes] Loading data cache...");
using var fs = File.OpenRead(fileName);
return (Dictionary<string, object>)new BinaryFormatter().Deserialize(fs);
}
private static void SaveCache(string fileName, Dictionary<string, object> cache)
{
using var fs = File.Open(fileName, FileMode.Create, FileAccess.Write);
new BinaryFormatter().Serialize(fs, cache);
}
}