CRC.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.IO;
  3. namespace SharpCompress.Compressors.LZMA
  4. {
  5. internal static class Crc
  6. {
  7. internal const uint INIT_CRC = 0xFFFFFFFF;
  8. internal static readonly uint[] TABLE = new uint[4 * 256];
  9. static Crc()
  10. {
  11. const uint kCrcPoly = 0xEDB88320;
  12. for (uint i = 0; i < 256; i++)
  13. {
  14. uint r = i;
  15. for (int j = 0; j < 8; j++)
  16. {
  17. r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1));
  18. }
  19. TABLE[i] = r;
  20. }
  21. for (uint i = 256; i < TABLE.Length; i++)
  22. {
  23. uint r = TABLE[i - 256];
  24. TABLE[i] = TABLE[r & 0xFF] ^ (r >> 8);
  25. }
  26. }
  27. public static uint From(Stream stream, long length)
  28. {
  29. uint crc = INIT_CRC;
  30. byte[] buffer = new byte[Math.Min(length, 4 << 10)];
  31. while (length > 0)
  32. {
  33. int delta = stream.Read(buffer, 0, (int)Math.Min(length, buffer.Length));
  34. if (delta == 0)
  35. {
  36. throw new EndOfStreamException();
  37. }
  38. crc = Update(crc, buffer, 0, delta);
  39. length -= delta;
  40. }
  41. return Finish(crc);
  42. }
  43. public static uint Finish(uint crc)
  44. {
  45. return ~crc;
  46. }
  47. public static uint Update(uint crc, byte bt)
  48. {
  49. return TABLE[(crc & 0xFF) ^ bt] ^ (crc >> 8);
  50. }
  51. public static uint Update(uint crc, uint value)
  52. {
  53. crc ^= value;
  54. return TABLE[0x300 + (crc & 0xFF)]
  55. ^ TABLE[0x200 + ((crc >> 8) & 0xFF)]
  56. ^ TABLE[0x100 + ((crc >> 16) & 0xFF)]
  57. ^ TABLE[0x000 + (crc >> 24)];
  58. }
  59. public static uint Update(uint crc, ulong value)
  60. {
  61. return Update(Update(crc, (uint)value), (uint)(value >> 32));
  62. }
  63. public static uint Update(uint crc, long value)
  64. {
  65. return Update(crc, (ulong)value);
  66. }
  67. public static uint Update(uint crc, byte[] buffer, int offset, int length)
  68. {
  69. for (int i = 0; i < length; i++)
  70. {
  71. crc = Update(crc, buffer[offset + i]);
  72. }
  73. return crc;
  74. }
  75. }
  76. }