Skip to content

Commit

Permalink
Improve: optimize NextLong
Browse files Browse the repository at this point in the history
  • Loading branch information
AnnulusGames committed Aug 19, 2024
1 parent 114fed5 commit 1e064a7
Showing 1 changed file with 16 additions and 31 deletions.
47 changes: 16 additions & 31 deletions src/RandomExtensions/RandomEx.Next.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,20 @@ public static ulong NextULong(this IRandom random, ulong max)
return random.NextUInt((uint)max);
}

return random.NextULong() % (max + 1);
if (max > 1)
{
int bits = Log2Ceiling(max);
while (true)
{
ulong result = random.NextULong() >> (sizeof(ulong) * 8 - bits);
if (result < max)
{
return result;
}
}
}

return 0;
}

/// <summary>
Expand Down Expand Up @@ -113,15 +126,7 @@ public static long NextLong(this IRandom random, long max)

if (max > 1)
{
int bits = Log2Ceiling((ulong)max);
while (true)
{
ulong result = random.NextULong() >> (sizeof(ulong) * 8 - bits);
if (result < (ulong)max)
{
return (long)result;
}
}
return (long)random.NextULong();
}

return 0;
Expand All @@ -132,27 +137,7 @@ public static long NextLong(this IRandom random, long max)
/// </summary>
public static long NextLong(this IRandom random, long min, long max)
{
ulong range = (ulong)(max - min);

if (range <= int.MaxValue)
{
return NextInt(random, (int)range) + min;
}

if (range > 1)
{
int bits = Log2Ceiling(range);
while (true)
{
ulong result = random.NextULong() >> (sizeof(ulong) * 8 - bits);
if (result < range)
{
return (long)result + min;
}
}
}

return min;
return NextLong(random, max - min) + min;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
Expand Down

0 comments on commit 1e064a7

Please sign in to comment.