forked from ServiceStackV3/ServiceStack.Contrib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathICSharpDeflateProvider.cs
More file actions
53 lines (45 loc) · 1.31 KB
/
Copy pathICSharpDeflateProvider.cs
File metadata and controls
53 lines (45 loc) · 1.31 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
using System;
using System.IO;
using System.Text;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ServiceStack.CacheAccess;
namespace ServiceStack.Compression
{
public class ICSharpDeflateProvider
: IDeflateProvider
{
public byte[] Deflate(string text)
{
var buffer = Encoding.UTF8.GetBytes(text);
using (var ms = new MemoryStream())
{
using (var zipStream = new DeflaterOutputStream(ms, new Deflater(9)))
{
zipStream.Write(buffer, 0, buffer.Length);
zipStream.Close();
var compressed = ms.ToArray();
var gzBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return gzBuffer;
}
}
}
public string Inflate(byte[] gzBuffer)
{
using (var ms = new MemoryStream())
{
var msgLength = BitConverter.ToInt32(gzBuffer, 0);
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
var buffer = new byte[msgLength];
ms.Position = 0;
using (var zipStream = new InflaterInputStream(ms, new Inflater()))
{
zipStream.Read(buffer, 0, buffer.Length);
}
return Encoding.UTF8.GetString(buffer);
}
}
}
}