Created
September 26, 2022 01:38
-
-
Save israellot/e4cd8737bfe051a81bd1071f33bd04d5 to your computer and use it in GitHub Desktop.
Expert Checksum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public unsafe static uint ChecksumExpert(ReadOnlySpan<byte> arr) | |
{ | |
if (arr.Length == 0) return 0; | |
fixed (byte* ptr = arr) | |
{ | |
uint sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0; | |
uint z = 0; | |
int rem = arr.Length % 32; | |
ulong tmp0 = 0, tmp1 = 0; | |
int limit2 = 64; | |
int limit = arr.Length - rem; | |
while (z < limit) | |
{ | |
ulong l1 = *(ulong*)(ptr + z); | |
ulong l2 = *(ulong*)(ptr + z + 8); | |
ulong l3 = *(ulong*)(ptr + z + 16); | |
ulong l4 = *(ulong*)(ptr + z + 24); | |
tmp0 += (l1 & 0x00ff00ff00ff00ff) + (l2 & 0x00ff00ff00ff00ff) | |
+ (l3 & 0x00ff00ff00ff00ff) + (l4 & 0x00ff00ff00ff00ff); | |
tmp1 += ((l1 & 0xff00ff00ff00ff00) >> 8) + ((l2 & 0xff00ff00ff00ff00) >> 8) | |
+ ((l3 & 0xff00ff00ff00ff00) >> 8) + ((l4 & 0xff00ff00ff00ff00) >> 8); | |
limit2--; | |
z += 32; | |
if (limit2 == 0) | |
{ | |
sum0 += (uint)(tmp0 & 0xffff) + (uint)((tmp0 & 0x0000ffff00000000) >> 32); | |
sum1 += (uint)(tmp1 & 0xffff) + (uint)((tmp1 & 0x0000ffff00000000) >> 32); | |
sum2 += (uint)((tmp0 & 0xffff0000) >> 16) + (uint)(tmp0 >> 48); | |
sum3 += (uint)((tmp1 & 0xffff0000) >> 16) + (uint)(tmp1 >> 48); | |
tmp0 = 0; tmp1 = 0; limit2 = 64; | |
} | |
} | |
if (limit2 != 64) | |
{ | |
sum0 += (uint)(tmp0 & 0xffff) + (uint)((tmp0 & 0x0000ffff00000000) >> 32); | |
sum1 += (uint)(tmp1 & 0xffff) + (uint)((tmp1 & 0x0000ffff00000000) >> 32); | |
sum2 += (uint)((tmp0 & 0xffff0000) >> 16) + (uint)(tmp0 >> 48); | |
sum3 += (uint)((tmp1 & 0xffff0000) >> 16) + (uint)(tmp1 >> 48); | |
} | |
limit = arr.Length - rem % 4; | |
rem = rem % 4; | |
while (z < limit) | |
{ | |
sum0 += ptr[z + 0]; | |
sum1 += ptr[z + 1]; | |
sum2 += ptr[z + 2]; | |
sum3 += ptr[z + 3]; | |
z += 4; | |
} | |
var sum = sum3 + (sum2 << 8) + (sum1 << 16) + (sum0 << 24); | |
switch (rem & 3) | |
{ | |
case 3: | |
sum += (uint)(ptr[z + 2]) << 8; | |
sum += (uint)(ptr[z + 1]) << 16; | |
sum += (uint)(ptr[z + 0]) << 24; | |
break; | |
case 2: | |
sum += (uint)(ptr[z + 1]) << 16; | |
sum += (uint)(ptr[z + 0]) << 24; | |
break; | |
case 1: | |
sum += (uint)(ptr[z + 0]) << 24; | |
break; | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment