Skip to content

Commit

Permalink
Fix CRC16 regression (#303)
Browse files Browse the repository at this point in the history
* Non-byte sized RVA statics are only supported from .NET 7 onwards.
  • Loading branch information
PaulusParssinen committed Apr 22, 2024
1 parent 03611e1 commit 716cfb8
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion libs/common/NumUtils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,11 @@ internal static unsafe int IndexOfByte(byte* src, byte value, int index, int cou
/// This table is based on the CRC-16-CCITT polynomial (0x1021)
/// </summary>
#pragma warning disable IDE0300 // Simplify collection initialization. Ignored to avoid dotnet-format bug, see https://github.com/dotnet/sdk/issues/39898
#if NET7_0_OR_GREATER
private static ReadOnlySpan<ushort> Crc16Table => new ushort[256]
#else
private static readonly ushort[] Crc16Table = new ushort[256]
#endif
{
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
Expand Down Expand Up @@ -476,11 +480,17 @@ internal static unsafe int IndexOfByte(byte* src, byte value, int index, int cou
public static unsafe ushort CRC16(byte* data, int len)
{
ushort result = 0;

#if NET7_0_OR_GREATER
ref var crc16Base = ref MemoryMarshal.GetReference(Crc16Table);
#else
ref var crc16Base = ref MemoryMarshal.GetArrayDataReference(Crc16Table);
#endif
byte* end = data + len;
while (data < end)
{
nuint index = (nuint)(uint)((result >> 8) ^ *data++) & 0xff;
result = (ushort)(Unsafe.Add(ref MemoryMarshal.GetReference(Crc16Table), index) ^ (result << 8));
result = (ushort)(Unsafe.Add(ref crc16Base, index) ^ (result << 8));
}
return result;
}
Expand Down

0 comments on commit 716cfb8

Please sign in to comment.