namespace VRio.Core.Protocol;

/// <summary>
/// The RIO packet checksum: the low 7 bits of the sum of the low 7 bits of
/// every byte in the command+payload (the checksum byte itself excluded).
/// Same algorithm as RIOJoy / the legacy firmware (riojoy/docs/PROTOCOL.md §2).
/// </summary>
public static class RioChecksum
{
    /// <summary>
    /// Compute the 7-bit checksum over <paramref name="commandAndPayload"/>
    /// (the command byte followed by its payload bytes — not the checksum byte).
    /// </summary>
    public static byte Compute(ReadOnlySpan<byte> commandAndPayload)
    {
        byte sum = 0;
        foreach (byte b in commandAndPayload)
            sum += (byte)(b & 0x7F);

        return (byte)(sum & 0x7F);
    }
}
