PageRenderTime 75ms CodeModel.GetById 41ms RepoModel.GetById 0ms app.codeStats 0ms

/random.c

https://github.com/vuxuandung/ruby
C | 1486 lines | 1082 code | 132 blank | 272 comment | 178 complexity | ae7ccd2940377b87ef0c34251398b6c8 MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0, 0BSD
  1. /**********************************************************************
  2. random.c -
  3. $Author$
  4. created at: Fri Dec 24 16:39:21 JST 1993
  5. Copyright (C) 1993-2007 Yukihiro Matsumoto
  6. **********************************************************************/
  7. /*
  8. This is based on trimmed version of MT19937. To get the original version,
  9. contact <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html>.
  10. The original copyright notice follows.
  11. A C-program for MT19937, with initialization improved 2002/2/10.
  12. Coded by Takuji Nishimura and Makoto Matsumoto.
  13. This is a faster version by taking Shawn Cokus's optimization,
  14. Matthe Bellew's simplification, Isaku Wada's real version.
  15. Before using, initialize the state by using init_genrand(mt, seed)
  16. or init_by_array(mt, init_key, key_length).
  17. Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
  18. All rights reserved.
  19. Redistribution and use in source and binary forms, with or without
  20. modification, are permitted provided that the following conditions
  21. are met:
  22. 1. Redistributions of source code must retain the above copyright
  23. notice, this list of conditions and the following disclaimer.
  24. 2. Redistributions in binary form must reproduce the above copyright
  25. notice, this list of conditions and the following disclaimer in the
  26. documentation and/or other materials provided with the distribution.
  27. 3. The names of its contributors may not be used to endorse or promote
  28. products derived from this software without specific prior written
  29. permission.
  30. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  31. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  32. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  33. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  34. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  35. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  36. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  37. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  38. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  39. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  40. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  41. Any feedback is very welcome.
  42. http://www.math.keio.ac.jp/matumoto/emt.html
  43. email: matumoto@math.keio.ac.jp
  44. */
  45. #include "ruby/ruby.h"
  46. #include <limits.h>
  47. #ifdef HAVE_UNISTD_H
  48. #include <unistd.h>
  49. #endif
  50. #include <time.h>
  51. #include <sys/types.h>
  52. #include <sys/stat.h>
  53. #ifdef HAVE_FCNTL_H
  54. #include <fcntl.h>
  55. #endif
  56. #include <math.h>
  57. #include <errno.h>
  58. #ifdef _WIN32
  59. # if !defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0400
  60. # undef _WIN32_WINNT
  61. # define _WIN32_WINNT 0x400
  62. # undef __WINCRYPT_H__
  63. # endif
  64. #include <wincrypt.h>
  65. #endif
  66. typedef int int_must_be_32bit_at_least[sizeof(int) * CHAR_BIT < 32 ? -1 : 1];
  67. /* Period parameters */
  68. #define N 624
  69. #define M 397
  70. #define MATRIX_A 0x9908b0dfU /* constant vector a */
  71. #define UMASK 0x80000000U /* most significant w-r bits */
  72. #define LMASK 0x7fffffffU /* least significant r bits */
  73. #define MIXBITS(u,v) ( ((u) & UMASK) | ((v) & LMASK) )
  74. #define TWIST(u,v) ((MIXBITS((u),(v)) >> 1) ^ ((v)&1U ? MATRIX_A : 0U))
  75. enum {MT_MAX_STATE = N};
  76. struct MT {
  77. /* assume int is enough to store 32bits */
  78. unsigned int state[N]; /* the array for the state vector */
  79. unsigned int *next;
  80. int left;
  81. };
  82. #define genrand_initialized(mt) ((mt)->next != 0)
  83. #define uninit_genrand(mt) ((mt)->next = 0)
  84. /* initializes state[N] with a seed */
  85. static void
  86. init_genrand(struct MT *mt, unsigned int s)
  87. {
  88. int j;
  89. mt->state[0] = s & 0xffffffffU;
  90. for (j=1; j<N; j++) {
  91. mt->state[j] = (1812433253U * (mt->state[j-1] ^ (mt->state[j-1] >> 30)) + j);
  92. /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
  93. /* In the previous versions, MSBs of the seed affect */
  94. /* only MSBs of the array state[]. */
  95. /* 2002/01/09 modified by Makoto Matsumoto */
  96. mt->state[j] &= 0xffffffff; /* for >32 bit machines */
  97. }
  98. mt->left = 1;
  99. mt->next = mt->state + N;
  100. }
  101. /* initialize by an array with array-length */
  102. /* init_key is the array for initializing keys */
  103. /* key_length is its length */
  104. /* slight change for C++, 2004/2/26 */
  105. static void
  106. init_by_array(struct MT *mt, unsigned int init_key[], int key_length)
  107. {
  108. int i, j, k;
  109. init_genrand(mt, 19650218U);
  110. i=1; j=0;
  111. k = (N>key_length ? N : key_length);
  112. for (; k; k--) {
  113. mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1664525U))
  114. + init_key[j] + j; /* non linear */
  115. mt->state[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
  116. i++; j++;
  117. if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
  118. if (j>=key_length) j=0;
  119. }
  120. for (k=N-1; k; k--) {
  121. mt->state[i] = (mt->state[i] ^ ((mt->state[i-1] ^ (mt->state[i-1] >> 30)) * 1566083941U))
  122. - i; /* non linear */
  123. mt->state[i] &= 0xffffffffU; /* for WORDSIZE > 32 machines */
  124. i++;
  125. if (i>=N) { mt->state[0] = mt->state[N-1]; i=1; }
  126. }
  127. mt->state[0] = 0x80000000U; /* MSB is 1; assuring non-zero initial array */
  128. }
  129. static void
  130. next_state(struct MT *mt)
  131. {
  132. unsigned int *p = mt->state;
  133. int j;
  134. mt->left = N;
  135. mt->next = mt->state;
  136. for (j=N-M+1; --j; p++)
  137. *p = p[M] ^ TWIST(p[0], p[1]);
  138. for (j=M; --j; p++)
  139. *p = p[M-N] ^ TWIST(p[0], p[1]);
  140. *p = p[M-N] ^ TWIST(p[0], mt->state[0]);
  141. }
  142. /* generates a random number on [0,0xffffffff]-interval */
  143. static unsigned int
  144. genrand_int32(struct MT *mt)
  145. {
  146. /* mt must be initialized */
  147. unsigned int y;
  148. if (--mt->left <= 0) next_state(mt);
  149. y = *mt->next++;
  150. /* Tempering */
  151. y ^= (y >> 11);
  152. y ^= (y << 7) & 0x9d2c5680;
  153. y ^= (y << 15) & 0xefc60000;
  154. y ^= (y >> 18);
  155. return y;
  156. }
  157. /* generates a random number on [0,1) with 53-bit resolution*/
  158. static double
  159. genrand_real(struct MT *mt)
  160. {
  161. /* mt must be initialized */
  162. unsigned int a = genrand_int32(mt)>>5, b = genrand_int32(mt)>>6;
  163. return(a*67108864.0+b)*(1.0/9007199254740992.0);
  164. }
  165. /* generates a random number on [0,1] with 53-bit resolution*/
  166. static double int_pair_to_real_inclusive(unsigned int a, unsigned int b);
  167. static double
  168. genrand_real2(struct MT *mt)
  169. {
  170. /* mt must be initialized */
  171. unsigned int a = genrand_int32(mt), b = genrand_int32(mt);
  172. return int_pair_to_real_inclusive(a, b);
  173. }
  174. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  175. #undef N
  176. #undef M
  177. typedef struct {
  178. VALUE seed;
  179. struct MT mt;
  180. } rb_random_t;
  181. #define DEFAULT_SEED_CNT 4
  182. static rb_random_t default_rand;
  183. static VALUE rand_init(struct MT *mt, VALUE vseed);
  184. static VALUE random_seed(void);
  185. static rb_random_t *
  186. rand_start(rb_random_t *r)
  187. {
  188. struct MT *mt = &r->mt;
  189. if (!genrand_initialized(mt)) {
  190. r->seed = rand_init(mt, random_seed());
  191. }
  192. return r;
  193. }
  194. static struct MT *
  195. default_mt(void)
  196. {
  197. return &rand_start(&default_rand)->mt;
  198. }
  199. unsigned int
  200. rb_genrand_int32(void)
  201. {
  202. struct MT *mt = default_mt();
  203. return genrand_int32(mt);
  204. }
  205. double
  206. rb_genrand_real(void)
  207. {
  208. struct MT *mt = default_mt();
  209. return genrand_real(mt);
  210. }
  211. #define BDIGITS(x) (RBIGNUM_DIGITS(x))
  212. #define BITSPERDIG (SIZEOF_BDIGITS*CHAR_BIT)
  213. #define BIGRAD ((BDIGIT_DBL)1 << BITSPERDIG)
  214. #define DIGSPERINT (SIZEOF_INT/SIZEOF_BDIGITS)
  215. #define BIGUP(x) ((BDIGIT_DBL)(x) << BITSPERDIG)
  216. #define BIGDN(x) RSHIFT((x),BITSPERDIG)
  217. #define BIGLO(x) ((BDIGIT)((x) & (BIGRAD-1)))
  218. #define BDIGMAX ((BDIGIT)-1)
  219. #define roomof(n, m) (int)(((n)+(m)-1) / (m))
  220. #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
  221. #define SIZEOF_INT32 (31/CHAR_BIT + 1)
  222. static double
  223. int_pair_to_real_inclusive(unsigned int a, unsigned int b)
  224. {
  225. VALUE x = rb_big_new(roomof(64, BITSPERDIG), 1);
  226. VALUE m = rb_big_new(roomof(53, BITSPERDIG), 1);
  227. BDIGIT *xd = BDIGITS(x);
  228. int i = 0;
  229. double r;
  230. xd[i++] = (BDIGIT)b;
  231. #if BITSPERDIG < 32
  232. xd[i++] = (BDIGIT)(b >> BITSPERDIG);
  233. #endif
  234. xd[i++] = (BDIGIT)a;
  235. #if BITSPERDIG < 32
  236. xd[i++] = (BDIGIT)(a >> BITSPERDIG);
  237. #endif
  238. xd = BDIGITS(m);
  239. #if BITSPERDIG < 53
  240. MEMZERO(xd, BDIGIT, roomof(53, BITSPERDIG) - 1);
  241. #endif
  242. xd[53 / BITSPERDIG] = 1 << 53 % BITSPERDIG;
  243. xd[0] |= 1;
  244. x = rb_big_mul(x, m);
  245. if (FIXNUM_P(x)) {
  246. #if CHAR_BIT * SIZEOF_LONG > 64
  247. r = (double)(FIX2ULONG(x) >> 64);
  248. #else
  249. return 0.0;
  250. #endif
  251. }
  252. else {
  253. #if 64 % BITSPERDIG == 0
  254. long len = RBIGNUM_LEN(x);
  255. xd = BDIGITS(x);
  256. MEMMOVE(xd, xd + 64 / BITSPERDIG, BDIGIT, len - 64 / BITSPERDIG);
  257. MEMZERO(xd + len - 64 / BITSPERDIG, BDIGIT, 64 / BITSPERDIG);
  258. r = rb_big2dbl(x);
  259. #else
  260. x = rb_big_rshift(x, INT2FIX(64));
  261. if (FIXNUM_P(x)) {
  262. r = (double)FIX2ULONG(x);
  263. }
  264. else {
  265. r = rb_big2dbl(x);
  266. }
  267. #endif
  268. }
  269. return ldexp(r, -53);
  270. }
  271. VALUE rb_cRandom;
  272. #define id_minus '-'
  273. #define id_plus '+'
  274. static ID id_rand, id_bytes;
  275. /* :nodoc: */
  276. static void
  277. random_mark(void *ptr)
  278. {
  279. rb_gc_mark(((rb_random_t *)ptr)->seed);
  280. }
  281. static void
  282. random_free(void *ptr)
  283. {
  284. if (ptr != &default_rand)
  285. xfree(ptr);
  286. }
  287. static size_t
  288. random_memsize(const void *ptr)
  289. {
  290. return ptr ? sizeof(rb_random_t) : 0;
  291. }
  292. static const rb_data_type_t random_data_type = {
  293. "random",
  294. {
  295. random_mark,
  296. random_free,
  297. random_memsize,
  298. },
  299. };
  300. static rb_random_t *
  301. get_rnd(VALUE obj)
  302. {
  303. rb_random_t *ptr;
  304. TypedData_Get_Struct(obj, rb_random_t, &random_data_type, ptr);
  305. return ptr;
  306. }
  307. static rb_random_t *
  308. try_get_rnd(VALUE obj)
  309. {
  310. if (obj == rb_cRandom) {
  311. return rand_start(&default_rand);
  312. }
  313. if (!rb_typeddata_is_kind_of(obj, &random_data_type)) return NULL;
  314. return DATA_PTR(obj);
  315. }
  316. /* :nodoc: */
  317. static VALUE
  318. random_alloc(VALUE klass)
  319. {
  320. rb_random_t *rnd;
  321. VALUE obj = TypedData_Make_Struct(klass, rb_random_t, &random_data_type, rnd);
  322. rnd->seed = INT2FIX(0);
  323. return obj;
  324. }
  325. static VALUE
  326. rand_init(struct MT *mt, VALUE vseed)
  327. {
  328. volatile VALUE seed;
  329. long blen = 0;
  330. long fixnum_seed;
  331. int i, j, len;
  332. unsigned int buf0[SIZEOF_LONG / SIZEOF_INT32 * 4], *buf = buf0;
  333. seed = rb_to_int(vseed);
  334. switch (TYPE(seed)) {
  335. case T_FIXNUM:
  336. len = 1;
  337. fixnum_seed = FIX2LONG(seed);
  338. if (fixnum_seed < 0)
  339. fixnum_seed = -fixnum_seed;
  340. buf[0] = (unsigned int)(fixnum_seed & 0xffffffff);
  341. #if SIZEOF_LONG > SIZEOF_INT32
  342. if ((long)(int32_t)fixnum_seed != fixnum_seed) {
  343. if ((buf[1] = (unsigned int)(fixnum_seed >> 32)) != 0) ++len;
  344. }
  345. #endif
  346. break;
  347. case T_BIGNUM:
  348. blen = RBIGNUM_LEN(seed);
  349. if (blen == 0) {
  350. len = 1;
  351. }
  352. else {
  353. if (blen > MT_MAX_STATE * SIZEOF_INT32 / SIZEOF_BDIGITS)
  354. blen = MT_MAX_STATE * SIZEOF_INT32 / SIZEOF_BDIGITS;
  355. len = roomof((int)blen * SIZEOF_BDIGITS, SIZEOF_INT32);
  356. }
  357. /* allocate ints for init_by_array */
  358. if (len > numberof(buf0)) buf = ALLOC_N(unsigned int, len);
  359. memset(buf, 0, len * sizeof(*buf));
  360. len = 0;
  361. for (i = (int)(blen-1); 0 <= i; i--) {
  362. j = i * SIZEOF_BDIGITS / SIZEOF_INT32;
  363. #if SIZEOF_BDIGITS < SIZEOF_INT32
  364. buf[j] <<= BITSPERDIG;
  365. #endif
  366. buf[j] |= RBIGNUM_DIGITS(seed)[i];
  367. if (!len && buf[j]) len = j;
  368. }
  369. ++len;
  370. break;
  371. default:
  372. rb_raise(rb_eTypeError, "failed to convert %s into Integer",
  373. rb_obj_classname(vseed));
  374. }
  375. if (len <= 1) {
  376. init_genrand(mt, buf[0]);
  377. }
  378. else {
  379. if (buf[len-1] == 1) /* remove leading-zero-guard */
  380. len--;
  381. init_by_array(mt, buf, len);
  382. }
  383. if (buf != buf0) xfree(buf);
  384. return seed;
  385. }
  386. /*
  387. * call-seq:
  388. * Random.new(seed = Random.new_seed) -> prng
  389. *
  390. * Creates a new PRNG using +seed+ to set the initial state. If +seed+ is
  391. * omitted, the generator is initialized with Random.new_seed.
  392. *
  393. * See Random.srand for more information on the use of seed values.
  394. */
  395. static VALUE
  396. random_init(int argc, VALUE *argv, VALUE obj)
  397. {
  398. VALUE vseed;
  399. rb_random_t *rnd = get_rnd(obj);
  400. if (argc == 0) {
  401. rb_check_frozen(obj);
  402. vseed = random_seed();
  403. }
  404. else {
  405. rb_scan_args(argc, argv, "01", &vseed);
  406. rb_check_copyable(obj, vseed);
  407. }
  408. rnd->seed = rand_init(&rnd->mt, vseed);
  409. return obj;
  410. }
  411. #define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int))
  412. #if defined(S_ISCHR) && !defined(DOSISH)
  413. # define USE_DEV_URANDOM 1
  414. #else
  415. # define USE_DEV_URANDOM 0
  416. #endif
  417. static void
  418. fill_random_seed(unsigned int seed[DEFAULT_SEED_CNT])
  419. {
  420. static int n = 0;
  421. struct timeval tv;
  422. #if USE_DEV_URANDOM
  423. int fd;
  424. struct stat statbuf;
  425. #elif defined(_WIN32)
  426. HCRYPTPROV prov;
  427. #endif
  428. memset(seed, 0, DEFAULT_SEED_LEN);
  429. #if USE_DEV_URANDOM
  430. if ((fd = rb_cloexec_open("/dev/urandom", O_RDONLY
  431. #ifdef O_NONBLOCK
  432. |O_NONBLOCK
  433. #endif
  434. #ifdef O_NOCTTY
  435. |O_NOCTTY
  436. #endif
  437. , 0)) >= 0) {
  438. rb_update_max_fd(fd);
  439. if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
  440. if (read(fd, seed, DEFAULT_SEED_LEN) < DEFAULT_SEED_LEN) {
  441. /* abandon */;
  442. }
  443. }
  444. close(fd);
  445. }
  446. #elif defined(_WIN32)
  447. if (CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
  448. CryptGenRandom(prov, DEFAULT_SEED_LEN, (void *)seed);
  449. CryptReleaseContext(prov, 0);
  450. }
  451. #endif
  452. gettimeofday(&tv, 0);
  453. seed[0] ^= tv.tv_usec;
  454. seed[1] ^= (unsigned int)tv.tv_sec;
  455. #if SIZEOF_TIME_T > SIZEOF_INT
  456. seed[0] ^= (unsigned int)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
  457. #endif
  458. seed[2] ^= getpid() ^ (n++ << 16);
  459. seed[3] ^= (unsigned int)(VALUE)&seed;
  460. #if SIZEOF_VOIDP > SIZEOF_INT
  461. seed[2] ^= (unsigned int)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
  462. #endif
  463. }
  464. static VALUE
  465. make_seed_value(const void *ptr)
  466. {
  467. const long len = DEFAULT_SEED_LEN/SIZEOF_BDIGITS;
  468. BDIGIT *digits;
  469. NEWOBJ_OF(big, struct RBignum, rb_cBignum, T_BIGNUM);
  470. RBIGNUM_SET_SIGN(big, 1);
  471. rb_big_resize((VALUE)big, len + 1);
  472. digits = RBIGNUM_DIGITS(big);
  473. MEMCPY(digits, ptr, char, DEFAULT_SEED_LEN);
  474. /* set leading-zero-guard if need. */
  475. digits[len] =
  476. #if SIZEOF_INT32 / SIZEOF_BDIGITS > 1
  477. digits[len-2] <= 1 && digits[len-1] == 0
  478. #else
  479. digits[len-1] <= 1
  480. #endif
  481. ? 1 : 0;
  482. return rb_big_norm((VALUE)big);
  483. }
  484. /*
  485. * call-seq: Random.new_seed -> integer
  486. *
  487. * Returns an arbitrary seed value. This is used by Random.new
  488. * when no seed value is specified as an argument.
  489. *
  490. * Random.new_seed #=> 115032730400174366788466674494640623225
  491. */
  492. static VALUE
  493. random_seed(void)
  494. {
  495. unsigned int buf[DEFAULT_SEED_CNT];
  496. fill_random_seed(buf);
  497. return make_seed_value(buf);
  498. }
  499. /*
  500. * call-seq: prng.seed -> integer
  501. *
  502. * Returns the seed value used to initialize the generator. This may be used to
  503. * initialize another generator with the same state at a later time, causing it
  504. * to produce the same sequence of numbers.
  505. *
  506. * prng1 = Random.new(1234)
  507. * prng1.seed #=> 1234
  508. * prng1.rand(100) #=> 47
  509. *
  510. * prng2 = Random.new(prng1.seed)
  511. * prng2.rand(100) #=> 47
  512. */
  513. static VALUE
  514. random_get_seed(VALUE obj)
  515. {
  516. return get_rnd(obj)->seed;
  517. }
  518. /* :nodoc: */
  519. static VALUE
  520. random_copy(VALUE obj, VALUE orig)
  521. {
  522. rb_random_t *rnd1, *rnd2;
  523. struct MT *mt;
  524. if (!OBJ_INIT_COPY(obj, orig)) return obj;
  525. rnd1 = get_rnd(obj);
  526. rnd2 = get_rnd(orig);
  527. mt = &rnd1->mt;
  528. *rnd1 = *rnd2;
  529. mt->next = mt->state + numberof(mt->state) - mt->left + 1;
  530. return obj;
  531. }
  532. static VALUE
  533. mt_state(const struct MT *mt)
  534. {
  535. VALUE bigo = rb_big_new(sizeof(mt->state) / sizeof(BDIGIT), 1);
  536. BDIGIT *d = RBIGNUM_DIGITS(bigo);
  537. int i;
  538. for (i = 0; i < numberof(mt->state); ++i) {
  539. unsigned int x = mt->state[i];
  540. #if SIZEOF_BDIGITS < SIZEOF_INT32
  541. int j;
  542. for (j = 0; j < SIZEOF_INT32 / SIZEOF_BDIGITS; ++j) {
  543. *d++ = BIGLO(x);
  544. x = BIGDN(x);
  545. }
  546. #else
  547. *d++ = (BDIGIT)x;
  548. #endif
  549. }
  550. return rb_big_norm(bigo);
  551. }
  552. /* :nodoc: */
  553. static VALUE
  554. random_state(VALUE obj)
  555. {
  556. rb_random_t *rnd = get_rnd(obj);
  557. return mt_state(&rnd->mt);
  558. }
  559. /* :nodoc: */
  560. static VALUE
  561. random_s_state(VALUE klass)
  562. {
  563. return mt_state(&default_rand.mt);
  564. }
  565. /* :nodoc: */
  566. static VALUE
  567. random_left(VALUE obj)
  568. {
  569. rb_random_t *rnd = get_rnd(obj);
  570. return INT2FIX(rnd->mt.left);
  571. }
  572. /* :nodoc: */
  573. static VALUE
  574. random_s_left(VALUE klass)
  575. {
  576. return INT2FIX(default_rand.mt.left);
  577. }
  578. /* :nodoc: */
  579. static VALUE
  580. random_dump(VALUE obj)
  581. {
  582. rb_random_t *rnd = get_rnd(obj);
  583. VALUE dump = rb_ary_new2(3);
  584. rb_ary_push(dump, mt_state(&rnd->mt));
  585. rb_ary_push(dump, INT2FIX(rnd->mt.left));
  586. rb_ary_push(dump, rnd->seed);
  587. return dump;
  588. }
  589. /* :nodoc: */
  590. static VALUE
  591. random_load(VALUE obj, VALUE dump)
  592. {
  593. rb_random_t *rnd = get_rnd(obj);
  594. struct MT *mt = &rnd->mt;
  595. VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
  596. VALUE *ary;
  597. unsigned long x;
  598. rb_check_copyable(obj, dump);
  599. Check_Type(dump, T_ARRAY);
  600. ary = RARRAY_PTR(dump);
  601. switch (RARRAY_LEN(dump)) {
  602. case 3:
  603. seed = ary[2];
  604. case 2:
  605. left = ary[1];
  606. case 1:
  607. state = ary[0];
  608. break;
  609. default:
  610. rb_raise(rb_eArgError, "wrong dump data");
  611. }
  612. memset(mt->state, 0, sizeof(mt->state));
  613. if (FIXNUM_P(state)) {
  614. x = FIX2ULONG(state);
  615. mt->state[0] = (unsigned int)x;
  616. #if SIZEOF_LONG / SIZEOF_INT >= 2
  617. mt->state[1] = (unsigned int)(x >> BITSPERDIG);
  618. #endif
  619. #if SIZEOF_LONG / SIZEOF_INT >= 3
  620. mt->state[2] = (unsigned int)(x >> 2 * BITSPERDIG);
  621. #endif
  622. #if SIZEOF_LONG / SIZEOF_INT >= 4
  623. mt->state[3] = (unsigned int)(x >> 3 * BITSPERDIG);
  624. #endif
  625. }
  626. else {
  627. BDIGIT *d;
  628. long len;
  629. Check_Type(state, T_BIGNUM);
  630. len = RBIGNUM_LEN(state);
  631. if (len > roomof(sizeof(mt->state), SIZEOF_BDIGITS)) {
  632. len = roomof(sizeof(mt->state), SIZEOF_BDIGITS);
  633. }
  634. #if SIZEOF_BDIGITS < SIZEOF_INT
  635. else if (len % DIGSPERINT) {
  636. d = RBIGNUM_DIGITS(state) + len;
  637. # if DIGSPERINT == 2
  638. --len;
  639. x = *--d;
  640. # else
  641. x = 0;
  642. do {
  643. x = (x << BITSPERDIG) | *--d;
  644. } while (--len % DIGSPERINT);
  645. # endif
  646. mt->state[len / DIGSPERINT] = (unsigned int)x;
  647. }
  648. #endif
  649. if (len > 0) {
  650. d = BDIGITS(state) + len;
  651. do {
  652. --len;
  653. x = *--d;
  654. # if DIGSPERINT == 2
  655. --len;
  656. x = (x << BITSPERDIG) | *--d;
  657. # elif SIZEOF_BDIGITS < SIZEOF_INT
  658. do {
  659. x = (x << BITSPERDIG) | *--d;
  660. } while (--len % DIGSPERINT);
  661. # endif
  662. mt->state[len / DIGSPERINT] = (unsigned int)x;
  663. } while (len > 0);
  664. }
  665. }
  666. x = NUM2ULONG(left);
  667. if (x > numberof(mt->state)) {
  668. rb_raise(rb_eArgError, "wrong value");
  669. }
  670. mt->left = (unsigned int)x;
  671. mt->next = mt->state + numberof(mt->state) - x + 1;
  672. rnd->seed = rb_to_int(seed);
  673. return obj;
  674. }
  675. /*
  676. * call-seq:
  677. * srand(number = Random.new_seed) -> old_seed
  678. *
  679. * Seeds the system pseudo-random number generator, Random::DEFAULT, with
  680. * +number+. The previous seed value is returned.
  681. *
  682. * If +number+ is omitted, seeds the generator using a source of entropy
  683. * provided by the operating system, if available (/dev/urandom on Unix systems
  684. * or the RSA cryptographic provider on Windows), which is then combined with
  685. * the time, the process id, and a sequence number.
  686. *
  687. * srand may be used to ensure repeatable sequences of pseudo-random numbers
  688. * between different runs of the program. By setting the seed to a known value,
  689. * programs can be made deterministic during testing.
  690. *
  691. * srand 1234 # => 268519324636777531569100071560086917274
  692. * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
  693. * [ rand(10), rand(1000) ] # => [4, 664]
  694. * srand 1234 # => 1234
  695. * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
  696. */
  697. static VALUE
  698. rb_f_srand(int argc, VALUE *argv, VALUE obj)
  699. {
  700. VALUE seed, old;
  701. rb_random_t *r = &default_rand;
  702. rb_secure(4);
  703. if (argc == 0) {
  704. seed = random_seed();
  705. }
  706. else {
  707. rb_scan_args(argc, argv, "01", &seed);
  708. }
  709. old = r->seed;
  710. r->seed = rand_init(&r->mt, seed);
  711. return old;
  712. }
  713. static unsigned long
  714. make_mask(unsigned long x)
  715. {
  716. x = x | x >> 1;
  717. x = x | x >> 2;
  718. x = x | x >> 4;
  719. x = x | x >> 8;
  720. x = x | x >> 16;
  721. #if 4 < SIZEOF_LONG
  722. x = x | x >> 32;
  723. #endif
  724. return x;
  725. }
  726. static unsigned long
  727. limited_rand(struct MT *mt, unsigned long limit)
  728. {
  729. /* mt must be initialized */
  730. int i;
  731. unsigned long val, mask;
  732. if (!limit) return 0;
  733. mask = make_mask(limit);
  734. retry:
  735. val = 0;
  736. for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
  737. if ((mask >> (i * 32)) & 0xffffffff) {
  738. val |= (unsigned long)genrand_int32(mt) << (i * 32);
  739. val &= mask;
  740. if (limit < val)
  741. goto retry;
  742. }
  743. }
  744. return val;
  745. }
  746. static VALUE
  747. limited_big_rand(struct MT *mt, struct RBignum *limit)
  748. {
  749. /* mt must be initialized */
  750. unsigned long mask, lim, rnd;
  751. struct RBignum *val;
  752. long i, len;
  753. int boundary;
  754. len = (RBIGNUM_LEN(limit) * SIZEOF_BDIGITS + 3) / 4;
  755. val = (struct RBignum *)rb_big_clone((VALUE)limit);
  756. RBIGNUM_SET_SIGN(val, 1);
  757. #if SIZEOF_BDIGITS == 2
  758. # define BIG_GET32(big,i) \
  759. (RBIGNUM_DIGITS(big)[(i)*2] | \
  760. ((i)*2+1 < RBIGNUM_LEN(big) ? \
  761. (RBIGNUM_DIGITS(big)[(i)*2+1] << 16) : \
  762. 0))
  763. # define BIG_SET32(big,i,d) \
  764. ((RBIGNUM_DIGITS(big)[(i)*2] = (d) & 0xffff), \
  765. ((i)*2+1 < RBIGNUM_LEN(big) ? \
  766. (RBIGNUM_DIGITS(big)[(i)*2+1] = (d) >> 16) : \
  767. 0))
  768. #else
  769. /* SIZEOF_BDIGITS == 4 */
  770. # define BIG_GET32(big,i) (RBIGNUM_DIGITS(big)[(i)])
  771. # define BIG_SET32(big,i,d) (RBIGNUM_DIGITS(big)[(i)] = (d))
  772. #endif
  773. retry:
  774. mask = 0;
  775. boundary = 1;
  776. for (i = len-1; 0 <= i; i--) {
  777. lim = BIG_GET32(limit, i);
  778. mask = mask ? 0xffffffff : make_mask(lim);
  779. if (mask) {
  780. rnd = genrand_int32(mt) & mask;
  781. if (boundary) {
  782. if (lim < rnd)
  783. goto retry;
  784. if (rnd < lim)
  785. boundary = 0;
  786. }
  787. }
  788. else {
  789. rnd = 0;
  790. }
  791. BIG_SET32(val, i, (BDIGIT)rnd);
  792. }
  793. return rb_big_norm((VALUE)val);
  794. }
  795. /*
  796. * Returns random unsigned long value in [0, +limit+].
  797. *
  798. * Note that +limit+ is included, and the range of the argument and the
  799. * return value depends on environments.
  800. */
  801. unsigned long
  802. rb_genrand_ulong_limited(unsigned long limit)
  803. {
  804. return limited_rand(default_mt(), limit);
  805. }
  806. unsigned int
  807. rb_random_int32(VALUE obj)
  808. {
  809. rb_random_t *rnd = try_get_rnd(obj);
  810. if (!rnd) {
  811. #if SIZEOF_LONG * CHAR_BIT > 32
  812. VALUE lim = ULONG2NUM(0x100000000UL);
  813. #elif defined HAVE_LONG_LONG
  814. VALUE lim = ULL2NUM((LONG_LONG)0xffffffff+1);
  815. #else
  816. VALUE lim = rb_big_plus(ULONG2NUM(0xffffffff), INT2FIX(1));
  817. #endif
  818. return (unsigned int)NUM2ULONG(rb_funcall2(obj, id_rand, 1, &lim));
  819. }
  820. return genrand_int32(&rnd->mt);
  821. }
  822. double
  823. rb_random_real(VALUE obj)
  824. {
  825. rb_random_t *rnd = try_get_rnd(obj);
  826. if (!rnd) {
  827. VALUE v = rb_funcall2(obj, id_rand, 0, 0);
  828. double d = NUM2DBL(v);
  829. if (d < 0.0) {
  830. rb_raise(rb_eRangeError, "random number too small %g", d);
  831. }
  832. else if (d >= 1.0) {
  833. rb_raise(rb_eRangeError, "random number too big %g", d);
  834. }
  835. return d;
  836. }
  837. return genrand_real(&rnd->mt);
  838. }
  839. unsigned long
  840. rb_random_ulong_limited(VALUE obj, unsigned long limit)
  841. {
  842. rb_random_t *rnd = try_get_rnd(obj);
  843. if (!rnd) {
  844. VALUE lim = ULONG2NUM(limit);
  845. VALUE v = rb_funcall2(obj, id_rand, 1, &lim);
  846. unsigned long r = NUM2ULONG(v);
  847. if (r > limit) {
  848. rb_raise(rb_eRangeError, "random number too big %ld", r);
  849. }
  850. return r;
  851. }
  852. return limited_rand(&rnd->mt, limit);
  853. }
  854. /*
  855. * call-seq: prng.bytes(size) -> a_string
  856. *
  857. * Returns a random binary string containing +size+ bytes.
  858. *
  859. * random_string = Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
  860. * random_string.size # => 10
  861. */
  862. static VALUE
  863. random_bytes(VALUE obj, VALUE len)
  864. {
  865. return rb_random_bytes(obj, NUM2LONG(rb_to_int(len)));
  866. }
  867. VALUE
  868. rb_random_bytes(VALUE obj, long n)
  869. {
  870. rb_random_t *rnd = try_get_rnd(obj);
  871. VALUE bytes;
  872. char *ptr;
  873. unsigned int r, i;
  874. if (!rnd) {
  875. VALUE len = LONG2NUM(n);
  876. return rb_funcall2(obj, id_bytes, 1, &len);
  877. }
  878. bytes = rb_str_new(0, n);
  879. ptr = RSTRING_PTR(bytes);
  880. for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
  881. r = genrand_int32(&rnd->mt);
  882. i = SIZEOF_INT32;
  883. do {
  884. *ptr++ = (char)r;
  885. r >>= CHAR_BIT;
  886. } while (--i);
  887. }
  888. if (n > 0) {
  889. r = genrand_int32(&rnd->mt);
  890. do {
  891. *ptr++ = (char)r;
  892. r >>= CHAR_BIT;
  893. } while (--n);
  894. }
  895. return bytes;
  896. }
  897. static VALUE
  898. range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp)
  899. {
  900. VALUE end, r;
  901. if (!rb_range_values(vmax, begp, &end, exclp)) return Qfalse;
  902. if (endp) *endp = end;
  903. if (!rb_respond_to(end, id_minus)) return Qfalse;
  904. r = rb_funcall2(end, id_minus, 1, begp);
  905. if (NIL_P(r)) return Qfalse;
  906. return r;
  907. }
  908. static VALUE
  909. rand_int(struct MT *mt, VALUE vmax, int restrictive)
  910. {
  911. /* mt must be initialized */
  912. long max;
  913. unsigned long r;
  914. if (FIXNUM_P(vmax)) {
  915. max = FIX2LONG(vmax);
  916. if (!max) return Qnil;
  917. if (max < 0) {
  918. if (restrictive) return Qnil;
  919. max = -max;
  920. }
  921. r = limited_rand(mt, (unsigned long)max - 1);
  922. return ULONG2NUM(r);
  923. }
  924. else {
  925. VALUE ret;
  926. if (rb_bigzero_p(vmax)) return Qnil;
  927. if (!RBIGNUM_SIGN(vmax)) {
  928. if (restrictive) return Qnil;
  929. vmax = rb_big_clone(vmax);
  930. RBIGNUM_SET_SIGN(vmax, 1);
  931. }
  932. vmax = rb_big_minus(vmax, INT2FIX(1));
  933. if (FIXNUM_P(vmax)) {
  934. max = FIX2LONG(vmax);
  935. if (max == -1) return Qnil;
  936. r = limited_rand(mt, max);
  937. return LONG2NUM(r);
  938. }
  939. ret = limited_big_rand(mt, RBIGNUM(vmax));
  940. RB_GC_GUARD(vmax);
  941. return ret;
  942. }
  943. }
  944. static inline double
  945. float_value(VALUE v)
  946. {
  947. double x = RFLOAT_VALUE(v);
  948. if (isinf(x) || isnan(x)) {
  949. VALUE error = INT2FIX(EDOM);
  950. rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError));
  951. }
  952. return x;
  953. }
  954. static inline VALUE
  955. rand_range(struct MT* mt, VALUE range)
  956. {
  957. VALUE beg = Qundef, end = Qundef, vmax, v;
  958. int excl = 0;
  959. if ((v = vmax = range_values(range, &beg, &end, &excl)) == Qfalse)
  960. return Qfalse;
  961. if (!RB_TYPE_P(vmax, T_FLOAT) && (v = rb_check_to_integer(vmax, "to_int"), !NIL_P(v))) {
  962. long max;
  963. vmax = v;
  964. v = Qnil;
  965. if (FIXNUM_P(vmax)) {
  966. fixnum:
  967. if ((max = FIX2LONG(vmax) - excl) >= 0) {
  968. unsigned long r = limited_rand(mt, (unsigned long)max);
  969. v = ULONG2NUM(r);
  970. }
  971. }
  972. else if (BUILTIN_TYPE(vmax) == T_BIGNUM && RBIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
  973. vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
  974. if (FIXNUM_P(vmax)) {
  975. excl = 0;
  976. goto fixnum;
  977. }
  978. v = limited_big_rand(mt, RBIGNUM(vmax));
  979. }
  980. }
  981. else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
  982. int scale = 1;
  983. double max = RFLOAT_VALUE(v), mid = 0.5, r;
  984. if (isinf(max)) {
  985. double min = float_value(rb_to_float(beg)) / 2.0;
  986. max = float_value(rb_to_float(end)) / 2.0;
  987. scale = 2;
  988. mid = max + min;
  989. max -= min;
  990. }
  991. else {
  992. float_value(v);
  993. }
  994. v = Qnil;
  995. if (max > 0.0) {
  996. if (excl) {
  997. r = genrand_real(mt);
  998. }
  999. else {
  1000. r = genrand_real2(mt);
  1001. }
  1002. if (scale > 1) {
  1003. return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
  1004. }
  1005. v = rb_float_new(r * max);
  1006. }
  1007. else if (max == 0.0 && !excl) {
  1008. v = rb_float_new(0.0);
  1009. }
  1010. }
  1011. if (FIXNUM_P(beg) && FIXNUM_P(v)) {
  1012. long x = FIX2LONG(beg) + FIX2LONG(v);
  1013. return LONG2NUM(x);
  1014. }
  1015. switch (TYPE(v)) {
  1016. case T_NIL:
  1017. break;
  1018. case T_BIGNUM:
  1019. return rb_big_plus(v, beg);
  1020. case T_FLOAT: {
  1021. VALUE f = rb_check_to_float(beg);
  1022. if (!NIL_P(f)) {
  1023. return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f));
  1024. }
  1025. }
  1026. default:
  1027. return rb_funcall2(beg, id_plus, 1, &v);
  1028. }
  1029. return v;
  1030. }
  1031. static VALUE rand_random(int argc, VALUE *argv, rb_random_t *rnd);
  1032. /*
  1033. * call-seq:
  1034. * prng.rand -> float
  1035. * prng.rand(max) -> number
  1036. *
  1037. * When +max+ is an Integer, +rand+ returns a random integer greater than
  1038. * or equal to zero and less than +max+. Unlike Kernel.rand, when +max+
  1039. * is a negative integer or zero, +rand+ raises an ArgumentError.
  1040. *
  1041. * prng = Random.new
  1042. * prng.rand(100) # => 42
  1043. *
  1044. * When +max+ is a Float, +rand+ returns a random floating point number
  1045. * between 0.0 and +max+, including 0.0 and excluding +max+.
  1046. *
  1047. * prng.rand(1.5) # => 1.4600282860034115
  1048. *
  1049. * When +max+ is a Range, +rand+ returns a random number where
  1050. * range.member?(number) == true.
  1051. *
  1052. * prng.rand(5..9) # => one of [5, 6, 7, 8, 9]
  1053. * prng.rand(5...9) # => one of [5, 6, 7, 8]
  1054. * prng.rand(5.0..9.0) # => between 5.0 and 9.0, including 9.0
  1055. * prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0
  1056. *
  1057. * Both the beginning and ending values of the range must respond to subtract
  1058. * (<tt>-</tt>) and add (<tt>+</tt>)methods, or rand will raise an
  1059. * ArgumentError.
  1060. */
  1061. static VALUE
  1062. random_rand(int argc, VALUE *argv, VALUE obj)
  1063. {
  1064. return rand_random(argc, argv, get_rnd(obj));
  1065. }
  1066. static VALUE
  1067. rand_random(int argc, VALUE *argv, rb_random_t *rnd)
  1068. {
  1069. VALUE vmax, v;
  1070. if (argc == 0) {
  1071. return rb_float_new(genrand_real(&rnd->mt));
  1072. }
  1073. else {
  1074. rb_check_arity(argc, 0, 1);
  1075. }
  1076. vmax = argv[0];
  1077. if (NIL_P(vmax)) {
  1078. v = Qnil;
  1079. }
  1080. else if (!RB_TYPE_P(vmax, T_FLOAT) && (v = rb_check_to_integer(vmax, "to_int"), !NIL_P(v))) {
  1081. v = rand_int(&rnd->mt, v, 1);
  1082. }
  1083. else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
  1084. double max = float_value(v);
  1085. if (max > 0.0)
  1086. v = rb_float_new(max * genrand_real(&rnd->mt));
  1087. else
  1088. v = Qnil;
  1089. }
  1090. else if ((v = rand_range(&rnd->mt, vmax)) != Qfalse) {
  1091. /* nothing to do */
  1092. }
  1093. else {
  1094. v = Qnil;
  1095. (void)NUM2LONG(vmax);
  1096. }
  1097. if (NIL_P(v)) {
  1098. VALUE mesg = rb_str_new_cstr("invalid argument - ");
  1099. rb_str_append(mesg, rb_obj_as_string(argv[0]));
  1100. rb_exc_raise(rb_exc_new3(rb_eArgError, mesg));
  1101. }
  1102. return v;
  1103. }
  1104. /*
  1105. * call-seq:
  1106. * prng1 == prng2 -> true or false
  1107. *
  1108. * Returns true if the two generators have the same internal state, otherwise
  1109. * false. Equivalent generators will return the same sequence of
  1110. * pseudo-random numbers. Two generators will generally have the same state
  1111. * only if they were initialized with the same seed
  1112. *
  1113. * Random.new == Random.new # => false
  1114. * Random.new(1234) == Random.new(1234) # => true
  1115. *
  1116. * and have the same invocation history.
  1117. *
  1118. * prng1 = Random.new(1234)
  1119. * prng2 = Random.new(1234)
  1120. * prng1 == prng2 # => true
  1121. *
  1122. * prng1.rand # => 0.1915194503788923
  1123. * prng1 == prng2 # => false
  1124. *
  1125. * prng2.rand # => 0.1915194503788923
  1126. * prng1 == prng2 # => true
  1127. */
  1128. static VALUE
  1129. random_equal(VALUE self, VALUE other)
  1130. {
  1131. rb_random_t *r1, *r2;
  1132. if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
  1133. r1 = get_rnd(self);
  1134. r2 = get_rnd(other);
  1135. if (!RTEST(rb_funcall2(r1->seed, rb_intern("=="), 1, &r2->seed))) return Qfalse;
  1136. if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
  1137. if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
  1138. if (r1->mt.left != r2->mt.left) return Qfalse;
  1139. return Qtrue;
  1140. }
  1141. /*
  1142. * call-seq:
  1143. * rand(max=0) -> number
  1144. *
  1145. * If called without an argument, or if <tt>max.to_i.abs == 0</tt>, rand
  1146. * returns a pseudo-random floating point number between 0.0 and 1.0,
  1147. * including 0.0 and excluding 1.0.
  1148. *
  1149. * rand #=> 0.2725926052826416
  1150. *
  1151. * When <tt>max.abs</tt> is greater than or equal to 1, +rand+ returns a
  1152. * pseudo-random integer greater than or equal to 0 and less than
  1153. * <tt>max.to_i.abs</tt>.
  1154. *
  1155. * rand(100) #=> 12
  1156. *
  1157. * Negative or floating point values for +max+ are allowed, but may give
  1158. * surprising results.
  1159. *
  1160. * rand(-100) # => 87
  1161. * rand(-0.5) # => 0.8130921818028143
  1162. * rand(1.9) # equivalent to rand(1), which is always 0
  1163. *
  1164. * Kernel.srand may be used to ensure that sequences of random numbers are
  1165. * reproducible between different runs of a program.
  1166. *
  1167. * See also Random.rand.
  1168. */
  1169. static VALUE
  1170. rb_f_rand(int argc, VALUE *argv, VALUE obj)
  1171. {
  1172. VALUE v, vmax, r;
  1173. struct MT *mt = default_mt();
  1174. if (argc == 0) goto zero_arg;
  1175. rb_scan_args(argc, argv, "01", &vmax);
  1176. if (NIL_P(vmax)) goto zero_arg;
  1177. if ((v = rand_range(mt, vmax)) != Qfalse) {
  1178. return v;
  1179. }
  1180. vmax = rb_to_int(vmax);
  1181. if (vmax == INT2FIX(0) || NIL_P(r = rand_int(mt, vmax, 0))) {
  1182. zero_arg:
  1183. return DBL2NUM(genrand_real(mt));
  1184. }
  1185. return r;
  1186. }
  1187. /*
  1188. * call-seq:
  1189. * Random.rand -> float
  1190. * Random.rand(max) -> number
  1191. *
  1192. * Alias of Random::DEFAULT.rand.
  1193. */
  1194. static VALUE
  1195. random_s_rand(int argc, VALUE *argv, VALUE obj)
  1196. {
  1197. return rand_random(argc, argv, rand_start(&default_rand));
  1198. }
  1199. #define SIP_HASH_STREAMING 0
  1200. #define sip_hash24 ruby_sip_hash24
  1201. #if !defined _WIN32 && !defined BYTE_ORDER
  1202. # ifdef WORDS_BIGENDIAN
  1203. # define BYTE_ORDER BIG_ENDIAN
  1204. # else
  1205. # define BYTE_ORDER LITTLE_ENDIAN
  1206. # endif
  1207. # ifndef LITTLE_ENDIAN
  1208. # define LITTLE_ENDIAN 1234
  1209. # endif
  1210. # ifndef BIG_ENDIAN
  1211. # define BIG_ENDIAN 4321
  1212. # endif
  1213. #endif
  1214. #include "siphash.c"
  1215. static st_index_t hashseed;
  1216. static union {
  1217. uint8_t key[16];
  1218. uint32_t u32[(16 * sizeof(uint8_t) - 1) / sizeof(uint32_t)];
  1219. } sipseed;
  1220. static VALUE
  1221. init_randomseed(struct MT *mt, unsigned int initial[DEFAULT_SEED_CNT])
  1222. {
  1223. VALUE seed;
  1224. fill_random_seed(initial);
  1225. init_by_array(mt, initial, DEFAULT_SEED_CNT);
  1226. seed = make_seed_value(initial);
  1227. memset(initial, 0, DEFAULT_SEED_LEN);
  1228. return seed;
  1229. }
  1230. void
  1231. Init_RandomSeed(void)
  1232. {
  1233. rb_random_t *r = &default_rand;
  1234. unsigned int initial[DEFAULT_SEED_CNT];
  1235. struct MT *mt = &r->mt;
  1236. VALUE seed = init_randomseed(mt, initial);
  1237. int i;
  1238. hashseed = genrand_int32(mt);
  1239. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 4*8
  1240. hashseed <<= 32;
  1241. hashseed |= genrand_int32(mt);
  1242. #endif
  1243. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 8*8
  1244. hashseed <<= 32;
  1245. hashseed |= genrand_int32(mt);
  1246. #endif
  1247. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 12*8
  1248. hashseed <<= 32;
  1249. hashseed |= genrand_int32(mt);
  1250. #endif
  1251. for (i = 0; i < numberof(sipseed.u32); ++i)
  1252. sipseed.u32[i] = genrand_int32(mt);
  1253. rb_global_variable(&r->seed);
  1254. r->seed = seed;
  1255. }
  1256. st_index_t
  1257. rb_hash_start(st_index_t h)
  1258. {
  1259. return st_hash_start(hashseed + h);
  1260. }
  1261. st_index_t
  1262. rb_memhash(const void *ptr, long len)
  1263. {
  1264. sip_uint64_t h = sip_hash24(sipseed.key, ptr, len);
  1265. #ifdef HAVE_UINT64_T
  1266. return (st_index_t)h;
  1267. #else
  1268. return (st_index_t)(h.u32[0] ^ h.u32[1]);
  1269. #endif
  1270. }
  1271. static void
  1272. Init_RandomSeed2(void)
  1273. {
  1274. VALUE seed = default_rand.seed;
  1275. if (RB_TYPE_P(seed, T_BIGNUM)) {
  1276. RBASIC(seed)->klass = rb_cBignum;
  1277. }
  1278. }
  1279. void
  1280. rb_reset_random_seed(void)
  1281. {
  1282. rb_random_t *r = &default_rand;
  1283. uninit_genrand(&r->mt);
  1284. r->seed = INT2FIX(0);
  1285. }
  1286. /*
  1287. * Document-class: Random
  1288. *
  1289. * Random provides an interface to Ruby's pseudo-random number generator, or
  1290. * PRNG. The PRNG produces a deterministic sequence of bits which approximate
  1291. * true randomness. The sequence may be represented by integers, floats, or
  1292. * binary strings.
  1293. *
  1294. * The generator may be initialized with either a system-generated or
  1295. * user-supplied seed value by using Random.srand.
  1296. *
  1297. * The class method Random.rand provides the base functionality of Kernel.rand
  1298. * along with better handling of floating point values. These are both
  1299. * interfaces to Random::DEFAULT, the Ruby system PRNG.
  1300. *
  1301. * Random.new will create a new PRNG with a state independent of
  1302. * Random::DEFAULT, allowing multiple generators with different seed values or
  1303. * sequence positions to exist simultaneously. Random objects can be
  1304. * marshaled, allowing sequences to be saved and resumed.
  1305. *
  1306. * PRNGs are currently implemented as a modified Mersenne Twister with a period
  1307. * of 2**19937-1.
  1308. */
  1309. void
  1310. Init_Random(void)
  1311. {
  1312. Init_RandomSeed2();
  1313. rb_define_global_function("srand", rb_f_srand, -1);
  1314. rb_define_global_function("rand", rb_f_rand, -1);
  1315. rb_cRandom = rb_define_class("Random", rb_cObject);
  1316. rb_define_alloc_func(rb_cRandom, random_alloc);
  1317. rb_define_method(rb_cRandom, "initialize", random_init, -1);
  1318. rb_define_method(rb_cRandom, "rand", random_rand, -1);
  1319. rb_define_method(rb_cRandom, "bytes", random_bytes, 1);
  1320. rb_define_method(rb_cRandom, "seed", random_get_seed, 0);
  1321. rb_define_method(rb_cRandom, "initialize_copy", random_copy, 1);
  1322. rb_define_private_method(rb_cRandom, "marshal_dump", random_dump, 0);
  1323. rb_define_private_method(rb_cRandom, "marshal_load", random_load, 1);
  1324. rb_define_private_method(rb_cRandom, "state", random_state, 0);
  1325. rb_define_private_method(rb_cRandom, "left", random_left, 0);
  1326. rb_define_method(rb_cRandom, "==", random_equal, 1);
  1327. {
  1328. VALUE rand_default = TypedData_Wrap_Struct(rb_cRandom, &random_data_type, &default_rand);
  1329. rb_gc_register_mark_object(rand_default);
  1330. rb_define_const(rb_cRandom, "DEFAULT", rand_default);
  1331. }
  1332. rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
  1333. rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1);
  1334. rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
  1335. rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
  1336. rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
  1337. id_rand = rb_intern("rand");
  1338. id_bytes = rb_intern("bytes");
  1339. }