MenuFileCache.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System.IO;
  2. using System.Collections.Generic;
  3. /*
  4. All of this is pretty much stolen from COM3D2.CacheEditMenu. Thanks Mr. Horsington.
  5. https://git.coder.horse/ghorsington/COM3D2.CacheEditMenu
  6. */
  7. namespace COM3D2.MeidoPhotoStudio.Plugin
  8. {
  9. using static MenuFileUtility;
  10. internal static class BinaryExtensions
  11. {
  12. public static string ReadNullableString(this BinaryReader binaryReader)
  13. {
  14. return binaryReader.ReadBoolean() ? binaryReader.ReadString() : null;
  15. }
  16. public static void WriteNullableString(this BinaryWriter binaryWriter, string str)
  17. {
  18. binaryWriter.Write(str != null);
  19. if (str != null) binaryWriter.Write(str);
  20. }
  21. }
  22. internal class MenuFileCache
  23. {
  24. private const int cacheVersion = 765;
  25. public static readonly string cachePath = Path.Combine(Constants.configPath, "cache.dat");
  26. private Dictionary<string, ModItem> modItems;
  27. private bool rebuild = false;
  28. public ModItem this[string menu]
  29. {
  30. get => modItems[menu];
  31. set
  32. {
  33. if (!modItems.ContainsKey(menu))
  34. {
  35. rebuild = true;
  36. modItems[menu] = value;
  37. }
  38. }
  39. }
  40. public MenuFileCache()
  41. {
  42. modItems = new Dictionary<string, ModItem>();
  43. if (File.Exists(cachePath)) Deserialize();
  44. }
  45. public bool Has(string menuFileName)
  46. {
  47. return modItems.ContainsKey(menuFileName);
  48. }
  49. private void Deserialize()
  50. {
  51. using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(cachePath)))
  52. {
  53. if (binaryReader.ReadInt32() != cacheVersion)
  54. {
  55. Utility.Logger.LogInfo($"Cache version out of date. Rebuilding");
  56. return;
  57. }
  58. while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
  59. {
  60. ModItem item = ModItem.Deserialize(binaryReader);
  61. modItems[item.MenuFile] = item;
  62. }
  63. }
  64. }
  65. public void Serialize()
  66. {
  67. if (!rebuild) return;
  68. using (BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(cachePath)))
  69. {
  70. binaryWriter.Write(cacheVersion);
  71. foreach (ModItem item in modItems.Values)
  72. {
  73. item.Serialize(binaryWriter);
  74. }
  75. }
  76. }
  77. }
  78. }