File size: 10,068 Bytes
b1b3bae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/// ------------------------------------------------------
/// RandomOps - (Pseudo) Random Number Generator For C#
/// Copyright (C) 2003-2010 Magnus Erik Hvass Pedersen.
/// Please see the file license.txt for license details.
/// RandomOps on the internet: http://www.Hvass-Labs.org/
/// ------------------------------------------------------

using System;
using System.Collections.Generic;

namespace RandomOps
{
    /// <summary>
    /// Base-class for an RNG which retrieves a stream of random
    /// bytes from somewhere, e.g. from a file, from the internet,
    /// or from a physical device such as a USB-device.
    /// </summary>
    public abstract class ByteStream : Random
    {
        #region Constructor.
        /// <summary>
        /// Construct the RNG-object.
        /// </summary>
        /// <param name="bufferSize">Number of random bytes the buffer holds.</param>
        /// <param name="randFallback">Fallback RNG to be used when buffer is empty.</param>
        /// <param name="numFallback">Use fallback RNG for this many bytes before trying to fill buffer again.</param>
        public ByteStream(int bufferSize, Random randFallback, int numFallback)
        {
            RandFallback = randFallback;
            NumFallback = numFallback;
            BufferSize = Math.Max(bufferSize, sizeof(UInt32));
            Queue = new Queue<byte>(BufferSize);

            // Fill the buffer so it is ready to use.
            FillBuffer();
        }
        #endregion

        #region Properties.
        /// <summary>
        /// The number of bytes to fill the buffer with.
        /// </summary>
        protected int FillCount
        {
            get { return BufferSize - Queue.Count; }
        }

        /// <summary>
        /// The maximum number of bytes that can be retrieved in a single
        /// call to DoFillBuffer(). Usually this is the same as BufferSize,
        /// but some sources allow a maximum number of bytes that can be
        /// retrieved each time or they will generate an error.
        /// </summary>
        protected virtual int MaxRetrieveLength
        {
            get { return BufferSize; }
        }
        #endregion

        #region Internal variables.
        /// <summary>
        /// The queue used for buffering the retrieved bytes.
        /// </summary>
        protected Queue<byte> Queue;

        /// <summary>
        /// Desired size of the byte-buffer.
        /// </summary>
        protected int BufferSize;

        /// <summary>
        /// 1.0/((double)UInt32.MaxValue + 2), for convenience and speed.
        /// </summary>
        double _randMaxPlusTwoInv = 1.0 / ((double)UInt32.MaxValue + 2);
        #endregion

        #region Fallback RNG.
        /// <summary>
        /// Fallback RNG.
        /// </summary>
        protected Random RandFallback;

        /// <summary>
        /// Number of bytes to retrieve from Fallback RNG
        /// whenever buffer becomes empty.
        /// </summary>
        protected int NumFallback
        {
            get;
            private set;
        }

        /// <summary>
        /// How many bytes yet to be retrieved from Fallback RNG
        /// before buffer will be attempted filled again.
        /// </summary>
        protected int FallbackCount = 0;
        #endregion

        #region Fill buffer.
        /// <summary>
        /// Override this so that it retrieves the requested number of bytes
        /// and calls AddBuffer() to add them to the buffer.
        /// </summary>
        /// <param name="length">Number of bytes to be retrieved.</param>
        protected abstract void DoFillBuffer(int length);

        /// <summary>
        /// Fill the buffer by calling DoFillBuffer(). The entire buffer
        /// may not be fillable in one call of DoFillBuffer(), e.g. due
        /// to restrictions on the source of the bytes, and hence several
        /// calls to DoFillBuffer() must be made.
        /// </summary>
        /// <exception>
        /// All exceptions cause the Fallback RNG to be used.
        /// </exception>
        public virtual void FillBuffer()
        {
            int fillCount = FillCount;

            try
            {
                while (fillCount > 0)
                {
                    DoFillBuffer(System.Math.Min(fillCount, MaxRetrieveLength));

                    fillCount -= MaxRetrieveLength;
                }
            }
            catch
            {
                // Various internet errors may occur. Simply do nothing
                // and let the fallback RNG generate numbers instead
                // when the byte-buffer is discovered to be empty.

                FallbackCount = NumFallback;
            }
        }

        /// <summary>
        /// Fill the buffer with at least the number of bytes designated.
        /// </summary>
        /// <param name="size">Number of bytes requested to be in buffer.</param>
        public void FillBuffer(int size)
        {
            if (BufferSize < size)
            {
                BufferSize = size;
            }

            FillBuffer();
        }

        /// <summary>
        /// Add retrieved random bytes to the buffer.
        /// </summary>
        /// <param name="buffer">Random bytes to be added.</param>
        protected virtual void AddBuffer(IEnumerable<byte> buffer)
        {
            foreach (byte b in buffer)
            {
                Queue.Enqueue(b);
            }
        }
        #endregion

        #region Availability status.
        /// <summary>
        /// Is a single random byte currently available in the buffer?
        /// </summary>
        public bool IsAvailableByte()
        {
            return IsAvailable(sizeof(byte));
        }

        /// <summary>
        /// Is the given number of random bytes currently available in the buffer?
        /// </summary>
        public bool IsAvailableBytes(int length)
        {
            return IsAvailable(length);
        }

        /// <summary>
        /// Is a random number available in the buffer using the Uniform() method?
        /// </summary>
        public bool IsAvailableUniform()
        {
            return IsAvailable(sizeof(UInt32));
        }

        /// <summary>
        /// Determine if the requested number of bytes are available, if not
        /// then refill buffer.
        /// </summary>
        /// <param name="numBytes">Number of bytes requested.</param>
        /// <returns>Boolean indicating whether the requested number of bytes are available.</returns>
        protected virtual bool IsAvailable(int numBytes)
        {
            if (FallbackCount > 0)
            {
                // Decrease the fallback-counter.
                FallbackCount = System.Math.Max(0, FallbackCount - numBytes);
            }
            else if (Queue.Count < numBytes)
            {
                // Resize buffer if more bytes are suddenly requested than it
                // has capacity for.
                if (BufferSize < numBytes)
                {
                    BufferSize = numBytes;
                }

                // Fill the buffer and wait for the results (i.e. synchronous execution).
                FillBuffer();
            }

            return (Queue.Count >= numBytes);
        }
        #endregion

        #region Base-class overrides.
        /// <summary>
        /// Draw a random boolean with equal probability of true or false.
        /// Use the buffered random bytes if available, otherwise use Fallback RNG.
        /// </summary>
        public override byte Byte()
        {
            byte b = (IsAvailableByte()) ? (Queue.Dequeue()) : (RandFallback.Byte());

            return b;
        }

        /// <summary>
        /// Draw an array of random and uniform bytes.
        /// Use the buffered random bytes if available, otherwise use Fallback RNG.
        /// </summary>
        /// <param name="length">The array length requested.</param>
        public override byte[] Bytes(int length)
        {
            byte[] arr;

            if (IsAvailableBytes(length))
            {
                arr = new byte[length];

                for (int i = 0; i < length; i++)
                {
                    arr[i] = Queue.Dequeue();
                }
            }
            else
            {
                arr = RandFallback.Bytes(length);
            }

            return arr;
        }

        /// <summary>
        /// Draw a uniform random number in the exclusive range (0,1)
        /// This uses the Bytes() method to draw 4 random bytes, make them
        /// into an integer, and make that into a double. As such, it will
        /// indirectly use the Fallback RNG if no random bytes are available
        /// in the buffer.
        /// </summary>
        public sealed override double Uniform()
        {
            double value;

            if (IsAvailableUniform())
            {
                byte[] b = Bytes(sizeof(UInt32));

                UInt32 rand = BitConverter.ToUInt32(b, 0);
                double randPlusOne = (double)rand + 1;

                value = randPlusOne * _randMaxPlusTwoInv;
            }
            else
            {
                value = RandFallback.Uniform();
            }

            return value;
        }

        /// <summary>
        /// Draw a random boolean with equal probability of drawing true or false.
        /// This indirectly uses the Byte() method and will as such use the Fallback
        /// RNG if no buffered random bytes are available.
        /// </summary>
        public sealed override bool Bool()
        {
            byte b = Byte();
            return b <= (byte.MaxValue / 2);
        }
        #endregion
    }
}