//http://sb2extensions.codeplex.com/
//Apache License 2.0 (Apache)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;
namespace Sb2.Extensions
{
public static class CompressionExtensions
{
///
/// Compresses the specified data.
///
/// The data.
///
public static byte[] Compress(this byte[] data)
{
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream def = new DeflateStream(output, CompressionMode.Compress))
{
def.Write(data, 0, data.Length);
}
return output.ToArray();
}
}
///
/// Decompresses the specified data.
///
/// The data.
///
public static byte[] Decompress(this byte[] data)
{
using (MemoryStream input = new MemoryStream())
{
input.Write(data, 0, data.Length);
input.Position = 0;
using (DeflateStream def = new DeflateStream(input, CompressionMode.Decompress))
{
using (MemoryStream output = new MemoryStream())
{
byte[] buff = new byte[64];
int read = -1;
read = def.Read(buff, 0, buff.Length);
while (read > 0)
{
output.Write(buff, 0, read);
read = def.Read(buff, 0, buff.Length);
}
def.Close();
return output.ToArray();
}
}
}
}
///
/// Compresses the specified data.
///
///
/// The data.
///
public static byte[] Compress(this T data)
{
byte[] result = null;
using (MemoryStream ms = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(ms, data);
result = Compress(ms.ToArray());
}
return result;
}
///
/// Decompresses the specified compressed data.
///
///
/// The compressed data.
///
public static T Decompress(this byte[] compressedData) where T : class
{
T result = null;
var formatter = new BinaryFormatter();
byte[] decompressed = Decompress(compressedData);
using (MemoryStream ms = new MemoryStream(decompressed))
{
result = formatter.Deserialize(ms) as T;
}
return result;
}
}
}