Esempio n. 1
0
        /// <summary>
        /// Generates a random long value.
        /// </summary>
        /// <param name="minValue">The inclusive lower bound of the random number returned.</param>
        /// <param name="maxValue">The inclusive upper bound of the random number returned.</param>
        /// <returns>A long value generated randomly.</returns>
        public long GenerateLong(long?minValue = null, long?maxValue = null)
        {
            minValue = minValue ?? long.MinValue;
            maxValue = maxValue ?? long.MaxValue;

            if (maxValue.Value <= minValue.Value)
            {
                throw new ArgumentOutOfRangeException("maxValue", "maxValue must be > minValue!");
            }

            //Working with ulong so that modulo works correctly with values > long.MaxValue
            var uRange = NumberExtensions.ComputeRange(minValue, maxValue);

            //Prevent a modolo bias; see https://stackoverflow.com/a/10984975/238419
            //for more information.
            //In the worst case, the expected number of calls is 2 (though usually it's
            //much closer to 1) so this loop doesn't really hurt performance at all.
            ulong ulongRand;
            var   maxValue1 = ulong.MaxValue - ((ulong.MaxValue % uRange) + 1) % uRange;

            do
            {
                var buf = new byte[8];
                _fuzzer.Random.NextBytes(buf);
                ulongRand = (ulong)BitConverter.ToInt64(buf, 0);
            } while (ulongRand > maxValue1);

            var modulo = (long)(ulongRand % uRange);
            var result = modulo + minValue.Value;

            return(result);
        }