Skip to content

Commit

Permalink
Fix Issue 17847 - Properly sanitize seeds for Park–Miller engines
Browse files Browse the repository at this point in the history
As in XorshiftEngine, sanitizing the seed is more useful than throwing
an exception. The original check was broken because it checked the seed
before taking the modulus. Making this change allows unpredictableSeed
to be marked nothrow and @nogc.
  • Loading branch information
n8sh authored and n8sh committed Sep 21, 2017
1 parent efae085 commit fd2e5ba
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 fd2e5ba

Please sign in to comment.