diff --git a/src/Polyfill/Polyfill_Random.cs b/src/Polyfill/Polyfill_Random.cs index 6860f08a..6bbb640b 100644 --- a/src/Polyfill/Polyfill_Random.cs +++ b/src/Polyfill/Polyfill_Random.cs @@ -80,6 +80,9 @@ public static T[] GetItems( #if !NET6_0_OR_GREATER + [ThreadStatic] + static byte[]? randomNextInt64Buffer; + /// /// Returns a non-negative random integer. /// @@ -113,11 +116,14 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + + // One buffer per thread rather than one per attempt. It is still filled by NextBytes(byte[]), + // so the values drawn from the generator are the same. + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); @@ -221,6 +227,9 @@ public static string GetString(this Random target, ReadOnlySpan choices, i #if !NETCOREAPP2_1_OR_GREATER && !NETSTANDARD2_1_OR_GREATER && FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; + /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -229,9 +238,31 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + // A derived type may fill an array in a way of its own, so it gets one array the size of the span + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + + // Random.NextBytes(byte[]) sets each byte to the low 8 bits of the next sample, which is what + // Next() % 256 is. So filling in chunks, and the rest one byte at a time, gives the same bytes + // and leaves the generator in the same state as filling one array the size of the span. + var chunk = randomNextBytesBuffer ??= new byte[256]; + + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif diff --git a/src/Split/net461/Polyfill_Random.cs b/src/Split/net461/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net461/Polyfill_Random.cs +++ b/src/Split/net461/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net462/Polyfill_Random.cs b/src/Split/net462/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net462/Polyfill_Random.cs +++ b/src/Split/net462/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net47/Polyfill_Random.cs b/src/Split/net47/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net47/Polyfill_Random.cs +++ b/src/Split/net47/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net471/Polyfill_Random.cs b/src/Split/net471/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net471/Polyfill_Random.cs +++ b/src/Split/net471/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net472/Polyfill_Random.cs b/src/Split/net472/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net472/Polyfill_Random.cs +++ b/src/Split/net472/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net48/Polyfill_Random.cs b/src/Split/net48/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net48/Polyfill_Random.cs +++ b/src/Split/net48/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net481/Polyfill_Random.cs b/src/Split/net481/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/net481/Polyfill_Random.cs +++ b/src/Split/net481/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/net5.0/Polyfill_Random.cs b/src/Split/net5.0/Polyfill_Random.cs index 4b3785c7..1f1f29cf 100644 --- a/src/Split/net5.0/Polyfill_Random.cs +++ b/src/Split/net5.0/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } diff --git a/src/Split/netcoreapp2.0/Polyfill_Random.cs b/src/Split/netcoreapp2.0/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/netcoreapp2.0/Polyfill_Random.cs +++ b/src/Split/netcoreapp2.0/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/netcoreapp2.1/Polyfill_Random.cs b/src/Split/netcoreapp2.1/Polyfill_Random.cs index 4b3785c7..1f1f29cf 100644 --- a/src/Split/netcoreapp2.1/Polyfill_Random.cs +++ b/src/Split/netcoreapp2.1/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } diff --git a/src/Split/netcoreapp2.2/Polyfill_Random.cs b/src/Split/netcoreapp2.2/Polyfill_Random.cs index 4b3785c7..1f1f29cf 100644 --- a/src/Split/netcoreapp2.2/Polyfill_Random.cs +++ b/src/Split/netcoreapp2.2/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } diff --git a/src/Split/netcoreapp3.0/Polyfill_Random.cs b/src/Split/netcoreapp3.0/Polyfill_Random.cs index 4b3785c7..1f1f29cf 100644 --- a/src/Split/netcoreapp3.0/Polyfill_Random.cs +++ b/src/Split/netcoreapp3.0/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } diff --git a/src/Split/netcoreapp3.1/Polyfill_Random.cs b/src/Split/netcoreapp3.1/Polyfill_Random.cs index 4b3785c7..1f1f29cf 100644 --- a/src/Split/netcoreapp3.1/Polyfill_Random.cs +++ b/src/Split/netcoreapp3.1/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } diff --git a/src/Split/netstandard2.0/Polyfill_Random.cs b/src/Split/netstandard2.0/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/netstandard2.0/Polyfill_Random.cs +++ b/src/Split/netstandard2.0/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Split/netstandard2.1/Polyfill_Random.cs b/src/Split/netstandard2.1/Polyfill_Random.cs index 4b3785c7..1f1f29cf 100644 --- a/src/Split/netstandard2.1/Polyfill_Random.cs +++ b/src/Split/netstandard2.1/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } diff --git a/src/Split/uap10.0/Polyfill_Random.cs b/src/Split/uap10.0/Polyfill_Random.cs index d78c799c..9a250b2b 100644 --- a/src/Split/uap10.0/Polyfill_Random.cs +++ b/src/Split/uap10.0/Polyfill_Random.cs @@ -61,6 +61,8 @@ public static T[] GetItems( } return result; } + [ThreadStatic] + static byte[]? randomNextInt64Buffer; /// /// Returns a non-negative random integer. /// @@ -87,11 +89,11 @@ public static long NextInt64(this Random target, long minValue, long maxValue) var range = unchecked((ulong)(maxValue - minValue)); var limit = ulong.MaxValue - ulong.MaxValue % range; ulong result; + var buffer = randomNextInt64Buffer ??= new byte[8]; do { - var buf = new byte[8]; - target.NextBytes(buf); - result = BitConverter.ToUInt64(buf, 0); + target.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); } while (result >= limit); return unchecked((long)(result % range) + minValue); } @@ -168,6 +170,8 @@ public static string GetString(this Random target, ReadOnlySpan choices, i } #endif #if FeatureMemory + [ThreadStatic] + static byte[]? randomNextBytesBuffer; /// /// Fills the elements of a specified span of bytes with random numbers. /// @@ -175,9 +179,24 @@ public static void NextBytes( this Random target, Span buffer) { - var array = new byte[buffer.Length]; - target.NextBytes(array); - array.CopyTo(buffer); + if (target.GetType() != typeof(Random)) + { + var array = new byte[buffer.Length]; + target.NextBytes(array); + array.CopyTo(buffer); + return; + } + var chunk = randomNextBytesBuffer ??= new byte[256]; + while (buffer.Length >= chunk.Length) + { + target.NextBytes(chunk); + chunk.CopyTo(buffer); + buffer = buffer.Slice(chunk.Length); + } + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = (byte) (target.Next() % 256); + } } #endif /// diff --git a/src/Tests/PolyfillTests_Random.cs b/src/Tests/PolyfillTests_Random.cs index 9df25141..b80b6c79 100644 --- a/src/Tests/PolyfillTests_Random.cs +++ b/src/Tests/PolyfillTests_Random.cs @@ -227,4 +227,236 @@ public async Task RandomNextInt64_FullRange() await Assert.That(result).IsLessThan(long.MaxValue); } } + + // NextInt64 is part of Random from net6, with an algorithm of its own + static readonly bool randomNextInt64IsPolyfill = typeof(Random).GetMethod("NextInt64", Type.EmptyTypes) == null; + + // What the NextInt64 polyfill has always returned: unbiased rejection sampling over 8 bytes from NextBytes + static long ReferenceNextInt64(Random random, long minValue, long maxValue) + { + if (minValue == maxValue) + { + return minValue; + } + + var range = unchecked((ulong) (maxValue - minValue)); + var limit = ulong.MaxValue - ulong.MaxValue % range; + var buffer = new byte[8]; + ulong result; + do + { + random.NextBytes(buffer); + result = BitConverter.ToUInt64(buffer, 0); + } while (result >= limit); + + return unchecked((long) (result % range) + minValue); + } + + [Test] + public async Task RandomNextInt64_Seeded_SameSequence() + { + var failures = new List(); + var ranges = new (long min, long max)[] + { + (0, 1), + (0, 3), + (0, 1000), + (-5, 5), + (0, long.MaxValue), + (long.MinValue, long.MaxValue), + (long.MinValue, 0), + (-5, long.MaxValue / 2 + 7), + // more than half of all values are rejected + (long.MinValue, 1), + (7, 7) + }; + + foreach (var (min, max) in ranges) + { + var random = new Random(1234); + var reference = new Random(1234); + + for (var i = 0; i < 200; i++) + { + var value = random.NextInt64(min, max); + + if (value < min || (value >= max && min != max)) + { + failures.Add($"{value} is outside of {min}..{max}"); + } + + if (randomNextInt64IsPolyfill && value != ReferenceNextInt64(reference, min, max)) + { + failures.Add($"{value} is not the next value for {min}..{max}"); + } + } + + // the generator is left in the same state + if (randomNextInt64IsPolyfill && random.Next() != reference.Next()) + { + failures.Add($"state after {min}..{max}"); + } + } + + await Assert.That(failures).IsEmpty(); + } + + [Test] + public async Task RandomNextInt64_Overloads_SameSequence() + { + var random = new Random(99); + var reference = new Random(99); + var first = random.NextInt64(); + var second = random.NextInt64(1000); + + await Assert.That(first).IsGreaterThanOrEqualTo(0); + await Assert.That(second).IsGreaterThanOrEqualTo(0); + await Assert.That(second).IsLessThan(1000); + + if (randomNextInt64IsPolyfill) + { + await Assert.That(first).IsEqualTo(ReferenceNextInt64(reference, 0, long.MaxValue)); + await Assert.That(second).IsEqualTo(ReferenceNextInt64(reference, 0, 1000)); + } + } + + [Test] + public async Task RandomNextInt64_Invalid_Throws() + { + var random = new Random(1); + await Assert.That(() => random.NextInt64(5, 4)).Throws(); + await Assert.That(random.NextInt64(5, 5)).IsEqualTo(5); + } + + [Test] + public async Task RandomNextInt64_CoversSmallRange() + { + var random = new Random(5); + var counts = new int[5]; + for (var i = 0; i < 5000; i++) + { + counts[random.NextInt64(10, 15) - 10]++; + } + + // 1000 expected for each, with a standard deviation of 28 + await Assert.That(counts.All(_ => _ is > 800 and < 1200)).IsTrue(); + } + + [Test] + public async Task RandomNextInt64_Concurrent_SameSequences() + { + // each thread has a generator of its own, and must get the sequence it would get alone + var expected = new long[200]; + var single = new Random(77); + for (var i = 0; i < expected.Length; i++) + { + expected[i] = single.NextInt64(-1000, long.MaxValue / 3); + } + + var tasks = new List>(); + for (var t = 0; t < 8; t++) + { + tasks.Add(Task.Run(() => + { + for (var round = 0; round < 50; round++) + { + var random = new Random(77); + for (var i = 0; i < expected.Length; i++) + { + if (random.NextInt64(-1000, long.MaxValue / 3) != expected[i]) + { + return false; + } + } + } + + return true; + })); + } + + var results = await Task.WhenAll(tasks); + await Assert.That(results.All(_ => _)).IsTrue(); + } + +#if FeatureMemory + + // NextBytes(Span) is part of Random from netcoreapp2.1, where it does not go through NextBytes(byte[]) + static readonly bool randomNextBytesSpanIsPolyfill = typeof(Random).GetMethod("NextBytes", [typeof(Span)]) == null; + + [Test] + [Arguments(0)] + [Arguments(1)] + [Arguments(7)] + [Arguments(255)] + [Arguments(256)] + [Arguments(257)] + [Arguments(512)] + [Arguments(1000)] + [Arguments(100_000)] + public async Task RandomNextBytesSpan_Seeded_SameAsArray(int length) + { + var random = new Random(4321); + var reference = new Random(4321); + + // a margin either side, to check nothing outside the span is written + var buffer = new byte[length + 16]; + random.NextBytes(buffer.AsSpan(8, length)); + var expected = new byte[length]; + reference.NextBytes(expected); + + await Assert.That(buffer.AsSpan(8, length).SequenceEqual(expected)).IsTrue(); + await Assert.That(buffer.Take(8).All(_ => _ == 0)).IsTrue(); + await Assert.That(buffer.Skip(8 + length).All(_ => _ == 0)).IsTrue(); + + // the generator is left in the same state + await Assert.That(random.Next()).IsEqualTo(reference.Next()); + + // and a second fill carries on from there + random.NextBytes(buffer.AsSpan(8, length)); + reference.NextBytes(expected); + await Assert.That(buffer.AsSpan(8, length).SequenceEqual(expected)).IsTrue(); + } + + [Test] + public async Task RandomNextBytesSpan_Unseeded_Fills() + { + var random = new Random(); + var buffer = new byte[1000]; + random.NextBytes(buffer.AsSpan()); + await Assert.That(buffer.Distinct().Count()).IsGreaterThan(200); + await Assert.That(buffer.Skip(900).Any(_ => _ != 0)).IsTrue(); + } + + [Test] + public async Task RandomNextBytesSpan_DerivedType() + { + var random = new CountingRandom(); + var buffer = new byte[1000]; + random.NextBytes(buffer.AsSpan()); + + if (randomNextBytesSpanIsPolyfill) + { + // a derived type still gets a single call for the whole of the span + await Assert.That(random.ArrayCalls).IsEqualTo(1); + await Assert.That(buffer.All(_ => _ == 42)).IsTrue(); + } + } + + [ExcludeFromCodeCoverage] + [System.Diagnostics.DebuggerNonUserCode] + class CountingRandom : Random + { + public int ArrayCalls; + + public override void NextBytes(byte[] buffer) + { + ArrayCalls++; + for (var i = 0; i < buffer.Length; i++) + { + buffer[i] = 42; + } + } + } + +#endif }