namespace DbaMessageInserter;

internal static class Crc32
{
    private static readonly uint[] Table = BuildTable();

    public static uint Compute(ReadOnlySpan<byte> data)
    {
        uint crc = 0xFFFF_FFFFu;

        foreach (byte value in data)
        {
            int tableIndex = (int)((crc ^ value) & 0xFFu);
            crc = Table[tableIndex] ^ (crc >> 8);
        }

        return ~crc;
    }

    private static uint[] BuildTable()
    {
        var table = new uint[256];

        for (int i = 0; i < table.Length; i++)
        {
            uint value = (uint)i;

            for (int bit = 0; bit < 8; bit++)
            {
                value = (value & 1u) != 0
                    ? 0xEDB8_8320u ^ (value >> 1)
                    : value >> 1;
            }

            table[i] = value;
        }

        return table;
    }
}
