Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make RandomNumberGenerator.Create return a singleton #52495

Merged
merged 2 commits into from
May 11, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ namespace System.Security.Cryptography
{
internal sealed partial class RandomNumberGeneratorImplementation
{
// a singleton which always calls into a thread-safe implementation
// and whose Dispose method no-ops
internal static readonly RandomNumberGeneratorImplementation s_singleton = new RandomNumberGeneratorImplementation();
GrabYourPitchforks marked this conversation as resolved.
Show resolved Hide resolved

// private ctor used only by singleton
private RandomNumberGeneratorImplementation()
{
}

private static unsafe void GetBytes(byte* pbBuffer, int count)
{
Debug.Assert(count > 0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@ public abstract class RandomNumberGenerator : IDisposable
{
protected RandomNumberGenerator() { }

public static RandomNumberGenerator Create()
{
return new RandomNumberGeneratorImplementation();
}
public static RandomNumberGenerator Create() => RandomNumberGeneratorImplementation.s_singleton;

[UnsupportedOSPlatform("browser")]
[RequiresUnreferencedCode(CryptoConfig.CreateFromNameUnreferencedCodeMessage)]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,30 @@ namespace System.Security.Cryptography.RNG.Tests
{
public class RandomNumberGeneratorTests
{
[Fact]
public static void Create_ReturnsSingleton()
{
RandomNumberGenerator rng1 = RandomNumberGenerator.Create();
RandomNumberGenerator rng2 = RandomNumberGenerator.Create();

Assert.Same(rng1, rng2);
}

[Fact]
public static void Singleton_NoopsDispose()
{
byte[] random = new byte[1024];
RandomNumberGenerator rng = RandomNumberGenerator.Create();
rng.GetBytes(random);
RandomDataGenerator.VerifyRandomDistribution(random);
rng.Dispose(); // should no-op if called once

random = new byte[1024];
rng.GetBytes(random); // should still work even after earlier Dispose call
RandomDataGenerator.VerifyRandomDistribution(random);
rng.Dispose(); // should no-op if called twice
}

[Theory]
[InlineData(2048)]
[InlineData(65536)]
Expand Down