-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompressor.cs
More file actions
62 lines (55 loc) · 1.9 KB
/
Compressor.cs
File metadata and controls
62 lines (55 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System;
using System.Data.Common;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace LinkableDiff
{
internal static class Compressor
{
private static readonly char[] s_padding = { '=' };
public static string Compress(string version1, string version2)
{
var separator = (char)7;
return Compress(version1 + separator + version2);
static string Compress(string input)
{
using var ms = new MemoryStream();
using (var compressor = new DeflateStream(ms, CompressionLevel.Optimal))
{
var inputBytes = Encoding.Unicode.GetBytes(input);
compressor.Write(inputBytes);
}
return ToBase64(ms.ToArray());
}
}
private static string ToBase64(byte[] input)
=> Convert.ToBase64String(input).TrimEnd(s_padding).Replace('+', '-').Replace('/', '_');
private static byte[] FromBase64(string input)
=> Convert.FromBase64String(input.Replace('_', '/').Replace('-', '+') +
(input.Length % 4) switch
{
0 => "",
2 => "==",
3 => "=",
_ => throw new ArgumentException()
});
public static string Uncompress(string slug)
{
try
{
var bytes = FromBase64(slug);
using var ms = new MemoryStream(bytes);
using (var compressor = new DeflateStream(ms, CompressionMode.Decompress))
using (var sr = new StreamReader(compressor, Encoding.Unicode))
{
return sr.ReadToEnd();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
}
}