using System.IO;
using System.IO.Compression;
using System.Text;

namespace QC.QTMInterface.Compression;

public static class Compression
{
	public static byte[] Zip(this byte[] bytes)
	{
		using MemoryStream src = new MemoryStream(bytes);
		using MemoryStream memoryStream = new MemoryStream();
		using (GZipStream dest = new GZipStream(memoryStream, CompressionMode.Compress))
		{
			CopyTo(src, dest);
		}
		return memoryStream.ToArray();
	}

	public static byte[] Unzip(this byte[] bytes)
	{
		using MemoryStream stream = new MemoryStream(bytes);
		using MemoryStream memoryStream = new MemoryStream();
		using (GZipStream src = new GZipStream(stream, CompressionMode.Decompress))
		{
			CopyTo(src, memoryStream);
		}
		return memoryStream.ToArray();
	}

	public static string UnzipToString(this byte[] bytes)
	{
		if (bytes == null)
		{
			return string.Empty;
		}
		byte[] bytes2 = bytes.Unzip();
		return Encoding.Default.GetString(bytes2);
	}

	public static byte[] ZipString(this string text)
	{
		if (text == null)
		{
			text = string.Empty;
		}
		byte[] bytes = Encoding.Default.GetBytes(text);
		return bytes.Zip();
	}

	private static void CopyTo(Stream src, Stream dest)
	{
		byte[] array = new byte[4096];
		int count;
		while ((count = src.Read(array, 0, array.Length)) != 0)
		{
			dest.Write(array, 0, count);
		}
	}
}
