|
- using System.IO;
- using System.IO.Compression;
- using HarmonyLib;
-
- namespace Kompressor
- {
- [HarmonyPatch(typeof(File), "ReadAllBytes")]
- public class FileReadAllBytesPatch
- {
- public static void Postfix(string path, ref byte[] __result)
- {
- if (!path.EndsWith("GameSave.GC")) return; // not a save file; do nothing
- for (byte i = 0; i < MyPlugin.COMPRESSION_FRAME_START.Length; i++)
- {
- if (__result[i] != MyPlugin.COMPRESSION_FRAME_START[i])
- {
- // Don't do anything; not compressed
- return;
- }
- }
- GamecraftModdingAPI.Utility.Logging.MetaLog($"Reading compressed save from {path}");
- // remove frame at start of file
- byte[] compressedResult = new byte[__result.Length - MyPlugin.COMPRESSION_FRAME_START.Length];
- for (long i = MyPlugin.COMPRESSION_FRAME_START.Length; i < __result.Length; i++)
- {
- compressedResult[i - MyPlugin.COMPRESSION_FRAME_START.Length] = __result[i];
- }
- MemoryStream compressedData = new MemoryStream(compressedResult);
- // decompress
- GZipStream gzip = new GZipStream(compressedData, CompressionMode.Decompress, true);
- // update result
- MemoryStream decompressedData = new MemoryStream();
- byte[] buffer = new byte[1];
- int readCount = gzip.Read(buffer, 0, 1);
- while (readCount != 0)
- {
- decompressedData.Write(buffer, 0, 1);
- readCount = gzip.Read(buffer, 0, 1);
- }
- gzip.Close();
- byte[] newResult = new byte[decompressedData.Length];
- decompressedData.Seek(0, 0);
- decompressedData.Read(newResult, 0, (int)decompressedData.Length);
- GamecraftModdingAPI.Utility.Logging.MetaLog($"compressedData.Length: {compressedData.Length}");
- GamecraftModdingAPI.Utility.Logging.MetaLog($"decompressedData.Length: {decompressedData.Length}");
- GamecraftModdingAPI.Utility.Logging.MetaLog($"newResult: \"{System.Text.Encoding.UTF8.GetString(newResult)}\"");
- GamecraftModdingAPI.Utility.Logging.MetaLog($"Completed decompression of save");
- __result = newResult;
- compressedData.Close();
- decompressedData.Close();
- }
- }
- }
|