1) Unifdef USE_WEAK_SEEDING since it is too obsolete to support and makes

reading hard.

2) Instead of doing range transformation in each and every function here,
do it single time directly in do_rand(). One "mod" operation overhead is not
a big deal, but the code looks nicer and possible future functions additions
or PRNG change do not miss range transformations neither have unneeded ones.

3) Use POSIX argument types for visible functions (cosmetic).

MFC after:      1 week
This commit is contained in:
Andrey A. Chernov 2016-05-29 13:57:06 +00:00
parent 864a391104
commit 44f8773834

View File

@ -48,14 +48,6 @@ __FBSDID("$FreeBSD$");
static int static int
do_rand(unsigned long *ctx) do_rand(unsigned long *ctx)
{ {
#ifdef USE_WEAK_SEEDING
/*
* Historic implementation compatibility.
* The random sequences do not vary much with the seed,
* even with overflowing.
*/
return ((*ctx = *ctx * 1103515245 + 12345) % ((u_long)RAND_MAX + 1));
#else /* !USE_WEAK_SEEDING */
/* /*
* Compute x = (7^5 * x) mod (2^31 - 1) * Compute x = (7^5 * x) mod (2^31 - 1)
* without overflowing 31 bits: * without overflowing 31 bits:
@ -66,48 +58,34 @@ do_rand(unsigned long *ctx)
*/ */
long hi, lo, x; long hi, lo, x;
/* Must be in [1, 0x7ffffffe] range at this point. */ /* Transform to [1, 0x7ffffffe] range. */
hi = *ctx / 127773; x = (*ctx % 0x7ffffffe) + 1;
lo = *ctx % 127773; hi = x / 127773;
lo = x % 127773;
x = 16807 * lo - 2836 * hi; x = 16807 * lo - 2836 * hi;
if (x < 0) if (x < 0)
x += 0x7fffffff; x += 0x7fffffff;
*ctx = x;
/* Transform to [0, 0x7ffffffd] range. */ /* Transform to [0, 0x7ffffffd] range. */
return (x - 1); x--;
#endif /* !USE_WEAK_SEEDING */ *ctx = x;
return (x);
} }
int int
rand_r(unsigned int *ctx) rand_r(unsigned *ctx)
{ {
u_long val; u_long val;
int r; int r;
#ifdef USE_WEAK_SEEDING
val = *ctx; val = *ctx;
#else
/* Transform to [1, 0x7ffffffe] range. */
val = (*ctx % 0x7ffffffe) + 1;
#endif
r = do_rand(&val); r = do_rand(&val);
*ctx = (unsigned)val;
#ifdef USE_WEAK_SEEDING
*ctx = (unsigned int)val;
#else
*ctx = (unsigned int)(val - 1);
#endif
return (r); return (r);
} }
static u_long next = static u_long next = 1;
#ifdef USE_WEAK_SEEDING
1;
#else
2;
#endif
int int
rand(void) rand(void)
@ -116,13 +94,9 @@ rand(void)
} }
void void
srand(u_int seed) srand(unsigned seed)
{ {
next = seed; next = seed;
#ifndef USE_WEAK_SEEDING
/* Transform to [1, 0x7ffffffe] range. */
next = (next % 0x7ffffffe) + 1;
#endif
} }
@ -144,10 +118,6 @@ sranddev(void)
mib[0] = CTL_KERN; mib[0] = CTL_KERN;
mib[1] = KERN_ARND; mib[1] = KERN_ARND;
sysctl(mib, 2, (void *)&next, &len, NULL, 0); sysctl(mib, 2, (void *)&next, &len, NULL, 0);
#ifndef USE_WEAK_SEEDING
/* Transform to [1, 0x7ffffffe] range. */
next = (next % 0x7ffffffe) + 1;
#endif
} }