34 lines
835 B
C#
34 lines
835 B
C#
|
|
namespace StitchATon2.Infra.Encoders;
|
||
|
|
|
||
|
|
public static class Crc32
|
||
|
|
{
|
||
|
|
private static readonly Lazy<uint[]> LazyTable = new(GenerateTable);
|
||
|
|
private static uint[] Table => LazyTable.Value;
|
||
|
|
|
||
|
|
public static uint Compute(Span<byte> buffer, uint initial = 0xFFFFFFFF)
|
||
|
|
{
|
||
|
|
uint crc = initial;
|
||
|
|
foreach (var b in buffer)
|
||
|
|
{
|
||
|
|
crc = Table[(crc ^ b) & 0xFF] ^ (crc >> 8);
|
||
|
|
}
|
||
|
|
return ~crc;
|
||
|
|
}
|
||
|
|
|
||
|
|
private static uint[] GenerateTable()
|
||
|
|
{
|
||
|
|
const uint poly = 0xEDB88320;
|
||
|
|
var table = new uint[256];
|
||
|
|
for (uint i = 0; i < 256; i++)
|
||
|
|
{
|
||
|
|
uint c = i;
|
||
|
|
for (int j = 0; j < 8; j++)
|
||
|
|
{
|
||
|
|
c = (c & 1) != 0 ? (poly ^ (c >> 1)) : (c >> 1);
|
||
|
|
}
|
||
|
|
table[i] = c;
|
||
|
|
}
|
||
|
|
return table;
|
||
|
|
}
|
||
|
|
}
|