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

namespace Framework.Server
{
	public class CompressionHelper
	{
		private const int BUFFER_SIZE = 4096;

		/// <summary>
		/// 压缩流
		/// </summary>
		/// <param name="sourceStream">需要被压缩的流</param>
		/// <returns>压缩后的流</returns>
		public static Stream GetCompressedStream(Stream inputStream)
		{
			Stream stream = new MemoryStream();
			using (GZipStream output = new GZipStream(stream, CompressionMode.Compress, true))
			{
				int read;
				byte[] buffer = new byte[BUFFER_SIZE];

				while ((read = inputStream.Read(buffer, 0, BUFFER_SIZE)) > 0)
				{
					output.Write(buffer, 0, read);
				}
			}
			stream.Seek(0, SeekOrigin.Begin);
			return stream;
		}
		/// <summary>
		/// 解压缩流
		/// </summary>
		/// <param name="sourceStream">需要被解压缩的流</param>
		/// <returns>解压后的流</returns>
		public static Stream GetUncompressedStream(Stream inputStream)
		{
			Stream stream = new MemoryStream();
			using (GZipStream output = new GZipStream(inputStream, CompressionMode.Decompress, true))
			{
				int read;
				byte[] buffer = new byte[BUFFER_SIZE];

				while ((read = output.Read(buffer, 0, BUFFER_SIZE)) > 0)
				{
					stream.Write(buffer, 0, read);
				}
			}

			// Rewind the response stream.
			stream.Seek(0, SeekOrigin.Begin);
			return stream;
		}

		public static void CopyStream2(System.IO.Stream input, System.IO.Stream output)
		{
			byte[] buffer = new byte[2000];
			int len;
			while ((len = input.Read(buffer, 0, 2000)) > 0)
			{
				output.Write(buffer, 0, len);
			}
			output.Flush();
		}

	}
}
