xref: /PHP-8.0/ext/standard/rand.c (revision 2b5de6f8)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | Authors: Rasmus Lerdorf <rasmus@php.net>                             |
14    |          Zeev Suraski <zeev@php.net>                                 |
15    |          Pedro Melo <melo@ip.pt>                                     |
16    |          Sterling Hughes <sterling@php.net>                          |
17    |                                                                      |
18    | Based on code from: Richard J. Wagner <rjwagner@writeme.com>         |
19    |                     Makoto Matsumoto <matumoto@math.keio.ac.jp>      |
20    |                     Takuji Nishimura                                 |
21    |                     Shawn Cokus <Cokus@math.washington.edu>          |
22    +----------------------------------------------------------------------+
23  */
24 
25 #include "php.h"
26 #include "php_rand.h"
27 #include "php_mt_rand.h"
28 
29 /* {{{ php_srand */
php_srand(zend_long seed)30 PHPAPI void php_srand(zend_long seed)
31 {
32 	php_mt_srand(seed);
33 }
34 /* }}} */
35 
36 /* {{{ php_rand */
php_rand(void)37 PHPAPI zend_long php_rand(void)
38 {
39 	return php_mt_rand();
40 }
41 /* }}} */
42 
43 /* {{{ Returns a random number from Mersenne Twister */
PHP_FUNCTION(rand)44 PHP_FUNCTION(rand)
45 {
46 	zend_long min;
47 	zend_long max;
48 	int argc = ZEND_NUM_ARGS();
49 
50 	if (argc == 0) {
51 		RETURN_LONG(php_mt_rand() >> 1);
52 	}
53 
54 	ZEND_PARSE_PARAMETERS_START(2, 2)
55 		Z_PARAM_LONG(min)
56 		Z_PARAM_LONG(max)
57 	ZEND_PARSE_PARAMETERS_END();
58 
59 	if (max < min) {
60 		RETURN_LONG(php_mt_rand_common(max, min));
61 	}
62 
63 	RETURN_LONG(php_mt_rand_common(min, max));
64 }
65 /* }}} */
66