using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Text;

namespace ChuPiao.Common.Utils
{
    /// <summary>
    /// GZip压缩、解压工具类
    /// </summary>
    public class GZipUtil
    {
        /// <summary> 
        /// 对byte数组进行压缩 
        /// </summary> 
        /// <param name="data">待压缩的byte数组</param> 
        /// <returns>压缩后的byte数组</returns> 
        public static byte[] Compress(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (GZipStream zip=new GZipStream(ms ,CompressionMode.Compress,true))
                {
                    zip.Write(data,0,data.Length);
                    zip.Close();
                    byte[] buffer = new byte[ms.Length];
                    ms.Position = 0;
                    ms.Read(buffer, 0, buffer.Length);
                    ms.Close();
                    return buffer;
                }
            }
        }
        /// <summary>
        /// 对byte数组进行解压缩 
        /// </summary>
        /// <param name="data">压缩后的byte数组</param>
        /// <returns>解压后的byte数组</returns>
        public static byte[] Decompress(byte[] data)
        {
            using (MemoryStream ms = new MemoryStream(data))
            {
                using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true))
                {
                    using(MemoryStream msreader = new MemoryStream())
                    {

                        byte[] buffer = new byte[4096];
                        while (true)
                        {
                            int reader = zip.Read(buffer, 0, buffer.Length);
                            if (reader <= 0)
                            {
                                break;
                            }
                            msreader.Write(buffer, 0, reader);
                        }
                        zip.Close();
                        ms.Close();
                        msreader.Position = 0;
                        buffer = msreader.ToArray();
                        msreader.Close();
                        return buffer;
                    }
                }
            }
        }
    }
}
