diff --git a/src/Ulid.Tests/PseudoRandomProviderTests.cs b/src/Ulid.Tests/PseudoRandomProviderTests.cs new file mode 100644 index 0000000..b82230a --- /dev/null +++ b/src/Ulid.Tests/PseudoRandomProviderTests.cs @@ -0,0 +1,91 @@ +namespace ByteAether.Ulid.Tests; + +public class PseudoRandomProviderTests +{ + [Fact] + public void GetBytes_ShouldNotRepeatValuesWhenCalledConcurrently() + { + // Arrange + const int threadCount = 8; + const int perThread = 100_000; + var options = new Ulid.GenerationOptions + { + Monotonicity = Ulid.GenerationOptions.MonotonicityOptions.NonMonotonic, + InitialRandomSource = new PseudoRandomProvider(), + }; + var generated = new Ulid[threadCount * perThread]; + using var barrier = new Barrier(threadCount); + + // Act + // The timestamp is fixed, so only the random part can differ. Dedicated threads start together for maximum contention. + var threads = Enumerable.Range(0, threadCount) + .Select(t => new Thread(() => + { + barrier.SignalAndWait(); + for (var i = t * perThread; i < (t + 1) * perThread; i++) + { + generated[i] = Ulid.New(0, options); + } + })) + .ToArray(); + + foreach (var thread in threads) + { + thread.Start(); + } + + foreach (var thread in threads) + { + thread.Join(); + } + + // Assert + Assert.Equal(generated.Length, generated.Distinct().Count()); + } + + [Theory] + [InlineData(0)] + [InlineData(1)] + [InlineData(7)] + [InlineData(8)] + [InlineData(9)] + [InlineData(10)] + [InlineData(16)] + [InlineData(33)] + [InlineData(64)] + public void GetBytes_ShouldFillExactlyTheRequestedLength(int length) + { + // Arrange + const byte sentinel = 0xAA; + var provider = new PseudoRandomProvider(); + var buffer = new byte[length + 2]; + Array.Fill(buffer, sentinel); + + // Act + provider.GetBytes(buffer.AsSpan(1, length)); + + // Assert + Assert.Equal(sentinel, buffer[0]); + Assert.Equal(sentinel, buffer[^1]); + if (length >= 8) + { + Assert.Contains(buffer.AsSpan(1, length).ToArray(), b => b != sentinel); + } + } + + [Fact] + public void GetBytes_ShouldProduceDifferentValuesOnConsecutiveCalls() + { + // Arrange + var provider = new PseudoRandomProvider(); + var first = new byte[32]; + var second = new byte[32]; + + // Act + provider.GetBytes(first); + provider.GetBytes(second); + + // Assert + Assert.NotEqual(first, second); + } +} diff --git a/src/Ulid/PseudoRandomProvider.cs b/src/Ulid/PseudoRandomProvider.cs index 750da65..15fd685 100644 --- a/src/Ulid/PseudoRandomProvider.cs +++ b/src/Ulid/PseudoRandomProvider.cs @@ -1,12 +1,18 @@ using System.Runtime.CompilerServices; +#if !NET6_0_OR_GREATER +using System.Runtime.InteropServices; +#endif namespace ByteAether.Ulid; /// /// Provides a pseudo-random number generator implementation for the -/// interface using the shared instance -/// of . +/// interface using . /// +/// +/// This provider is thread-safe. It uses the shared instance of +/// where available, and a separate instance for each thread on older targets. +/// public readonly struct PseudoRandomProvider : IRandomProvider { #if NET6_0_OR_GREATER @@ -15,11 +21,43 @@ private static Random _rng [MethodImpl(MethodImplOptions.AggressiveInlining)] get => Random.Shared; } -#else - private static readonly Random _rng = new(); -#endif /// [MethodImpl(MethodImplOptions.AggressiveInlining)] public void GetBytes(Span buffer) => _rng.NextBytes(buffer); +#else + [ThreadStatic] + private static Random? _threadRng; + + /// + public void GetBytes(Span buffer) + { + var rng = _threadRng ?? CreateThreadRng(); +#if NETSTANDARD2_0 + // Random.NextBytes accepts only an array on this target and always fills all of it. + // Each Random.Next() call yields 31 random bits, of which 3 whole bytes are used. + for (var i = 0; i < buffer.Length;) + { + var value = rng.Next(); + for (var j = 0; j < 3 && i < buffer.Length; j++, i++, value >>= 8) + { + buffer[i] = (byte)value; + } + } +#else + rng.NextBytes(buffer); +#endif + } + + // The seed comes from the cryptographically secure source: threads started within the same clock tick would + // otherwise get the same time-dependent default seed of System.Random on .NET Framework. + [MethodImpl(MethodImplOptions.NoInlining)] + private static Random CreateThreadRng() + { + Span seed = stackalloc byte[sizeof(int)]; + new CryptographicallySecureRandomProvider().GetBytes(seed); + + return _threadRng = new(MemoryMarshal.Read(seed)); + } +#endif }