Skip to content

Add Random.Get{Hex}String #112162

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

Merged
merged 3 commits into from
Feb 21, 2025
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
48 changes: 48 additions & 0 deletions src/libraries/System.Private.CoreLib/src/System/Random.cs
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,54 @@ public void Shuffle<T>(Span<T> values)
}
}

/// <summary>Creates a string populated with characters chosen at random from <paramref name="choices"/>.</summary>
/// <param name="choices">The characters to use to populate the string.</param>
/// <param name="length">The length of string to return.</param>
/// <returns>A string populated with items selected at random from <paramref name="choices"/>.</returns>
/// <exception cref="ArgumentException"><paramref name="choices" /> is empty.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length" /> is not zero or a positive number.</exception>
/// <seealso cref="GetItems{T}(ReadOnlySpan{T}, Span{T})" />
public string GetString(ReadOnlySpan<char> choices, int length)
{
if (choices.IsEmpty)
{
throw new ArgumentException(SR.Arg_EmptySpan, nameof(choices));
}

if (length <= 0)
{
ArgumentOutOfRangeException.ThrowIfNegative(length);
return string.Empty;
}

string destination = string.FastAllocateString(length);
GetItems(choices, new Span<char>(ref destination.GetRawStringData(), destination.Length));
return destination;
}

/// <summary>Creates a string filled with random hexadecimal characters.</summary>
/// <param name="stringLength">The length of string to create.</param>
/// <param name="lowercase">
/// <see langword="true" /> if the hexadecimal characters should be lowercase; <see langword="false" /> if they should be uppercase.
/// The default is <see langword="false" />.
/// </param>
/// <returns>A string populated with random hexadecimal characters.</returns>
public string GetHexString(int stringLength, bool lowercase = false) =>
GetString(GetHexChoices(lowercase), stringLength);

/// <summary>Fills a buffer with random hexadecimal characters.</summary>
/// <param name="destination">The buffer to receive the characters.</param>
/// <param name="lowercase">
/// <see langword="true" /> if the hexadecimal characters should be lowercase; <see langword="false" /> if they should be uppercase.
/// The default is <see langword="false" />.
/// </param>
public void GetHexString(Span<char> destination, bool lowercase = false) =>
GetItems(GetHexChoices(lowercase), destination);

/// <summary>Gets all possible hex characters for the specified casing.</summary>
private static ReadOnlySpan<char> GetHexChoices(bool lowercase) =>
lowercase ? "0123456789abcdef" : "0123456789ABCDEF";

/// <summary>Returns a random floating-point number between 0.0 and 1.0.</summary>
/// <returns>A double-precision floating point number that is greater than or equal to 0.0, and less than 1.0.</returns>
protected virtual double Sample()
Expand Down
3 changes: 3 additions & 0 deletions src/libraries/System.Runtime/ref/System.Runtime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4999,9 +4999,12 @@ public partial class Random
public Random() { }
public Random(int Seed) { }
public static System.Random Shared { get { throw null; } }
public string GetHexString(int stringLength, bool lowercase = false) { throw null; }
public void GetHexString(System.Span<char> destination, bool lowercase = false) { throw null; }
public T[] GetItems<T>(System.ReadOnlySpan<T> choices, int length) { throw null; }
public void GetItems<T>(System.ReadOnlySpan<T> choices, System.Span<T> destination) { }
public T[] GetItems<T>(T[] choices, int length) { throw null; }
public string GetString(System.ReadOnlySpan<char> choices, int length) { throw null; }
public virtual int Next() { throw null; }
public virtual int Next(int maxValue) { throw null; }
public virtual int Next(int minValue, int maxValue) { throw null; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -924,6 +924,79 @@ public static void GetItems_AllValuesInRange(int mode)
}
}

[Fact]
public static void GetString_ArgValidation()
{
Random random = new();
AssertExtensions.Throws<ArgumentException>("choices", () => random.GetString([], 42));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => random.GetString(['a'], -1));
}

[Fact]
public static void GetHexString_Array_ArgValidation()
{
Random random = new();
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => random.GetHexString(-1, true));
AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => random.GetHexString(-2, false));
}

[Fact]
public static void GetString_ProducesExpectedStrings()
{
Random random = new Random(42);
Assert.Equal("", random.GetString("abcdefghijklmnopqrstuvwxyz", 0));
Assert.Equal("c", random.GetString("abcd", 1));
Assert.Equal("aaca", random.GetString("abcde", 4));
Assert.Equal("gsnetggnijgnavpkdcsvobsdxsnebi", random.GetString("abcdefghijklmnopqrstuvwxyz", 30));
}

[Fact]
public static void GetHexString_Array_ProducesExpectedStrings()
{
Random random = new Random(42);

Assert.Equal("", random.GetHexString(0));
Assert.Equal("A", random.GetHexString(1));
Assert.Equal("2282", random.GetHexString(4));
Assert.Equal("4B82C34856480D9621BD80B2EB8204", random.GetHexString(30));

Assert.Equal("", random.GetHexString(0, false));
Assert.Equal("9", random.GetHexString(1, false));
Assert.Equal("D08C", random.GetHexString(4, false));
Assert.Equal("B6200CA13C4A209806BA30541B170C", random.GetHexString(30, false));

Assert.Equal("", random.GetHexString(0, true));
Assert.Equal("7", random.GetHexString(1, true));
Assert.Equal("870d", random.GetHexString(4, true));
Assert.Equal("001a0ee7690526c864e9b0ef5b2175", random.GetHexString(30, true));
}

[Fact]
public static void GetHexString_Span_ProducesExpectedItems()
{
Random random = new Random(42);

char[] dest;

dest = [];
random.GetHexString(dest);

var tests = new (int Length, string Expected)[]
{
(0, ""),
(1, "A"),
(4, "2282"),
(30, "4B82C34856480D9621BD80B2EB8204"),
};

foreach (var test in tests)
{
dest = new char[test.Length];
random.GetHexString(dest);
Assert.Equal(test.Expected, new string(dest));
}
}

private static Random Create(bool derived, bool seeded) =>
(derived, seeded) switch
{
Expand Down