/// ------------------------------------------------------ /// 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 { /// /// 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. /// public abstract class ByteStream : Random { #region Constructor. /// /// Construct the RNG-object. /// /// Number of random bytes the buffer holds. /// Fallback RNG to be used when buffer is empty. /// Use fallback RNG for this many bytes before trying to fill buffer again. public ByteStream(int bufferSize, Random randFallback, int numFallback) { RandFallback = randFallback; NumFallback = numFallback; BufferSize = Math.Max(bufferSize, sizeof(UInt32)); Queue = new Queue(BufferSize); // Fill the buffer so it is ready to use. FillBuffer(); } #endregion #region Properties. /// /// The number of bytes to fill the buffer with. /// protected int FillCount { get { return BufferSize - Queue.Count; } } /// /// 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. /// protected virtual int MaxRetrieveLength { get { return BufferSize; } } #endregion #region Internal variables. /// /// The queue used for buffering the retrieved bytes. /// protected Queue Queue; /// /// Desired size of the byte-buffer. /// protected int BufferSize; /// /// 1.0/((double)UInt32.MaxValue + 2), for convenience and speed. /// double _randMaxPlusTwoInv = 1.0 / ((double)UInt32.MaxValue + 2); #endregion #region Fallback RNG. /// /// Fallback RNG. /// protected Random RandFallback; /// /// Number of bytes to retrieve from Fallback RNG /// whenever buffer becomes empty. /// protected int NumFallback { get; private set; } /// /// How many bytes yet to be retrieved from Fallback RNG /// before buffer will be attempted filled again. /// protected int FallbackCount = 0; #endregion #region Fill buffer. /// /// Override this so that it retrieves the requested number of bytes /// and calls AddBuffer() to add them to the buffer. /// /// Number of bytes to be retrieved. protected abstract void DoFillBuffer(int length); /// /// 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. /// /// /// All exceptions cause the Fallback RNG to be used. /// 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; } } /// /// Fill the buffer with at least the number of bytes designated. /// /// Number of bytes requested to be in buffer. public void FillBuffer(int size) { if (BufferSize < size) { BufferSize = size; } FillBuffer(); } /// /// Add retrieved random bytes to the buffer. /// /// Random bytes to be added. protected virtual void AddBuffer(IEnumerable buffer) { foreach (byte b in buffer) { Queue.Enqueue(b); } } #endregion #region Availability status. /// /// Is a single random byte currently available in the buffer? /// public bool IsAvailableByte() { return IsAvailable(sizeof(byte)); } /// /// Is the given number of random bytes currently available in the buffer? /// public bool IsAvailableBytes(int length) { return IsAvailable(length); } /// /// Is a random number available in the buffer using the Uniform() method? /// public bool IsAvailableUniform() { return IsAvailable(sizeof(UInt32)); } /// /// Determine if the requested number of bytes are available, if not /// then refill buffer. /// /// Number of bytes requested. /// Boolean indicating whether the requested number of bytes are available. 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. /// /// Draw a random boolean with equal probability of true or false. /// Use the buffered random bytes if available, otherwise use Fallback RNG. /// public override byte Byte() { byte b = (IsAvailableByte()) ? (Queue.Dequeue()) : (RandFallback.Byte()); return b; } /// /// Draw an array of random and uniform bytes. /// Use the buffered random bytes if available, otherwise use Fallback RNG. /// /// The array length requested. 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; } /// /// 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. /// 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; } /// /// 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. /// public sealed override bool Bool() { byte b = Byte(); return b <= (byte.MaxValue / 2); } #endregion } }