Add Cache Compression

This commit is contained in:
Namhyeon Go 2025-04-06 15:23:19 +09:00
parent 2cb3c1c331
commit f7de7bd430

View File

@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Reflection;
@ -213,7 +214,15 @@ namespace WelsonJS.Launcher
{
if (File.Exists(cachePath))
{
data = File.ReadAllBytes(cachePath);
byte[] raw = File.ReadAllBytes(cachePath);
if (isMetadata)
{
data = raw;
return true;
}
data = IsCompressed(raw) ? Decompress(raw) : raw;
return true;
}
}
@ -255,7 +264,8 @@ namespace WelsonJS.Launcher
}
// Save the cache
File.WriteAllBytes(cachePath, data);
byte[] compressed = Compress(data);
File.WriteAllBytes(cachePath, compressed);
// Save the cache meta
File.WriteAllBytes($"{cachePath}.meta", Encoding.UTF8.GetBytes(mimeType));
@ -360,5 +370,34 @@ namespace WelsonJS.Launcher
return memoryStream.ToArray();
}
}
private byte[] Compress(byte[] data)
{
using (var output = new MemoryStream())
{
using (var gzip = new GZipStream(output, CompressionMode.Compress))
{
gzip.Write(data, 0, data.Length);
}
return output.ToArray(); // includes GZip signature
}
}
private byte[] Decompress(byte[] data)
{
using (var input = new MemoryStream(data))
using (var gzip = new GZipStream(input, CompressionMode.Decompress))
using (var output = new MemoryStream())
{
gzip.CopyTo(output);
return output.ToArray();
}
}
private bool IsCompressed(byte[] data)
{
// GZip signature: 0x1F 0x8B
return data != null && data.Length >= 2 && data[0] == 0x1F && data[1] == 0x8B;
}
}
}