MenuFileCache.cs 2.6 KB

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