NadekoBot/NadekoBot.Core/Common/NadekoRandom.cs

63 lines
1.8 KiB
C#
Raw Normal View History

using System;
using System.Security.Cryptography;
2017-07-17 19:42:36 +00:00
namespace NadekoBot.Common
{
public class NadekoRandom : Random
{
2017-07-17 19:42:36 +00:00
readonly RandomNumberGenerator _rng;
public NadekoRandom() : base()
{
2017-07-17 19:42:36 +00:00
_rng = RandomNumberGenerator.Create();
}
public override int Next()
{
var bytes = new byte[sizeof(int)];
2017-07-17 19:42:36 +00:00
_rng.GetBytes(bytes);
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);
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);
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);
}
protected override double Sample()
{
var bytes = new byte[sizeof(double)];
2017-07-17 19:42:36 +00:00
_rng.GetBytes(bytes);
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);
return BitConverter.ToDouble(bytes, 0);
}
}
}