namespace ZelWiki.Security
{
    /// <summary>
    /// 
    /// </summary>
    public class Crc32
    {
        #region

        /// <summary>
        /// 逆CRC32算法的生成多项式（模2）
        /// </summary>
        private const UInt32 s_generator = 0xEDB88320;

        #endregion

        #region

        /// <summary>
        /// 创建Crc32类的新实例
        /// </summary>
        public Crc32()
        {
            m_checksumTable = Enumerable.Range(0, 256).Select(i =>
            {
                var tableEntry = (uint)i;
                for (var j = 0; j < 8; ++j)
                {
                    tableEntry = ((tableEntry & 1) != 0)
                        ? (s_generator ^ (tableEntry >> 1))
                        : (tableEntry >> 1);
                }

                return tableEntry;
            }).ToArray();
        }

        #endregion

        #region 

        /// <summary>
        /// 计算字节流的校验和
        /// </summary>
        /// <param name="byteStream"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public UInt32 Get<T>(IEnumerable<T> byteStream)
        {
            try
            {
                return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) =>
                    (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^
                     (checksumRegister >> 8)));
            }
            catch (FormatException e)
            {
                throw new Exception("无法以字节形式读取流", e);
            }
            catch (InvalidCastException e)
            {
                throw new Exception("无法以字节形式读取流", e);
            }
            catch (OverflowException e)
            {
                throw new Exception("无法以字节形式读取流", e);
            }
        }

        #endregion

        #region 

        /// <summary>
        /// 包含计算校验和块的缓存
        /// </summary>
        private readonly UInt32[] m_checksumTable;

        #endregion
    }
}