-
Notifications
You must be signed in to change notification settings - Fork 293
Expand file tree
/
Copy pathRandomId.cs
More file actions
49 lines (42 loc) · 1.65 KB
/
RandomId.cs
File metadata and controls
49 lines (42 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under dual-license. See LICENSE.PLATFORMTOOLS.txt file in the project root for full license information.
// Copy from https://github.com/microsoft/testfx/blob/b769496b8992bf8f51e000f7a5626b5ec6bb3d27/test/Utilities/Microsoft.Testing.TestInfrastructure/RandomId.cs
using System.Security.Cryptography;
namespace Microsoft.Testing.Extensions;
/// <summary>
/// Slightly random id that is just good enough for creating distinct directories for each test.
/// </summary>
internal static class RandomId
{
private const string Pool = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#if NET9_0_OR_GREATER
private static readonly Lock s_lock = new();
#else
private static readonly object s_lock = new();
#endif
private static readonly RandomNumberGenerator Rng = RandomNumberGenerator.Create();
/// <summary>
/// 5 character long id from 0-9A-Za-z0, for example fUfko, A6uvM, sOMXa, RY1ei, KvdJZ.
/// </summary>
public static string Next() => Next(5);
private static string Next(int length)
{
int poolLength = Pool.Length;
char[] id = new char[length];
lock (s_lock)
{
for (int idIndex = 0; idIndex < length; idIndex++)
{
int poolIndex = poolLength + 1;
while (poolIndex >= poolLength)
{
byte[] bytes = new byte[1];
Rng.GetNonZeroBytes(bytes);
poolIndex = bytes[0];
}
id[idIndex] = Pool[poolIndex];
}
}
return new string(id);
}
}