xref: /php-src/ext/standard/rand.c (revision 5d6e923d)
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
30  */
php_srand(zend_long seed)31 PHPAPI void php_srand(zend_long seed)
32 {
33 	php_mt_srand(seed);
34 }
35 /* }}} */
36 
37 /* {{{ php_rand
38  */
php_rand(void)39 PHPAPI zend_long php_rand(void)
40 {
41 	return php_mt_rand();
42 }
43 /* }}} */
44 
45 /* {{{ proto int mt_rand([int min, int max])
46    Returns a random number from Mersenne Twister */
PHP_FUNCTION(rand)47 PHP_FUNCTION(rand)
48 {
49 	zend_long min;
50 	zend_long max;
51 	int argc = ZEND_NUM_ARGS();
52 
53 	if (argc == 0) {
54 		RETURN_LONG(php_mt_rand() >> 1);
55 	}
56 
57 	ZEND_PARSE_PARAMETERS_START(2, 2)
58 		Z_PARAM_LONG(min)
59 		Z_PARAM_LONG(max)
60 	ZEND_PARSE_PARAMETERS_END();
61 
62 	if (max < min) {
63 		RETURN_LONG(php_mt_rand_common(max, min));
64 	}
65 
66 	RETURN_LONG(php_mt_rand_common(min, max));
67 }
68 /* }}} */
69