Skip to content

Commit

Permalink
Simplify Random for ulong (#87219)
Browse files Browse the repository at this point in the history
Use Math.BigMul instead of UInt128 since both values are always ulongs.
  • Loading branch information
MichalPetryka authored Jun 8, 2023
1 parent c96c15c commit 5353824
Showing 1 changed file with 4 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Runtime.CompilerServices;

namespace System
Expand Down Expand Up @@ -57,21 +58,19 @@ internal static uint NextUInt32(uint maxValue, XoshiroImpl xoshiro)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static ulong NextUInt64(ulong maxValue, XoshiroImpl xoshiro)
{
UInt128 randomProduct = (UInt128)maxValue * xoshiro.NextUInt64();
ulong lowPart = (ulong)randomProduct;
ulong randomProduct = Math.BigMul(maxValue, xoshiro.NextUInt64(), out ulong lowPart);

if (lowPart < maxValue)
{
ulong remainder = (0ul - maxValue) % maxValue;

while (lowPart < remainder)
{
randomProduct = (UInt128)maxValue * xoshiro.NextUInt64();
lowPart = (ulong)randomProduct;
randomProduct = Math.BigMul(maxValue, xoshiro.NextUInt64(), out lowPart);
}
}

return (ulong)(randomProduct >> 64);
return randomProduct;
}
}
}
Expand Down

0 comments on commit 5353824

Please sign in to comment.