Skip to content

Commit

Permalink
Merge pull request #5743 from n8sh/fix-random-lcg
Browse files Browse the repository at this point in the history
Fix Issue 17847 - Properly sanitize seeds for Park–Miller engines
merged-on-behalf-of: Dmitry Olshansky <dmitry@olshansky.me>
  • Loading branch information
dlang-bot committed Sep 25, 2017
2 parents b60b75c + fd2e5ba commit 218434f
Showing 1 changed file with 15 additions and 7 deletions.
22 changes: 15 additions & 7 deletions std/random.d
Expand Up @@ -362,23 +362,23 @@ The parameters of this distribution. The random number is $(D_PARAM x
Constructs a $(D_PARAM LinearCongruentialEngine) generator seeded with
$(D x0).
*/
this(UIntType x0) @safe pure
this(UIntType x0) @safe pure nothrow @nogc
{
seed(x0);
}

/**
(Re)seeds the generator.
*/
void seed(UIntType x0 = 1) @safe pure
void seed(UIntType x0 = 1) @safe pure nothrow @nogc
{
_x = modulus ? (x0 % modulus) : x0;
static if (c == 0)
{
import std.exception : enforce;
enforce(x0, "Invalid (zero) seed for "
~ LinearCongruentialEngine.stringof);
//Necessary to prevent generator from outputting an endless series of zeroes.
if (_x == 0)
_x = max;
}
_x = modulus ? (x0 % modulus) : x0;
popFront();
}

Expand Down Expand Up @@ -537,6 +537,14 @@ alias MinstdRand = LinearCongruentialEngine!(uint, 48_271, 0, 2_147_483_647);
}
}

@safe unittest
{
auto rnd0 = MinstdRand0(MinstdRand0.modulus);
auto n = rnd0.front;
rnd0.popFront();
assert(n != rnd0.front);
}

/**
The $(LINK2 https://en.wikipedia.org/wiki/Mersenne_Twister, Mersenne Twister) generator.
*/
Expand Down Expand Up @@ -1291,7 +1299,7 @@ random number sequences every run.
Returns:
A single unsigned integer seed value, different on each successive call
*/
@property uint unpredictableSeed() @trusted
@property uint unpredictableSeed() @trusted nothrow @nogc
{
import core.thread : Thread, getpid, MonoTime;
static bool seeded;
Expand Down

0 comments on commit 218434f

Please sign in to comment.