2016-09-10 19:40:25 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
|
2017-07-17 19:42:36 +00:00
|
|
|
|
namespace NadekoBot.Common
|
2016-09-10 19:40:25 +00:00
|
|
|
|
{
|
|
|
|
|
public class NadekoRandom : Random
|
|
|
|
|
{
|
2017-07-17 19:42:36 +00:00
|
|
|
|
readonly RandomNumberGenerator _rng;
|
2016-09-10 19:40:25 +00:00
|
|
|
|
|
|
|
|
|
public NadekoRandom() : base()
|
|
|
|
|
{
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng = RandomNumberGenerator.Create();
|
2016-09-10 19:40:25 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override int Next()
|
|
|
|
|
{
|
|
|
|
|
var bytes = new byte[sizeof(int)];
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng.GetBytes(bytes);
|
2016-09-10 19:40:25 +00:00
|
|
|
|
return Math.Abs(BitConverter.ToInt32(bytes, 0));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override int Next(int maxValue)
|
|
|
|
|
{
|
|
|
|
|
if (maxValue <= 0)
|
|
|
|
|
throw new ArgumentOutOfRangeException();
|
|
|
|
|
var bytes = new byte[sizeof(int)];
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng.GetBytes(bytes);
|
2016-09-10 19:40:25 +00:00
|
|
|
|
return Math.Abs(BitConverter.ToInt32(bytes, 0)) % maxValue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override int Next(int minValue, int maxValue)
|
|
|
|
|
{
|
|
|
|
|
if (minValue > maxValue)
|
|
|
|
|
throw new ArgumentOutOfRangeException();
|
|
|
|
|
if (minValue == maxValue)
|
|
|
|
|
return minValue;
|
|
|
|
|
var bytes = new byte[sizeof(int)];
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng.GetBytes(bytes);
|
2016-09-10 19:40:25 +00:00
|
|
|
|
var sign = Math.Sign(BitConverter.ToInt32(bytes, 0));
|
|
|
|
|
return (sign * BitConverter.ToInt32(bytes, 0)) % (maxValue - minValue) + minValue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override void NextBytes(byte[] buffer)
|
|
|
|
|
{
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng.GetBytes(buffer);
|
2016-09-10 19:40:25 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected override double Sample()
|
|
|
|
|
{
|
|
|
|
|
var bytes = new byte[sizeof(double)];
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng.GetBytes(bytes);
|
2016-09-10 19:40:25 +00:00
|
|
|
|
return Math.Abs(BitConverter.ToDouble(bytes, 0) / double.MaxValue + 1);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public override double NextDouble()
|
|
|
|
|
{
|
|
|
|
|
var bytes = new byte[sizeof(double)];
|
2017-07-17 19:42:36 +00:00
|
|
|
|
_rng.GetBytes(bytes);
|
2016-09-10 19:40:25 +00:00
|
|
|
|
return BitConverter.ToDouble(bytes, 0);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|