Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions src/Ulid.Tests/PseudoRandomProviderTests.cs
Original file line number Diff line number Diff line change
@@ -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);
}
}
48 changes: 43 additions & 5 deletions src/Ulid/PseudoRandomProvider.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
using System.Runtime.CompilerServices;
#if !NET6_0_OR_GREATER
using System.Runtime.InteropServices;
#endif

namespace ByteAether.Ulid;

/// <summary>
/// Provides a pseudo-random number generator implementation for the
/// <see cref="IRandomProvider"/> interface using the shared instance
/// of <see cref="System.Random"/>.
/// <see cref="IRandomProvider"/> interface using <see cref="System.Random"/>.
/// </summary>
/// <remarks>
/// This provider is thread-safe. It uses the shared instance of <see cref="System.Random"/>
/// where available, and a separate instance for each thread on older targets.
/// </remarks>
public readonly struct PseudoRandomProvider : IRandomProvider
{
#if NET6_0_OR_GREATER
Expand All @@ -15,11 +21,43 @@ private static Random _rng
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Random.Shared;
}
#else
private static readonly Random _rng = new();
#endif

/// <inheritdoc/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GetBytes(Span<byte> buffer) => _rng.NextBytes(buffer);
#else
[ThreadStatic]
private static Random? _threadRng;

/// <inheritdoc/>
public void GetBytes(Span<byte> 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<byte> seed = stackalloc byte[sizeof(int)];
new CryptographicallySecureRandomProvider().GetBytes(seed);

return _threadRng = new(MemoryMarshal.Read<int>(seed));
}
#endif
}
Loading