From 373fc12bb1a985c10792050b5e50998f762d2cbb Mon Sep 17 00:00:00 2001 From: Sterling Hughes Date: Sun, 16 Sep 2001 03:46:59 +0000 Subject: [PATCH] @ Make the seed options to srand() and mt_srand() optional, if the seed is @ not specified, the generate the most random seed possible. (Sterling) Please, if anyone has any comments on the way I generate this seed, speak up! This seems to be the most "random" seed I could come up with... This commit is 100% backwards compatible :) Add myself to the authors list cause of recent work on the file --- ext/standard/rand.c | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/ext/standard/rand.c b/ext/standard/rand.c index 3be21653037..8cde64300b3 100644 --- a/ext/standard/rand.c +++ b/ext/standard/rand.c @@ -15,6 +15,7 @@ | Authors: Rasmus Lerdorf | | Zeev Suraski | | Pedro Melo | + | Sterling Hughes | | | | Based on code from: Shawn Cokus | +----------------------------------------------------------------------+ @@ -112,6 +113,7 @@ PHPAPI void php_mt_srand(php_uint32 seed TSRMLS_DC) 2^31, 2^31, 2^31, ...; 2^30, 2^30, 2^30, ...; 2^29, 2^29 + 2^31, 2^29, 2^29 + 2^31, ..., etc. so I force seed to be odd below. + Even if x_initial is odd, if x_initial is 1 mod 4 then the lowest bit of x is always 1, @@ -190,28 +192,36 @@ PHPAPI php_uint32 php_mt_rand(TSRMLS_D) return y ^ (y >> 18); } -/* {{{ proto void srand(int seed) +#define GENERATE_SEED() (time(0) * getpid() * 1000000 * php_combined_lcg(TSRMLS_C)) + +/* {{{ proto void srand([int seed]) Seeds random number generator */ PHP_FUNCTION(srand) { - long seed; + long seed = 0; - if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &seed) == FAILURE) + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &seed) == FAILURE) return; + if (!seed) + seed = GENERATE_SEED(); + php_srand(seed); } /* }}} */ -/* {{{ proto void mt_srand(int seed) +/* {{{ proto void mt_srand([int seed]) Seeds Mersenne Twister random number generator */ PHP_FUNCTION(mt_srand) { - long seed; + long seed = 0; - if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &seed) == FAILURE) + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &seed) == FAILURE) return; + if (!seed) + seed = GENERATE_SEED(); + php_mt_srand(seed TSRMLS_CC); } /* }}} */