mu3-mods/LoadBoost/MU3.Data/patch_DataStudioManager.cs

67 lines
2.0 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace MU3.Data;
public class patch_DataStudioManager: DataStudioManager {
public static bool needSave;
private static string _fileName;
private static Dictionary<string, object> _dataCache;
private static extern bool orig_Deserialize<T>(string filePath, out T dsr) where T : new();
private static void initCache() {
using IniFile iniFile = new("mu3.ini");
_fileName = Path.Combine(iniFile.getValue("Extra", "CacheDir", "."), "data_cache.bin");
if(File.Exists(_fileName)) {
System.Console.WriteLine("Loading data cache...");
using FileStream serializationStream = File.OpenRead(_fileName);
_dataCache = (Dictionary<string, object>)new BinaryFormatter().Deserialize(serializationStream);
return;
}
_dataCache = new();
}
private static void saveCache() {
if(_fileName == "") {
return;
}
if(File.Exists(_fileName)) {
File.Delete(_fileName);
}
using FileStream serializationStream = File.OpenWrite(_fileName);
new BinaryFormatter().Serialize(serializationStream, _dataCache);
}
private static bool Deserialize<T>(string filePath, out T dsr) where T : new() {
if(_dataCache == null) {
initCache();
}
if(_dataCache.ContainsKey(filePath)) {
dsr = (T)_dataCache[filePath];
return true;
}
if(orig_Deserialize(filePath, out dsr)) {
needSave = true;
_dataCache.Add(filePath, dsr);
return true;
}
return false;
}
public extern bool orig_IsLoaded();
public new bool IsLoaded() {
if(orig_IsLoaded()) {
if(needSave) {
System.Console.WriteLine("Saving data cache...");
saveCache();
}
return true;
}
return false;
}
}