Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor improvement on the dataLength % 3. #114

Merged
merged 8 commits into from
Mar 17, 2020
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,32 @@ private static int GetNumBase64PaddingCharsAddedByEncode(int dataLength)
// 0 -> 0
// 1 -> 2
// 2 -> 1
int mod3 = FastMod3(dataLength);
return mod3 == 0 ? 0 : (3 - mod3);
}
//---------------------------------------------------------------------
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int FastMod3(int value)
gfoidl marked this conversation as resolved.
Show resolved Hide resolved
gfoidl marked this conversation as resolved.
Show resolved Hide resolved
{
if (Environment.Is64BitProcess)
{
// We use modified Daniel Lemire's fastmod algorithm (https://github.com/dotnet/runtime/pull/406),
// which allows to avoid the long multiplication if the divisor is less than 2**31.
Debug.Assert(value <= int.MaxValue);
gfoidl marked this conversation as resolved.
Show resolved Hide resolved

ulong lowbits = (ulong.MaxValue / 3 + 1) * (uint)value;

return dataLength % 3 == 0 ? 0 : 3 - dataLength % 3;
// 64bit * 64bit => 128bit isn't currently supported by Math https://github.com/dotnet/runtime/issues/31184
// otherwise we'd want this to be (uint)Math.BigMul(lowbits, divisor, out _)
uint highbits = (uint)((((lowbits >> 32) + 1) * 3) >> 32);

Debug.Assert(highbits == value % 3);
return (int)highbits;
}
else
{
return value % 3;
}
}
//---------------------------------------------------------------------
// internal because tests use this map too
Expand Down