-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Random.cs
245 lines (216 loc) · 10.4 KB
/
Random.cs
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
namespace SuperLinq.Async;
public static partial class AsyncSuperEnumerable
{
/// <summary>
/// Returns an infinite sequence of random integers using the standard
/// .NET random number generator.
/// </summary>
/// <returns>An infinite sequence of random integers</returns>
/// <remarks>
/// The implementation internally uses a shared, thread-local instance of
/// <see cref="System.Random" /> to generate a random number on each
/// iteration. The actual <see cref="System.Random" /> instance used
/// therefore will depend on the thread on which a single iteration is
/// taking place; that is the call to
/// <see cref="System.Collections.IEnumerator.MoveNext()" />. If the
/// overall iteration takes place on different threads (e.g.
/// via asynchronous awaits completing on different threads) then various
/// different <see cref="System.Random" /> instances will be involved
/// in the generation of the sequence of random numbers. Because the
/// <see cref="System.Random" /> instance is shared, if multiple sequences
/// are generated on the same thread, the order of enumeration affects the
/// resulting sequences.
/// </remarks>
public static IAsyncEnumerable<int> Random()
{
return Random(s_randomInstance);
}
/// <summary>
/// Returns an infinite sequence of random integers using the supplied
/// random number generator.
/// </summary>
/// <param name="rand">Random generator used to produce random numbers</param>
/// <returns>An infinite sequence of random integers</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="rand"/> is <see langword="null"/>.</exception>
public static IAsyncEnumerable<int> Random(Random rand)
{
ArgumentNullException.ThrowIfNull(rand);
return RandomImpl(rand, r => r.Next());
}
/// <summary>
/// Returns an infinite sequence of random integers between zero and
/// a given maximum.
/// </summary>
/// <param name="maxValue">exclusive upper bound for the random values returned</param>
/// <returns>An infinite sequence of random integers</returns>
/// <remarks>
/// The implementation internally uses a shared, thread-local instance of
/// <see cref="System.Random" /> to generate a random number on each
/// iteration. The actual <see cref="System.Random" /> instance used
/// therefore will depend on the thread on which a single iteration is
/// taking place; that is the call to
/// <see cref="System.Collections.IEnumerator.MoveNext()" />. If the
/// overall iteration takes place on different threads (e.g.
/// via asynchronous awaits completing on different threads) then various
/// different <see cref="System.Random" /> instances will be involved
/// in the generation of the sequence of random numbers. Because the
/// <see cref="System.Random" /> instance is shared, if multiple sequences
/// are generated on the same thread, the order of enumeration affects the
/// resulting sequences.
/// </remarks>
public static IAsyncEnumerable<int> Random(int maxValue)
{
ArgumentOutOfRangeException.ThrowIfNegative(maxValue);
return Random(s_randomInstance, maxValue);
}
/// <summary>
/// Returns an infinite sequence of random integers between zero and a
/// given maximum using the supplied random number generator.
/// </summary>
/// <param name="rand">Random generator used to produce values</param>
/// <param name="maxValue">Exclusive upper bound for random values returned</param>
/// <returns>An infinite sequence of random integers</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="rand"/> is <see langword="null"/>.</exception>
public static IAsyncEnumerable<int> Random(Random rand, int maxValue)
{
ArgumentNullException.ThrowIfNull(rand);
ArgumentOutOfRangeException.ThrowIfNegative(maxValue);
return RandomImpl(rand, r => r.Next(maxValue));
}
/// <summary>
/// Returns an infinite sequence of random integers between a given
/// minimum and a maximum.
/// </summary>
/// <param name="minValue">Inclusive lower bound of the values returned</param>
/// <param name="maxValue">Exclusive upper bound of the values returned</param>
/// <returns>An infinite sequence of random integers</returns>
/// <remarks>
/// The implementation internally uses a shared, thread-local instance of
/// <see cref="System.Random" /> to generate a random number on each
/// iteration. The actual <see cref="System.Random" /> instance used
/// therefore will depend on the thread on which a single iteration is
/// taking place; that is the call to
/// <see cref="System.Collections.IEnumerator.MoveNext()" />. If the
/// overall iteration takes place on different threads (e.g.
/// via asynchronous awaits completing on different threads) then various
/// different <see cref="System.Random" /> instances will be involved
/// in the generation of the sequence of random numbers. Because the
/// <see cref="System.Random" /> instance is shared, if multiple sequences
/// are generated on the same thread, the order of enumeration affects the
/// resulting sequences.
/// </remarks>
public static IAsyncEnumerable<int> Random(int minValue, int maxValue)
{
return Random(s_randomInstance, minValue, maxValue);
}
/// <summary>
/// Returns an infinite sequence of random integers between a given
/// minumum and a maximum using the supplied random number generator.
/// </summary>
/// <param name="rand">Generator used to produce random numbers</param>
/// <param name="minValue">Inclusive lower bound of the values returned</param>
/// <param name="maxValue">Exclusive upper bound of the values returned</param>
/// <returns>An infinite sequence of random integers</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="rand"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="minValue"/> is greater than <paramref name="maxValue"/>.</exception>
public static IAsyncEnumerable<int> Random(Random rand, int minValue, int maxValue)
{
ArgumentNullException.ThrowIfNull(rand);
ArgumentOutOfRangeException.ThrowIfLessThan(maxValue, minValue);
return RandomImpl(rand, r => r.Next(minValue, maxValue));
}
/// <summary>
/// Returns an infinite sequence of random double values between 0.0 and 1.0
/// </summary>
/// <returns>An infinite sequence of random doubles</returns>
/// <remarks>
/// The implementation internally uses a shared, thread-local instance of
/// <see cref="System.Random" /> to generate a random number on each
/// iteration. The actual <see cref="System.Random" /> instance used
/// therefore will depend on the thread on which a single iteration is
/// taking place; that is the call to
/// <see cref="System.Collections.IEnumerator.MoveNext()" />. If the
/// overall iteration takes place on different threads (e.g.
/// via asynchronous awaits completing on different threads) then various
/// different <see cref="System.Random" /> instances will be involved
/// in the generation of the sequence of random numbers. Because the
/// <see cref="System.Random" /> instance is shared, if multiple sequences
/// are generated on the same thread, the order of enumeration affects the
/// resulting sequences.
/// </remarks>
public static IAsyncEnumerable<double> RandomDouble()
{
return RandomDouble(s_randomInstance);
}
/// <summary>
/// Returns an infinite sequence of random double values between 0.0 and 1.0
/// using the supplied random number generator.
/// </summary>
/// <param name="rand">Generator used to produce random numbers</param>
/// <returns>An infinite sequence of random doubles</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="rand"/> is <see langword="null"/>.</exception>
public static IAsyncEnumerable<double> RandomDouble(Random rand)
{
ArgumentNullException.ThrowIfNull(rand);
return RandomImpl(rand, r => r.NextDouble());
}
/// <summary>
/// This is the underlying implementation that all random operators use to
/// produce a sequence of random values.
/// </summary>
/// <typeparam name="T">The type of value returned (either Int32 or Double)</typeparam>
/// <param name="rand">Random generators used to produce the sequence</param>
/// <param name="nextValue">Generator function that actually produces the next value - specific to T</param>
/// <param name="cancellationToken"></param>
/// <returns>An infinite sequence of random numbers of type T</returns>
#pragma warning disable CS1998
private static async IAsyncEnumerable<T> RandomImpl<T>(
Random rand,
Func<Random, T> nextValue,
[EnumeratorCancellation] CancellationToken cancellationToken = default
)
{
while (true)
{
cancellationToken.ThrowIfCancellationRequested();
yield return nextValue(rand);
}
}
#pragma warning restore CS1998
private static readonly Random s_randomInstance =
#if NET6_0_OR_GREATER
System.Random.Shared;
#else
new GlobalRandom();
/// <remarks>
/// <see cref="System.Random"/> is not thread-safe so the following
/// implementation uses thread-local <see cref="System.Random"/>
/// instances to create the illusion of a global
/// <see cref="System.Random"/> implementation. For some background,
/// see <a href="https://blogs.msdn.microsoft.com/pfxteam/2009/02/19/getting-random-numbers-in-a-thread-safe-way/">Getting
/// random numbers in a thread-safe way</a>
/// </remarks>
private sealed class GlobalRandom : Random
{
private static int s_seed = Environment.TickCount;
[ThreadStatic] private static Random? s_threadRandom;
private static Random ThreadRandom => s_threadRandom ??= new Random(Interlocked.Increment(ref s_seed));
public override int Next() => ThreadRandom.Next();
public override int Next(int minValue, int maxValue) => ThreadRandom.Next(minValue, maxValue);
public override int Next(int maxValue) => ThreadRandom.Next(maxValue);
public override double NextDouble() => ThreadRandom.NextDouble();
public override void NextBytes(byte[] buffer) => ThreadRandom.NextBytes(buffer);
protected override double Sample()
{
// All the NextXXX calls are hijacked above to use the Random
// instance allocated for the thread so no call from the base
// class should ever end up here. If Random introduces new
// virtual members in the future that call into Sample and
// which end up getting used in the implementation of a
// randomizing operator from the outer class then they will
// need to be overriden.
return ThrowHelper.ThrowNotSupportedException<double>();
}
}
#endif
}