namespace StitchATon2.Infra.Encoders; public static class Crc32 { private static readonly Lazy LazyTable = new(GenerateTable); private static uint[] Table => LazyTable.Value; public static uint Compute(Span buffer, uint initial = 0xFFFFFFFF) { uint crc = initial; foreach (var b in buffer) { crc = Table[(crc ^ b) & 0xFF] ^ (crc >> 8); } return ~crc; } public static uint Compute(Stream stream, int count, uint initial = 0xFFFFFFFF) { uint crc = initial; while (count-- > 0) { crc = Table[(crc ^ stream.ReadByte()) & 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; } }