PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/ext/standard/mt_rand.c

http://github.com/php/php-src
C | 356 lines | 171 code | 55 blank | 130 comment | 30 complexity | eff05c249e7dc7b5c8ae1a85d6e07776 MD5 | raw file
Possible License(s): BSD-2-Clause, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1
  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. #include "php.h"
  25. #include "php_rand.h"
  26. #include "php_mt_rand.h"
  27. /* MT RAND FUNCTIONS */
  28. /*
  29. The following php_mt_...() functions are based on a C++ class MTRand by
  30. Richard J. Wagner. For more information see the web page at
  31. http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/VERSIONS/C-LANG/MersenneTwister.h
  32. Mersenne Twister random number generator -- a C++ class MTRand
  33. Based on code by Makoto Matsumoto, Takuji Nishimura, and Shawn Cokus
  34. Richard J. Wagner v1.0 15 May 2003 rjwagner@writeme.com
  35. The Mersenne Twister is an algorithm for generating random numbers. It
  36. was designed with consideration of the flaws in various other generators.
  37. The period, 2^19937-1, and the order of equidistribution, 623 dimensions,
  38. are far greater. The generator is also fast; it avoids multiplication and
  39. division, and it benefits from caches and pipelines. For more information
  40. see the inventors' web page at http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
  41. Reference
  42. M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-Dimensionally
  43. Equidistributed Uniform Pseudo-Random Number Generator", ACM Transactions on
  44. Modeling and Computer Simulation, Vol. 8, No. 1, January 1998, pp 3-30.
  45. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  46. Copyright (C) 2000 - 2003, Richard J. Wagner
  47. All rights reserved.
  48. Redistribution and use in source and binary forms, with or without
  49. modification, are permitted provided that the following conditions
  50. are met:
  51. 1. Redistributions of source code must retain the above copyright
  52. notice, this list of conditions and the following disclaimer.
  53. 2. Redistributions in binary form must reproduce the above copyright
  54. notice, this list of conditions and the following disclaimer in the
  55. documentation and/or other materials provided with the distribution.
  56. 3. The names of its contributors may not be used to endorse or promote
  57. products derived from this software without specific prior written
  58. permission.
  59. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  60. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  61. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  62. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  63. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  64. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  65. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  66. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  67. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  68. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  69. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  70. */
  71. #define N MT_N /* length of state vector */
  72. #define M (397) /* a period parameter */
  73. #define hiBit(u) ((u) & 0x80000000U) /* mask all but highest bit of u */
  74. #define loBit(u) ((u) & 0x00000001U) /* mask all but lowest bit of u */
  75. #define loBits(u) ((u) & 0x7FFFFFFFU) /* mask the highest bit of u */
  76. #define mixBits(u, v) (hiBit(u)|loBits(v)) /* move hi bit of u to hi bit of v */
  77. #define twist(m,u,v) (m ^ (mixBits(u,v)>>1) ^ ((uint32_t)(-(int32_t)(loBit(v))) & 0x9908b0dfU))
  78. #define twist_php(m,u,v) (m ^ (mixBits(u,v)>>1) ^ ((uint32_t)(-(int32_t)(loBit(u))) & 0x9908b0dfU))
  79. /* {{{ php_mt_initialize
  80. */
  81. static inline void php_mt_initialize(uint32_t seed, uint32_t *state)
  82. {
  83. /* Initialize generator state with seed
  84. See Knuth TAOCP Vol 2, 3rd Ed, p.106 for multiplier.
  85. In previous versions, most significant bits (MSBs) of the seed affect
  86. only MSBs of the state array. Modified 9 Jan 2002 by Makoto Matsumoto. */
  87. register uint32_t *s = state;
  88. register uint32_t *r = state;
  89. register int i = 1;
  90. *s++ = seed & 0xffffffffU;
  91. for( ; i < N; ++i ) {
  92. *s++ = ( 1812433253U * ( *r ^ (*r >> 30) ) + i ) & 0xffffffffU;
  93. r++;
  94. }
  95. }
  96. /* }}} */
  97. /* {{{ php_mt_reload
  98. */
  99. static inline void php_mt_reload(void)
  100. {
  101. /* Generate N new values in state
  102. Made clearer and faster by Matthew Bellew (matthew.bellew@home.com) */
  103. register uint32_t *state = BG(state);
  104. register uint32_t *p = state;
  105. register int i;
  106. if (BG(mt_rand_mode) == MT_RAND_MT19937) {
  107. for (i = N - M; i--; ++p)
  108. *p = twist(p[M], p[0], p[1]);
  109. for (i = M; --i; ++p)
  110. *p = twist(p[M-N], p[0], p[1]);
  111. *p = twist(p[M-N], p[0], state[0]);
  112. }
  113. else {
  114. for (i = N - M; i--; ++p)
  115. *p = twist_php(p[M], p[0], p[1]);
  116. for (i = M; --i; ++p)
  117. *p = twist_php(p[M-N], p[0], p[1]);
  118. *p = twist_php(p[M-N], p[0], state[0]);
  119. }
  120. BG(left) = N;
  121. BG(next) = state;
  122. }
  123. /* }}} */
  124. /* {{{ php_mt_srand
  125. */
  126. PHPAPI void php_mt_srand(uint32_t seed)
  127. {
  128. /* Seed the generator with a simple uint32 */
  129. php_mt_initialize(seed, BG(state));
  130. php_mt_reload();
  131. /* Seed only once */
  132. BG(mt_rand_is_seeded) = 1;
  133. }
  134. /* }}} */
  135. /* {{{ php_mt_rand
  136. */
  137. PHPAPI uint32_t php_mt_rand(void)
  138. {
  139. /* Pull a 32-bit integer from the generator state
  140. Every other access function simply transforms the numbers extracted here */
  141. register uint32_t s1;
  142. if (UNEXPECTED(!BG(mt_rand_is_seeded))) {
  143. php_mt_srand(GENERATE_SEED());
  144. }
  145. if (BG(left) == 0) {
  146. php_mt_reload();
  147. }
  148. --BG(left);
  149. s1 = *BG(next)++;
  150. s1 ^= (s1 >> 11);
  151. s1 ^= (s1 << 7) & 0x9d2c5680U;
  152. s1 ^= (s1 << 15) & 0xefc60000U;
  153. return ( s1 ^ (s1 >> 18) );
  154. }
  155. /* }}} */
  156. /* {{{ proto void mt_srand([int seed])
  157. Seeds Mersenne Twister random number generator */
  158. PHP_FUNCTION(mt_srand)
  159. {
  160. zend_long seed = 0;
  161. zend_long mode = MT_RAND_MT19937;
  162. ZEND_PARSE_PARAMETERS_START(0, 2)
  163. Z_PARAM_OPTIONAL
  164. Z_PARAM_LONG(seed)
  165. Z_PARAM_LONG(mode)
  166. ZEND_PARSE_PARAMETERS_END();
  167. if (ZEND_NUM_ARGS() == 0)
  168. seed = GENERATE_SEED();
  169. switch (mode) {
  170. case MT_RAND_PHP:
  171. BG(mt_rand_mode) = MT_RAND_PHP;
  172. break;
  173. default:
  174. BG(mt_rand_mode) = MT_RAND_MT19937;
  175. }
  176. php_mt_srand(seed);
  177. }
  178. /* }}} */
  179. static uint32_t rand_range32(uint32_t umax) {
  180. uint32_t result, limit;
  181. result = php_mt_rand();
  182. /* Special case where no modulus is required */
  183. if (UNEXPECTED(umax == UINT32_MAX)) {
  184. return result;
  185. }
  186. /* Increment the max so the range is inclusive of max */
  187. umax++;
  188. /* Powers of two are not biased */
  189. if ((umax & (umax - 1)) == 0) {
  190. return result & (umax - 1);
  191. }
  192. /* Ceiling under which UINT32_MAX % max == 0 */
  193. limit = UINT32_MAX - (UINT32_MAX % umax) - 1;
  194. /* Discard numbers over the limit to avoid modulo bias */
  195. while (UNEXPECTED(result > limit)) {
  196. result = php_mt_rand();
  197. }
  198. return result % umax;
  199. }
  200. #if ZEND_ULONG_MAX > UINT32_MAX
  201. static uint64_t rand_range64(uint64_t umax) {
  202. uint64_t result, limit;
  203. result = php_mt_rand();
  204. result = (result << 32) | php_mt_rand();
  205. /* Special case where no modulus is required */
  206. if (UNEXPECTED(umax == UINT64_MAX)) {
  207. return result;
  208. }
  209. /* Increment the max so the range is inclusive of max */
  210. umax++;
  211. /* Powers of two are not biased */
  212. if ((umax & (umax - 1)) == 0) {
  213. return result & (umax - 1);
  214. }
  215. /* Ceiling under which UINT64_MAX % max == 0 */
  216. limit = UINT64_MAX - (UINT64_MAX % umax) - 1;
  217. /* Discard numbers over the limit to avoid modulo bias */
  218. while (UNEXPECTED(result > limit)) {
  219. result = php_mt_rand();
  220. result = (result << 32) | php_mt_rand();
  221. }
  222. return result % umax;
  223. }
  224. #endif
  225. /* {{{ php_mt_rand_range
  226. */
  227. PHPAPI zend_long php_mt_rand_range(zend_long min, zend_long max)
  228. {
  229. zend_ulong umax = max - min;
  230. #if ZEND_ULONG_MAX > UINT32_MAX
  231. if (umax > UINT32_MAX) {
  232. return (zend_long) (rand_range64(umax) + min);
  233. }
  234. #endif
  235. return (zend_long) (rand_range32(umax) + min);
  236. }
  237. /* }}} */
  238. /* {{{ php_mt_rand_common
  239. * rand() allows min > max, mt_rand does not */
  240. PHPAPI zend_long php_mt_rand_common(zend_long min, zend_long max)
  241. {
  242. int64_t n;
  243. if (BG(mt_rand_mode) == MT_RAND_MT19937) {
  244. return php_mt_rand_range(min, max);
  245. }
  246. /* Legacy mode deliberately not inside php_mt_rand_range()
  247. * to prevent other functions being affected */
  248. n = (int64_t)php_mt_rand() >> 1;
  249. RAND_RANGE_BADSCALING(n, min, max, PHP_MT_RAND_MAX);
  250. return n;
  251. }
  252. /* }}} */
  253. /* {{{ proto int mt_rand([int min, int max])
  254. Returns a random number from Mersenne Twister */
  255. PHP_FUNCTION(mt_rand)
  256. {
  257. zend_long min;
  258. zend_long max;
  259. int argc = ZEND_NUM_ARGS();
  260. if (argc == 0) {
  261. // genrand_int31 in mt19937ar.c performs a right shift
  262. RETURN_LONG(php_mt_rand() >> 1);
  263. }
  264. ZEND_PARSE_PARAMETERS_START(2, 2)
  265. Z_PARAM_LONG(min)
  266. Z_PARAM_LONG(max)
  267. ZEND_PARSE_PARAMETERS_END();
  268. if (UNEXPECTED(max < min)) {
  269. zend_argument_value_error(2, "must be greater than or equal to argument #1 ($min)");
  270. RETURN_THROWS();
  271. }
  272. RETURN_LONG(php_mt_rand_common(min, max));
  273. }
  274. /* }}} */
  275. /* {{{ proto int mt_getrandmax(void)
  276. Returns the maximum value a random number from Mersenne Twister can have */
  277. PHP_FUNCTION(mt_getrandmax)
  278. {
  279. ZEND_PARSE_PARAMETERS_NONE();
  280. /*
  281. * Melo: it could be 2^^32 but we only use 2^^31 to maintain
  282. * compatibility with the previous php_rand
  283. */
  284. RETURN_LONG(PHP_MT_RAND_MAX); /* 2^^31 */
  285. }
  286. /* }}} */
  287. PHP_MINIT_FUNCTION(mt_rand)
  288. {
  289. REGISTER_LONG_CONSTANT("MT_RAND_MT19937", MT_RAND_MT19937, CONST_CS | CONST_PERSISTENT);
  290. REGISTER_LONG_CONSTANT("MT_RAND_PHP", MT_RAND_PHP, CONST_CS | CONST_PERSISTENT);
  291. return SUCCESS;
  292. }