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

61 lines
1.8 KiB
C#
Raw Normal View History

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace MU3.Data;
public class DataStudioManager {
public static bool needSave;
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() {
if(File.Exists("data_cache.bin")) {
System.Console.WriteLine("Loading cache...");
using FileStream serializationStream = File.OpenRead("data_cache.bin");
_dataCache = (Dictionary<string, object>)new BinaryFormatter().Deserialize(serializationStream);
return;
}
_dataCache = new Dictionary<string, object>();
}
private static void SaveCache() {
if(File.Exists("data_cache.bin")) {
File.Delete("data_cache.bin");
}
using FileStream serializationStream = File.OpenWrite("data_cache.bin");
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<T>(filePath, out dsr)) {
needSave = true;
_dataCache.Add(filePath, dsr);
return true;
}
return false;
}
public extern bool orig_IsLoaded();
public bool IsLoaded() {
if(orig_IsLoaded()) {
if(needSave) {
System.Console.WriteLine("Saving cache...");
SaveCache();
}
return true;
}
return false;
}
}