From 5f385e241e9cd44815e7120762bcdd35666d43ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Petryka?= <35800402+MichalPetryka@users.noreply.github.com> Date: Wed, 7 Jun 2023 18:12:47 +0200 Subject: [PATCH] Simplify Random for ulong Use Math.BigMul instead of UInt128 since both values are always ulongs. --- .../System.Private.CoreLib/src/System/Random.ImplBase.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/libraries/System.Private.CoreLib/src/System/Random.ImplBase.cs b/src/libraries/System.Private.CoreLib/src/System/Random.ImplBase.cs index 6bd1b8a1ac943b..c7857b156262df 100644 --- a/src/libraries/System.Private.CoreLib/src/System/Random.ImplBase.cs +++ b/src/libraries/System.Private.CoreLib/src/System/Random.ImplBase.cs @@ -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 @@ -57,8 +58,7 @@ 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) { @@ -66,12 +66,11 @@ internal static ulong NextUInt64(ulong maxValue, XoshiroImpl xoshiro) 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; } } }