Skip to content

Commit 4bf6fcf

Browse files
committed
Add utility extensions for compressing and encoding payloads
1 parent b32fd7a commit 4bf6fcf

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
using System;
2+
using System.IO;
3+
using System.IO.Compression;
4+
using System.Text;
5+
using Newtonsoft.Json;
6+
7+
namespace InEngine.Core
8+
{
9+
public static class CommandExtensions
10+
{
11+
public static string EncodeCommend(this ICommand command)
12+
{
13+
return Convert.ToBase64String(JsonConvert.SerializeObject(command).Compress());
14+
}
15+
16+
public static ICommand DecodeCommand(this string encodedCommand, Type type)
17+
{
18+
var decoded = Convert.FromBase64String(encodedCommand);
19+
var uncompressed = decoded.Decompress();
20+
return JsonConvert.DeserializeObject(uncompressed, type) as ICommand;
21+
}
22+
23+
public static byte[] Compress(this string str)
24+
{
25+
var bytes = Encoding.UTF8.GetBytes(str);
26+
27+
using (var msi = new MemoryStream(bytes))
28+
using (var mso = new MemoryStream())
29+
{
30+
using (var gs = new GZipStream(mso, CompressionMode.Compress))
31+
{
32+
StreamCopy.FromTo(msi, gs);
33+
}
34+
return mso.ToArray();
35+
}
36+
}
37+
38+
public static string Decompress(this byte[] bytes)
39+
{
40+
using (var msi = new MemoryStream(bytes))
41+
using (var mso = new MemoryStream())
42+
{
43+
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
44+
{
45+
StreamCopy.FromTo(gs, mso);
46+
}
47+
return Encoding.UTF8.GetString(mso.ToArray());
48+
}
49+
}
50+
}
51+
}

src/InEngine.Core/StreamCopy.cs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System;
2+
using System.IO;
3+
using System.IO.Compression;
4+
using System.Text;
5+
6+
namespace InEngine.Core
7+
{
8+
public class StreamCopy
9+
{
10+
public static void FromTo(Stream src, Stream dest)
11+
{
12+
byte[] bytes = new byte[4096];
13+
14+
int cnt;
15+
16+
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0)
17+
{
18+
dest.Write(bytes, 0, cnt);
19+
}
20+
}
21+
}
22+
}

0 commit comments

Comments
 (0)