Skip to content

Commit

Permalink
Fix for old HarmonyX not having MonoMod backports.
Browse files Browse the repository at this point in the history
  • Loading branch information
CptMoore committed Dec 22, 2024
1 parent 5e89f90 commit 8d8ce6b
Showing 1 changed file with 38 additions and 2 deletions.
40 changes: 38 additions & 2 deletions ModTek/Features/Logging/FormattingHelpers.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System.Numerics;
using System.Runtime.CompilerServices;

namespace ModTek.Features.Logging;
Expand All @@ -22,7 +21,7 @@ internal static unsafe void WriteDigits(byte* positionPtr, long value, int digit
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int CountDigits(uint value)
{
var tableValue = s_countDigitsTable[(uint)BitOperations.Log2(value)];
var tableValue = s_countDigitsTable[Log2(value)];
return (int)((value + tableValue) >> 32);
}
// Algorithm based on https://lemire.me/blog/2021/06/03/computing-the-number-of-digits-of-an-integer-even-faster.
Expand Down Expand Up @@ -61,4 +60,41 @@ internal static int CountDigits(uint value)
42949672960,
42949672960,
];

// following from MonoMod.Backports
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static int Log2(uint value)
{
// The 0->0 contract is fulfilled by setting the LSB to 1.
// Log(1) is 0, and setting the LSB for values > 1 does not change the log2 result.
value |= 1;

// Fallback contract is 0->0
return Log2SoftwareFallback(value);
}
private static unsafe int Log2SoftwareFallback(uint value)
{
// No AggressiveInlining due to large method size
// Has conventional contract 0->0 (Log(0) is undefined)

// Fill trailing zeros with ones, eg 00010010 becomes 00011111
value |= value >> 01;
value |= value >> 02;
value |= value >> 04;
value |= value >> 08;
value |= value >> 16;

var offset = (value * 0x07C4ACDDu) >> 27;
fixed (byte* ptr = s_log2DeBruijn)
{
return ptr[offset];
}
}
private static readonly byte[] s_log2DeBruijn =
[
00, 09, 01, 10, 13, 21, 02, 29,
11, 14, 16, 18, 22, 25, 03, 30,
08, 12, 20, 28, 15, 17, 24, 07,
19, 27, 23, 06, 26, 05, 04, 31
];
}

0 comments on commit 8d8ce6b

Please sign in to comment.