PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/random.c

https://github.com/nazy/ruby
C | 1296 lines | 986 code | 116 blank | 194 comment | 170 complexity | 107ae8052dd2e18093aaa804838b445a MD5 | raw file
Possible License(s): GPL-2.0, BSD-3-Clause, AGPL-3.0, 0BSD, Unlicense
  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. /* These real versions are due to Isaku Wada, 2002/01/09 added */
  178. typedef struct {
  179. VALUE seed;
  180. struct MT mt;
  181. } rb_random_t;
  182. #define DEFAULT_SEED_CNT 4
  183. static rb_random_t default_rand;
  184. static VALUE rand_init(struct MT *mt, VALUE vseed);
  185. static VALUE random_seed(void);
  186. static rb_random_t *
  187. rand_start(rb_random_t *r)
  188. {
  189. struct MT *mt = &r->mt;
  190. if (!genrand_initialized(mt)) {
  191. r->seed = rand_init(mt, random_seed());
  192. }
  193. return r;
  194. }
  195. static struct MT *
  196. default_mt(void)
  197. {
  198. return &rand_start(&default_rand)->mt;
  199. }
  200. unsigned int
  201. rb_genrand_int32(void)
  202. {
  203. struct MT *mt = default_mt();
  204. return genrand_int32(mt);
  205. }
  206. double
  207. rb_genrand_real(void)
  208. {
  209. struct MT *mt = default_mt();
  210. return genrand_real(mt);
  211. }
  212. #define BDIGITS(x) (RBIGNUM_DIGITS(x))
  213. #define BITSPERDIG (SIZEOF_BDIGITS*CHAR_BIT)
  214. #define BIGRAD ((BDIGIT_DBL)1 << BITSPERDIG)
  215. #define DIGSPERINT (SIZEOF_INT/SIZEOF_BDIGITS)
  216. #define BIGUP(x) ((BDIGIT_DBL)(x) << BITSPERDIG)
  217. #define BIGDN(x) RSHIFT(x,BITSPERDIG)
  218. #define BIGLO(x) ((BDIGIT)((x) & (BIGRAD-1)))
  219. #define BDIGMAX ((BDIGIT)-1)
  220. #define roomof(n, m) (int)(((n)+(m)-1) / (m))
  221. #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
  222. #define SIZEOF_INT32 (31/CHAR_BIT + 1)
  223. static double
  224. int_pair_to_real_inclusive(unsigned int a, unsigned int b)
  225. {
  226. VALUE x = rb_big_new(roomof(64, BITSPERDIG), 1);
  227. VALUE m = rb_big_new(roomof(53, BITSPERDIG), 1);
  228. BDIGIT *xd = BDIGITS(x);
  229. int i = 0;
  230. double r;
  231. xd[i++] = (BDIGIT)b;
  232. #if BITSPERDIG < 32
  233. xd[i++] = (BDIGIT)(b >> BITSPERDIG);
  234. #endif
  235. xd[i++] = (BDIGIT)a;
  236. #if BITSPERDIG < 32
  237. xd[i++] = (BDIGIT)(a >> BITSPERDIG);
  238. #endif
  239. xd = BDIGITS(m);
  240. #if BITSPERDIG < 53
  241. MEMZERO(xd, BDIGIT, roomof(53, BITSPERDIG) - 1);
  242. #endif
  243. xd[53 / BITSPERDIG] = 1 << 53 % BITSPERDIG;
  244. xd[0] |= 1;
  245. x = rb_big_mul(x, m);
  246. if (FIXNUM_P(x)) {
  247. #if CHAR_BIT * SIZEOF_LONG > 64
  248. r = (double)(FIX2ULONG(x) >> 64);
  249. #else
  250. return 0.0;
  251. #endif
  252. }
  253. else {
  254. #if 64 % BITSPERDIG == 0
  255. long len = RBIGNUM_LEN(x);
  256. xd = BDIGITS(x);
  257. MEMMOVE(xd, xd + 64 / BITSPERDIG, BDIGIT, len - 64 / BITSPERDIG);
  258. MEMZERO(xd + len - 64 / BITSPERDIG, BDIGIT, 64 / BITSPERDIG);
  259. r = rb_big2dbl(x);
  260. #else
  261. x = rb_big_rshift(x, INT2FIX(64));
  262. if (FIXNUM_P(x)) {
  263. r = (double)FIX2ULONG(x);
  264. }
  265. else {
  266. r = rb_big2dbl(x);
  267. }
  268. #endif
  269. }
  270. return ldexp(r, -53);
  271. }
  272. VALUE rb_cRandom;
  273. #define id_minus '-'
  274. #define id_plus '+'
  275. static ID id_rand, id_bytes;
  276. /* :nodoc: */
  277. static void
  278. random_mark(void *ptr)
  279. {
  280. rb_gc_mark(((rb_random_t *)ptr)->seed);
  281. }
  282. static void
  283. random_free(void *ptr)
  284. {
  285. if (ptr != &default_rand)
  286. xfree(ptr);
  287. }
  288. static size_t
  289. random_memsize(const void *ptr)
  290. {
  291. return ptr ? sizeof(rb_random_t) : 0;
  292. }
  293. static const rb_data_type_t random_data_type = {
  294. "random",
  295. {
  296. random_mark,
  297. random_free,
  298. random_memsize,
  299. },
  300. };
  301. static rb_random_t *
  302. get_rnd(VALUE obj)
  303. {
  304. rb_random_t *ptr;
  305. TypedData_Get_Struct(obj, rb_random_t, &random_data_type, ptr);
  306. return ptr;
  307. }
  308. static rb_random_t *
  309. try_get_rnd(VALUE obj)
  310. {
  311. if (obj == rb_cRandom) {
  312. return rand_start(&default_rand);
  313. }
  314. if (!rb_typeddata_is_kind_of(obj, &random_data_type)) return NULL;
  315. return DATA_PTR(obj);
  316. }
  317. /* :nodoc: */
  318. static VALUE
  319. random_alloc(VALUE klass)
  320. {
  321. rb_random_t *rnd;
  322. VALUE obj = TypedData_Make_Struct(klass, rb_random_t, &random_data_type, rnd);
  323. rnd->seed = INT2FIX(0);
  324. return obj;
  325. }
  326. static VALUE
  327. rand_init(struct MT *mt, VALUE vseed)
  328. {
  329. volatile VALUE seed;
  330. long blen = 0;
  331. long fixnum_seed;
  332. int i, j, len;
  333. unsigned int buf0[SIZEOF_LONG / SIZEOF_INT32 * 4], *buf = buf0;
  334. seed = rb_to_int(vseed);
  335. switch (TYPE(seed)) {
  336. case T_FIXNUM:
  337. len = 1;
  338. fixnum_seed = FIX2LONG(seed);
  339. if (fixnum_seed < 0)
  340. fixnum_seed = -fixnum_seed;
  341. buf[0] = (unsigned int)(fixnum_seed & 0xffffffff);
  342. #if SIZEOF_LONG > SIZEOF_INT32
  343. if ((long)(int)fixnum_seed != fixnum_seed) {
  344. if ((buf[1] = (unsigned int)(fixnum_seed >> 32)) != 0) ++len;
  345. }
  346. #endif
  347. break;
  348. case T_BIGNUM:
  349. blen = RBIGNUM_LEN(seed);
  350. if (blen == 0) {
  351. len = 1;
  352. }
  353. else {
  354. if (blen > MT_MAX_STATE * SIZEOF_INT32 / SIZEOF_BDIGITS)
  355. blen = (len = MT_MAX_STATE) * SIZEOF_INT32 / SIZEOF_BDIGITS;
  356. len = roomof((int)blen * SIZEOF_BDIGITS, SIZEOF_INT32);
  357. }
  358. /* allocate ints for init_by_array */
  359. if (len > numberof(buf0)) buf = ALLOC_N(unsigned int, len);
  360. memset(buf, 0, len * sizeof(*buf));
  361. len = 0;
  362. for (i = (int)(blen-1); 0 <= i; i--) {
  363. j = i * SIZEOF_BDIGITS / SIZEOF_INT32;
  364. #if SIZEOF_BDIGITS < SIZEOF_INT32
  365. buf[j] <<= BITSPERDIG;
  366. #endif
  367. buf[j] |= RBIGNUM_DIGITS(seed)[i];
  368. if (!len && buf[j]) len = j;
  369. }
  370. ++len;
  371. break;
  372. default:
  373. rb_raise(rb_eTypeError, "failed to convert %s into Integer",
  374. rb_obj_classname(vseed));
  375. }
  376. if (len <= 1) {
  377. init_genrand(mt, buf[0]);
  378. }
  379. else {
  380. if (buf[len-1] == 1) /* remove leading-zero-guard */
  381. len--;
  382. init_by_array(mt, buf, len);
  383. }
  384. if (buf != buf0) xfree(buf);
  385. return seed;
  386. }
  387. /*
  388. * call-seq: Random.new([seed]) -> prng
  389. *
  390. * Creates new Mersenne Twister based pseudorandom number generator with
  391. * seed. When the argument seed is omitted, the generator is initialized
  392. * with Random.new_seed.
  393. *
  394. * The argument seed is used to ensure repeatable sequences of random numbers
  395. * between different runs of the program.
  396. *
  397. * prng = Random.new(1234)
  398. * [ prng.rand, prng.rand ] #=> [0.191519450378892, 0.622108771039832]
  399. * [ prng.integer(10), prng.integer(1000) ] #=> [4, 664]
  400. * prng = Random.new(1234)
  401. * [ prng.rand, prng.rand ] #=> [0.191519450378892, 0.622108771039832]
  402. */
  403. static VALUE
  404. random_init(int argc, VALUE *argv, VALUE obj)
  405. {
  406. VALUE vseed;
  407. rb_random_t *rnd = get_rnd(obj);
  408. if (argc == 0) {
  409. vseed = random_seed();
  410. }
  411. else {
  412. rb_scan_args(argc, argv, "01", &vseed);
  413. }
  414. rnd->seed = rand_init(&rnd->mt, vseed);
  415. return obj;
  416. }
  417. #define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int))
  418. #if defined(S_ISCHR) && !defined(DOSISH)
  419. # define USE_DEV_URANDOM 1
  420. #else
  421. # define USE_DEV_URANDOM 0
  422. #endif
  423. static void
  424. fill_random_seed(unsigned int seed[DEFAULT_SEED_CNT])
  425. {
  426. static int n = 0;
  427. struct timeval tv;
  428. #if USE_DEV_URANDOM
  429. int fd;
  430. struct stat statbuf;
  431. #elif defined(_WIN32)
  432. HCRYPTPROV prov;
  433. #endif
  434. memset(seed, 0, DEFAULT_SEED_LEN);
  435. #if USE_DEV_URANDOM
  436. if ((fd = open("/dev/urandom", O_RDONLY
  437. #ifdef O_NONBLOCK
  438. |O_NONBLOCK
  439. #endif
  440. #ifdef O_NOCTTY
  441. |O_NOCTTY
  442. #endif
  443. )) >= 0) {
  444. if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
  445. if (read(fd, seed, DEFAULT_SEED_LEN) < DEFAULT_SEED_LEN) {
  446. /* abandon */;
  447. }
  448. }
  449. close(fd);
  450. }
  451. #elif defined(_WIN32)
  452. if (CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
  453. CryptGenRandom(prov, DEFAULT_SEED_LEN, (void *)seed);
  454. CryptReleaseContext(prov, 0);
  455. }
  456. #endif
  457. gettimeofday(&tv, 0);
  458. seed[0] ^= tv.tv_usec;
  459. seed[1] ^= (unsigned int)tv.tv_sec;
  460. #if SIZEOF_TIME_T > SIZEOF_INT
  461. seed[0] ^= (unsigned int)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
  462. #endif
  463. seed[2] ^= getpid() ^ (n++ << 16);
  464. seed[3] ^= (unsigned int)(VALUE)&seed;
  465. #if SIZEOF_VOIDP > SIZEOF_INT
  466. seed[2] ^= (unsigned int)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
  467. #endif
  468. }
  469. static VALUE
  470. make_seed_value(const void *ptr)
  471. {
  472. const long len = DEFAULT_SEED_LEN/SIZEOF_BDIGITS;
  473. BDIGIT *digits;
  474. NEWOBJ(big, struct RBignum);
  475. OBJSETUP(big, rb_cBignum, T_BIGNUM);
  476. RBIGNUM_SET_SIGN(big, 1);
  477. rb_big_resize((VALUE)big, len + 1);
  478. digits = RBIGNUM_DIGITS(big);
  479. MEMCPY(digits, ptr, char, DEFAULT_SEED_LEN);
  480. /* set leading-zero-guard if need. */
  481. digits[len] =
  482. #if SIZEOF_INT32 / SIZEOF_BDIGITS > 1
  483. digits[len-2] <= 1 && digits[len-1] == 0
  484. #else
  485. digits[len-1] <= 1
  486. #endif
  487. ? 1 : 0;
  488. return rb_big_norm((VALUE)big);
  489. }
  490. /*
  491. * call-seq: Random.new_seed -> integer
  492. *
  493. * Returns arbitrary value for seed.
  494. */
  495. static VALUE
  496. random_seed(void)
  497. {
  498. unsigned int buf[DEFAULT_SEED_CNT];
  499. fill_random_seed(buf);
  500. return make_seed_value(buf);
  501. }
  502. /*
  503. * call-seq: prng.seed -> integer
  504. *
  505. * Returns the seed of the generator.
  506. */
  507. static VALUE
  508. random_get_seed(VALUE obj)
  509. {
  510. return get_rnd(obj)->seed;
  511. }
  512. /* :nodoc: */
  513. static VALUE
  514. random_copy(VALUE obj, VALUE orig)
  515. {
  516. rb_random_t *rnd1 = get_rnd(obj);
  517. rb_random_t *rnd2 = get_rnd(orig);
  518. struct MT *mt = &rnd1->mt;
  519. *rnd1 = *rnd2;
  520. mt->next = mt->state + numberof(mt->state) - mt->left + 1;
  521. return obj;
  522. }
  523. static VALUE
  524. mt_state(const struct MT *mt)
  525. {
  526. VALUE bigo = rb_big_new(sizeof(mt->state) / sizeof(BDIGIT), 1);
  527. BDIGIT *d = RBIGNUM_DIGITS(bigo);
  528. int i;
  529. for (i = 0; i < numberof(mt->state); ++i) {
  530. unsigned int x = mt->state[i];
  531. #if SIZEOF_BDIGITS < SIZEOF_INT32
  532. int j;
  533. for (j = 0; j < SIZEOF_INT32 / SIZEOF_BDIGITS; ++j) {
  534. *d++ = BIGLO(x);
  535. x = BIGDN(x);
  536. }
  537. #else
  538. *d++ = (BDIGIT)x;
  539. #endif
  540. }
  541. return rb_big_norm(bigo);
  542. }
  543. /* :nodoc: */
  544. static VALUE
  545. random_state(VALUE obj)
  546. {
  547. rb_random_t *rnd = get_rnd(obj);
  548. return mt_state(&rnd->mt);
  549. }
  550. /* :nodoc: */
  551. static VALUE
  552. random_s_state(VALUE klass)
  553. {
  554. return mt_state(&default_rand.mt);
  555. }
  556. /* :nodoc: */
  557. static VALUE
  558. random_left(VALUE obj)
  559. {
  560. rb_random_t *rnd = get_rnd(obj);
  561. return INT2FIX(rnd->mt.left);
  562. }
  563. /* :nodoc: */
  564. static VALUE
  565. random_s_left(VALUE klass)
  566. {
  567. return INT2FIX(default_rand.mt.left);
  568. }
  569. /* :nodoc: */
  570. static VALUE
  571. random_dump(VALUE obj)
  572. {
  573. rb_random_t *rnd = get_rnd(obj);
  574. VALUE dump = rb_ary_new2(3);
  575. rb_ary_push(dump, mt_state(&rnd->mt));
  576. rb_ary_push(dump, INT2FIX(rnd->mt.left));
  577. rb_ary_push(dump, rnd->seed);
  578. return dump;
  579. }
  580. /* :nodoc: */
  581. static VALUE
  582. random_load(VALUE obj, VALUE dump)
  583. {
  584. rb_random_t *rnd = get_rnd(obj);
  585. struct MT *mt = &rnd->mt;
  586. VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
  587. VALUE *ary;
  588. unsigned long x;
  589. Check_Type(dump, T_ARRAY);
  590. ary = RARRAY_PTR(dump);
  591. switch (RARRAY_LEN(dump)) {
  592. case 3:
  593. seed = ary[2];
  594. case 2:
  595. left = ary[1];
  596. case 1:
  597. state = ary[0];
  598. break;
  599. default:
  600. rb_raise(rb_eArgError, "wrong dump data");
  601. }
  602. memset(mt->state, 0, sizeof(mt->state));
  603. if (FIXNUM_P(state)) {
  604. x = FIX2ULONG(state);
  605. mt->state[0] = (unsigned int)x;
  606. #if SIZEOF_LONG / SIZEOF_INT >= 2
  607. mt->state[1] = (unsigned int)(x >> BITSPERDIG);
  608. #endif
  609. #if SIZEOF_LONG / SIZEOF_INT >= 3
  610. mt->state[2] = (unsigned int)(x >> 2 * BITSPERDIG);
  611. #endif
  612. #if SIZEOF_LONG / SIZEOF_INT >= 4
  613. mt->state[3] = (unsigned int)(x >> 3 * BITSPERDIG);
  614. #endif
  615. }
  616. else {
  617. BDIGIT *d;
  618. long len;
  619. Check_Type(state, T_BIGNUM);
  620. len = RBIGNUM_LEN(state);
  621. if (len > roomof(sizeof(mt->state), SIZEOF_BDIGITS)) {
  622. len = roomof(sizeof(mt->state), SIZEOF_BDIGITS);
  623. }
  624. #if SIZEOF_BDIGITS < SIZEOF_INT
  625. else if (len % DIGSPERINT) {
  626. d = RBIGNUM_DIGITS(state) + len;
  627. # if DIGSPERINT == 2
  628. --len;
  629. x = *--d;
  630. # else
  631. x = 0;
  632. do {
  633. x = (x << BITSPERDIG) | *--d;
  634. } while (--len % DIGSPERINT);
  635. # endif
  636. mt->state[len / DIGSPERINT] = (unsigned int)x;
  637. }
  638. #endif
  639. if (len > 0) {
  640. d = BDIGITS(state) + len;
  641. do {
  642. --len;
  643. x = *--d;
  644. # if DIGSPERINT == 2
  645. --len;
  646. x = (x << BITSPERDIG) | *--d;
  647. # elif SIZEOF_BDIGITS < SIZEOF_INT
  648. do {
  649. x = (x << BITSPERDIG) | *--d;
  650. } while (--len % DIGSPERINT);
  651. # endif
  652. mt->state[len / DIGSPERINT] = (unsigned int)x;
  653. } while (len > 0);
  654. }
  655. }
  656. x = NUM2ULONG(left);
  657. if (x > numberof(mt->state)) {
  658. rb_raise(rb_eArgError, "wrong value");
  659. }
  660. mt->left = (unsigned int)x;
  661. mt->next = mt->state + numberof(mt->state) - x + 1;
  662. rnd->seed = rb_to_int(seed);
  663. return obj;
  664. }
  665. /*
  666. * call-seq:
  667. * srand(number=0) -> old_seed
  668. *
  669. * Seeds the pseudorandom number generator to the value of
  670. * <i>number</i>. If <i>number</i> is omitted
  671. * or zero, seeds the generator using a combination of the time, the
  672. * process id, and a sequence number. (This is also the behavior if
  673. * <code>Kernel::rand</code> is called without previously calling
  674. * <code>srand</code>, but without the sequence.) By setting the seed
  675. * to a known value, scripts can be made deterministic during testing.
  676. * The previous seed value is returned. Also see <code>Kernel::rand</code>.
  677. */
  678. static VALUE
  679. rb_f_srand(int argc, VALUE *argv, VALUE obj)
  680. {
  681. VALUE seed, old;
  682. rb_random_t *r = &default_rand;
  683. rb_secure(4);
  684. if (argc == 0) {
  685. seed = random_seed();
  686. }
  687. else {
  688. rb_scan_args(argc, argv, "01", &seed);
  689. }
  690. old = r->seed;
  691. r->seed = rand_init(&r->mt, seed);
  692. return old;
  693. }
  694. static unsigned long
  695. make_mask(unsigned long x)
  696. {
  697. x = x | x >> 1;
  698. x = x | x >> 2;
  699. x = x | x >> 4;
  700. x = x | x >> 8;
  701. x = x | x >> 16;
  702. #if 4 < SIZEOF_LONG
  703. x = x | x >> 32;
  704. #endif
  705. return x;
  706. }
  707. static unsigned long
  708. limited_rand(struct MT *mt, unsigned long limit)
  709. {
  710. /* mt must be initialized */
  711. int i;
  712. unsigned long val, mask;
  713. if (!limit) return 0;
  714. mask = make_mask(limit);
  715. retry:
  716. val = 0;
  717. for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
  718. if ((mask >> (i * 32)) & 0xffffffff) {
  719. val |= (unsigned long)genrand_int32(mt) << (i * 32);
  720. val &= mask;
  721. if (limit < val)
  722. goto retry;
  723. }
  724. }
  725. return val;
  726. }
  727. static VALUE
  728. limited_big_rand(struct MT *mt, struct RBignum *limit)
  729. {
  730. /* mt must be initialized */
  731. unsigned long mask, lim, rnd;
  732. struct RBignum *val;
  733. long i, len;
  734. int boundary;
  735. len = (RBIGNUM_LEN(limit) * SIZEOF_BDIGITS + 3) / 4;
  736. val = (struct RBignum *)rb_big_clone((VALUE)limit);
  737. RBIGNUM_SET_SIGN(val, 1);
  738. #if SIZEOF_BDIGITS == 2
  739. # define BIG_GET32(big,i) \
  740. (RBIGNUM_DIGITS(big)[(i)*2] | \
  741. ((i)*2+1 < RBIGNUM_LEN(big) ? \
  742. (RBIGNUM_DIGITS(big)[(i)*2+1] << 16) : \
  743. 0))
  744. # define BIG_SET32(big,i,d) \
  745. ((RBIGNUM_DIGITS(big)[(i)*2] = (d) & 0xffff), \
  746. ((i)*2+1 < RBIGNUM_LEN(big) ? \
  747. (RBIGNUM_DIGITS(big)[(i)*2+1] = (d) >> 16) : \
  748. 0))
  749. #else
  750. /* SIZEOF_BDIGITS == 4 */
  751. # define BIG_GET32(big,i) (RBIGNUM_DIGITS(big)[i])
  752. # define BIG_SET32(big,i,d) (RBIGNUM_DIGITS(big)[i] = (d))
  753. #endif
  754. retry:
  755. mask = 0;
  756. boundary = 1;
  757. for (i = len-1; 0 <= i; i--) {
  758. lim = BIG_GET32(limit, i);
  759. mask = mask ? 0xffffffff : make_mask(lim);
  760. if (mask) {
  761. rnd = genrand_int32(mt) & mask;
  762. if (boundary) {
  763. if (lim < rnd)
  764. goto retry;
  765. if (rnd < lim)
  766. boundary = 0;
  767. }
  768. }
  769. else {
  770. rnd = 0;
  771. }
  772. BIG_SET32(val, i, (BDIGIT)rnd);
  773. }
  774. return rb_big_norm((VALUE)val);
  775. }
  776. /*
  777. * Returns random unsigned long value in [0, _limit_].
  778. *
  779. * Note that _limit_ is included, and the range of the argument and the
  780. * return value depends on environments.
  781. */
  782. unsigned long
  783. rb_genrand_ulong_limited(unsigned long limit)
  784. {
  785. return limited_rand(default_mt(), limit);
  786. }
  787. unsigned int
  788. rb_random_int32(VALUE obj)
  789. {
  790. rb_random_t *rnd = try_get_rnd(obj);
  791. if (!rnd) {
  792. #if SIZEOF_LONG * CHAR_BIT > 32
  793. VALUE lim = ULONG2NUM(0x100000000);
  794. #elif defined HAVE_LONG_LONG
  795. VALUE lim = ULL2NUM((LONG_LONG)0xffffffff+1);
  796. #else
  797. VALUE lim = rb_big_plus(ULONG2NUM(0xffffffff), INT2FIX(1));
  798. #endif
  799. return (unsigned int)NUM2ULONG(rb_funcall2(obj, id_rand, 1, &lim));
  800. }
  801. return genrand_int32(&rnd->mt);
  802. }
  803. double
  804. rb_random_real(VALUE obj)
  805. {
  806. rb_random_t *rnd = try_get_rnd(obj);
  807. if (!rnd) {
  808. VALUE v = rb_funcall2(obj, id_rand, 0, 0);
  809. double d = NUM2DBL(v);
  810. if (d < 0.0 || d >= 1.0) {
  811. rb_raise(rb_eRangeError, "random number too big %g", d);
  812. }
  813. return d;
  814. }
  815. return genrand_real(&rnd->mt);
  816. }
  817. /*
  818. * call-seq: prng.bytes(size) -> prng
  819. *
  820. * Returns a random binary string. The argument size specified the length of
  821. * the result string.
  822. */
  823. static VALUE
  824. random_bytes(VALUE obj, VALUE len)
  825. {
  826. return rb_random_bytes(obj, NUM2LONG(rb_to_int(len)));
  827. }
  828. VALUE
  829. rb_random_bytes(VALUE obj, long n)
  830. {
  831. rb_random_t *rnd = try_get_rnd(obj);
  832. VALUE bytes;
  833. char *ptr;
  834. unsigned int r, i;
  835. if (!rnd) {
  836. VALUE len = LONG2NUM(n);
  837. return rb_funcall2(obj, id_bytes, 1, &len);
  838. }
  839. bytes = rb_str_new(0, n);
  840. ptr = RSTRING_PTR(bytes);
  841. for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
  842. r = genrand_int32(&rnd->mt);
  843. i = SIZEOF_INT32;
  844. do {
  845. *ptr++ = (char)r;
  846. r >>= CHAR_BIT;
  847. } while (--i);
  848. }
  849. if (n > 0) {
  850. r = genrand_int32(&rnd->mt);
  851. do {
  852. *ptr++ = (char)r;
  853. r >>= CHAR_BIT;
  854. } while (--n);
  855. }
  856. return bytes;
  857. }
  858. static VALUE
  859. range_values(VALUE vmax, VALUE *begp, int *exclp)
  860. {
  861. VALUE end, r;
  862. if (!rb_range_values(vmax, begp, &end, exclp)) return Qfalse;
  863. if (!rb_respond_to(end, id_minus)) return Qfalse;
  864. r = rb_funcall2(end, id_minus, 1, begp);
  865. if (NIL_P(r)) return Qfalse;
  866. return r;
  867. }
  868. static VALUE
  869. rand_int(struct MT *mt, VALUE vmax, int restrictive)
  870. {
  871. /* mt must be initialized */
  872. long max;
  873. unsigned long r;
  874. if (FIXNUM_P(vmax)) {
  875. max = FIX2LONG(vmax);
  876. if (!max) return Qnil;
  877. if (max < 0) {
  878. if (restrictive) return Qnil;
  879. max = -max;
  880. }
  881. r = limited_rand(mt, (unsigned long)max - 1);
  882. return ULONG2NUM(r);
  883. }
  884. else {
  885. VALUE ret;
  886. if (rb_bigzero_p(vmax)) return Qnil;
  887. if (!RBIGNUM_SIGN(vmax)) {
  888. if (restrictive) return Qnil;
  889. vmax = rb_big_clone(vmax);
  890. RBIGNUM_SET_SIGN(vmax, 1);
  891. }
  892. vmax = rb_big_minus(vmax, INT2FIX(1));
  893. if (FIXNUM_P(vmax)) {
  894. max = FIX2LONG(vmax);
  895. if (max == -1) return Qnil;
  896. r = limited_rand(mt, max);
  897. return LONG2NUM(r);
  898. }
  899. ret = limited_big_rand(mt, RBIGNUM(vmax));
  900. RB_GC_GUARD(vmax);
  901. return ret;
  902. }
  903. }
  904. static inline double
  905. float_value(VALUE v)
  906. {
  907. double x = RFLOAT_VALUE(v);
  908. if (isinf(x) || isnan(x)) {
  909. VALUE error = INT2FIX(EDOM);
  910. rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError));
  911. }
  912. return x;
  913. }
  914. /*
  915. * call-seq:
  916. * prng.rand -> float
  917. * prng.rand(limit) -> number
  918. *
  919. * When the argument is an +Integer+ or a +Bignum+, it returns a
  920. * random integer greater than or equal to zero and less than the
  921. * argument. Unlike Random.rand, when the argument is a negative
  922. * integer or zero, it raises an ArgumentError.
  923. *
  924. * When the argument is a +Float+, it returns a random floating point
  925. * number between 0.0 and _max_, including 0.0 and excluding _max_.
  926. *
  927. * When the argument _limit_ is a +Range+, it returns a random
  928. * number where range.member?(number) == true.
  929. * prng.rand(5..9) #=> one of [5, 6, 7, 8, 9]
  930. * prng.rand(5...9) #=> one of [5, 6, 7, 8]
  931. * prng.rand(5.0..9.0) #=> between 5.0 and 9.0, including 9.0
  932. * prng.rand(5.0...9.0) #=> between 5.0 and 9.0, excluding 9.0
  933. *
  934. * +begin+/+end+ of the range have to have subtract and add methods.
  935. *
  936. * Otherwise, it raises an ArgumentError.
  937. */
  938. static VALUE
  939. random_rand(int argc, VALUE *argv, VALUE obj)
  940. {
  941. rb_random_t *rnd = get_rnd(obj);
  942. VALUE vmax, beg = Qundef, v;
  943. int excl = 0;
  944. if (argc == 0) {
  945. return rb_float_new(genrand_real(&rnd->mt));
  946. }
  947. else if (argc != 1) {
  948. rb_raise(rb_eArgError, "wrong number of arguments (%d for 0..1)", argc);
  949. }
  950. vmax = argv[0];
  951. if (NIL_P(vmax)) {
  952. v = Qnil;
  953. }
  954. else if (TYPE(vmax) != T_FLOAT && (v = rb_check_to_integer(vmax, "to_int"), !NIL_P(v))) {
  955. v = rand_int(&rnd->mt, vmax = v, 1);
  956. }
  957. else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
  958. double max = float_value(v);
  959. if (max > 0.0)
  960. v = rb_float_new(max * genrand_real(&rnd->mt));
  961. else
  962. v = Qnil;
  963. }
  964. else if ((v = range_values(vmax, &beg, &excl)) != Qfalse) {
  965. vmax = v;
  966. if (TYPE(vmax) != T_FLOAT && (v = rb_check_to_integer(vmax, "to_int"), !NIL_P(v))) {
  967. long max;
  968. vmax = v;
  969. v = Qnil;
  970. if (FIXNUM_P(vmax)) {
  971. fixnum:
  972. if ((max = FIX2LONG(vmax) - excl) >= 0) {
  973. unsigned long r = limited_rand(&rnd->mt, (unsigned long)max);
  974. v = ULONG2NUM(r);
  975. }
  976. }
  977. else if (BUILTIN_TYPE(vmax) == T_BIGNUM && RBIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
  978. vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
  979. if (FIXNUM_P(vmax)) {
  980. excl = 0;
  981. goto fixnum;
  982. }
  983. v = limited_big_rand(&rnd->mt, RBIGNUM(vmax));
  984. }
  985. }
  986. else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
  987. double max = float_value(v), r;
  988. v = Qnil;
  989. if (max > 0.0) {
  990. if (excl) {
  991. r = genrand_real(&rnd->mt);
  992. }
  993. else {
  994. r = genrand_real2(&rnd->mt);
  995. }
  996. v = rb_float_new(r * max);
  997. }
  998. else if (max == 0.0 && !excl) {
  999. v = rb_float_new(0.0);
  1000. }
  1001. }
  1002. }
  1003. else {
  1004. v = Qnil;
  1005. (void)NUM2LONG(vmax);
  1006. }
  1007. if (NIL_P(v)) {
  1008. VALUE mesg = rb_str_new_cstr("invalid argument - ");
  1009. rb_str_append(mesg, rb_obj_as_string(argv[0]));
  1010. rb_exc_raise(rb_exc_new3(rb_eArgError, mesg));
  1011. }
  1012. if (beg == Qundef) return v;
  1013. if (FIXNUM_P(beg) && FIXNUM_P(v)) {
  1014. long x = FIX2LONG(beg) + FIX2LONG(v);
  1015. return LONG2NUM(x);
  1016. }
  1017. switch (TYPE(v)) {
  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. RFLOAT_VALUE(v) += RFLOAT_VALUE(f);
  1024. return v;
  1025. }
  1026. }
  1027. default:
  1028. return rb_funcall2(beg, id_plus, 1, &v);
  1029. }
  1030. }
  1031. /*
  1032. * call-seq:
  1033. * prng1 == prng2 -> true or false
  1034. *
  1035. * Returns true if the generators' states equal.
  1036. */
  1037. static VALUE
  1038. random_equal(VALUE self, VALUE other)
  1039. {
  1040. rb_random_t *r1, *r2;
  1041. if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
  1042. r1 = get_rnd(self);
  1043. r2 = get_rnd(other);
  1044. if (!RTEST(rb_funcall2(r1->seed, rb_intern("=="), 1, &r2->seed))) return Qfalse;
  1045. if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
  1046. if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
  1047. if (r1->mt.left != r2->mt.left) return Qfalse;
  1048. return Qtrue;
  1049. }
  1050. /*
  1051. * call-seq:
  1052. * rand(max=0) -> number
  1053. *
  1054. * Converts <i>max</i> to an integer using max1 =
  1055. * max<code>.to_i.abs</code>. If _max_ is +nil+ the result is zero, returns a
  1056. * pseudorandom floating point number greater than or equal to 0.0 and
  1057. * less than 1.0. Otherwise, returns a pseudorandom integer greater
  1058. * than or equal to zero and less than max1. <code>Kernel::srand</code>
  1059. * may be used to ensure repeatable sequences of random numbers between
  1060. * different runs of the program. Ruby currently uses a modified
  1061. * Mersenne Twister with a period of 2**19937-1.
  1062. *
  1063. * srand 1234 #=> 0
  1064. * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
  1065. * [ rand(10), rand(1000) ] #=> [6, 817]
  1066. * srand 1234 #=> 1234
  1067. * [ rand, rand ] #=> [0.191519450163469, 0.49766366626136]
  1068. */
  1069. static VALUE
  1070. rb_f_rand(int argc, VALUE *argv, VALUE obj)
  1071. {
  1072. VALUE vmax, r;
  1073. struct MT *mt = default_mt();
  1074. if (argc == 0) goto zero_arg;
  1075. rb_scan_args(argc, argv, "01", &vmax);
  1076. if (NIL_P(vmax)) goto zero_arg;
  1077. vmax = rb_to_int(vmax);
  1078. if (vmax == INT2FIX(0) || NIL_P(r = rand_int(mt, vmax, 0))) {
  1079. zero_arg:
  1080. return DBL2NUM(genrand_real(mt));
  1081. }
  1082. return r;
  1083. }
  1084. static st_index_t hashseed;
  1085. static VALUE
  1086. init_randomseed(struct MT *mt, unsigned int initial[DEFAULT_SEED_CNT])
  1087. {
  1088. VALUE seed;
  1089. fill_random_seed(initial);
  1090. init_by_array(mt, initial, DEFAULT_SEED_CNT);
  1091. seed = make_seed_value(initial);
  1092. memset(initial, 0, DEFAULT_SEED_LEN);
  1093. return seed;
  1094. }
  1095. void
  1096. Init_RandomSeed(void)
  1097. {
  1098. rb_random_t *r = &default_rand;
  1099. unsigned int initial[DEFAULT_SEED_CNT];
  1100. struct MT *mt = &r->mt;
  1101. VALUE seed = init_randomseed(mt, initial);
  1102. hashseed = genrand_int32(mt);
  1103. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 4*8
  1104. hashseed <<= 32;
  1105. hashseed |= genrand_int32(mt);
  1106. #endif
  1107. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 8*8
  1108. hashseed <<= 32;
  1109. hashseed |= genrand_int32(mt);
  1110. #endif
  1111. #if SIZEOF_ST_INDEX_T*CHAR_BIT > 12*8
  1112. hashseed <<= 32;
  1113. hashseed |= genrand_int32(mt);
  1114. #endif
  1115. rb_global_variable(&r->seed);
  1116. r->seed = seed;
  1117. }
  1118. st_index_t
  1119. rb_hash_start(st_index_t h)
  1120. {
  1121. return st_hash_start(hashseed + h);
  1122. }
  1123. static void
  1124. Init_RandomSeed2(void)
  1125. {
  1126. VALUE seed = default_rand.seed;
  1127. if (RB_TYPE_P(seed, T_BIGNUM)) {
  1128. RBASIC(seed)->klass = rb_cBignum;
  1129. }
  1130. }
  1131. void
  1132. rb_reset_random_seed(void)
  1133. {
  1134. rb_random_t *r = &default_rand;
  1135. uninit_genrand(&r->mt);
  1136. r->seed = INT2FIX(0);
  1137. }
  1138. void
  1139. Init_Random(void)
  1140. {
  1141. Init_RandomSeed2();
  1142. rb_define_global_function("srand", rb_f_srand, -1);
  1143. rb_define_global_function("rand", rb_f_rand, -1);
  1144. rb_cRandom = rb_define_class("Random", rb_cObject);
  1145. rb_define_alloc_func(rb_cRandom, random_alloc);
  1146. rb_define_method(rb_cRandom, "initialize", random_init, -1);
  1147. rb_define_method(rb_cRandom, "rand", random_rand, -1);
  1148. rb_define_method(rb_cRandom, "bytes", random_bytes, 1);
  1149. rb_define_method(rb_cRandom, "seed", random_get_seed, 0);
  1150. rb_define_method(rb_cRandom, "initialize_copy", random_copy, 1);
  1151. rb_define_method(rb_cRandom, "marshal_dump", random_dump, 0);
  1152. rb_define_method(rb_cRandom, "marshal_load", random_load, 1);
  1153. rb_define_private_method(rb_cRandom, "state", random_state, 0);
  1154. rb_define_private_method(rb_cRandom, "left", random_left, 0);
  1155. rb_define_method(rb_cRandom, "==", random_equal, 1);
  1156. rb_define_const(rb_cRandom, "DEFAULT",
  1157. TypedData_Wrap_Struct(rb_cRandom, &random_data_type, &default_rand));
  1158. rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
  1159. rb_define_singleton_method(rb_cRandom, "rand", rb_f_rand, -1);
  1160. rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
  1161. rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
  1162. rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
  1163. id_rand = rb_intern("rand");
  1164. id_bytes = rb_intern("bytes");
  1165. }