12#include "ruby/internal/config.h"
31#if defined(HAVE_SYS_TIME_H)
37#elif defined HAVE_SYS_SYSCALL_H
38# include <sys/syscall.h>
48#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
50# include <sys/param.h>
53#if defined HAVE_GETRANDOM || defined HAVE_GETENTROPY
54# if defined(HAVE_SYS_RANDOM_H)
55# include <sys/random.h>
57#elif defined __linux__ && defined __NR_getrandom
58# include <linux/random.h>
62# include <AvailabilityMacros.h>
66#include "internal/array.h"
67#include "internal/compilers.h"
68#include "internal/numeric.h"
69#include "internal/random.h"
70#include "internal/sanitizers.h"
71#include "internal/variable.h"
72#include "ruby_atomic.h"
76typedef int int_must_be_32bit_at_least[
sizeof(int) * CHAR_BIT < 32 ? -1 : 1];
78#include "missing/mt19937.c"
81static double int_pair_to_real_exclusive(uint32_t a, uint32_t b);
83genrand_real(
struct MT *mt)
86 unsigned int a = genrand_int32(mt), b = genrand_int32(mt);
87 return int_pair_to_real_exclusive(a, b);
90static const double dbl_reduce_scale =
92 / (double)(DBL_MANT_DIG > 2*31 ? (1ul<<31) : 1.0)
93 / (
double)(DBL_MANT_DIG > 1*31 ? (1ul<<31) : 1.0)
94 / (double)(1ul<<(DBL_MANT_DIG%31)));
97int_pair_to_real_exclusive(uint32_t a, uint32_t b)
99 static const int a_shift = DBL_MANT_DIG < 64 ?
100 (64-DBL_MANT_DIG)/2 : 0;
101 static const int b_shift = DBL_MANT_DIG < 64 ?
102 (65-DBL_MANT_DIG)/2 : 0;
105 return (a*(
double)(1ul<<(32-b_shift))+b)*dbl_reduce_scale;
109static double int_pair_to_real_inclusive(uint32_t a, uint32_t b);
112genrand_real2(
struct MT *mt)
115 uint32_t a = genrand_int32(mt), b = genrand_int32(mt);
116 return int_pair_to_real_inclusive(a, b);
130#define DEFAULT_SEED_CNT 4
133static VALUE random_seed(VALUE);
134static void fill_random_seed(uint32_t *seed,
size_t cnt);
135static VALUE make_seed_value(uint32_t *ptr,
size_t len);
139 DEFAULT_SEED_CNT * 32,
146 if (!genrand_initialized(&r->mt)) {
147 r->base.
seed = rand_init(&random_mt_if, &r->base, random_seed(
Qundef));
155 return &rand_mt_start(r)->base;
161default_rand_mark(
void *ptr)
188 return rand_mt_start(default_rand());
194 struct MT *mt = &default_mt()->mt;
195 return genrand_int32(mt);
201 struct MT *mt = &default_mt()->mt;
202 return genrand_real(mt);
205#define SIZEOF_INT32 (31/CHAR_BIT + 1)
208int_pair_to_real_inclusive(uint32_t a, uint32_t b)
211 enum {dig = DBL_MANT_DIG};
212 enum {dig_u = dig-32, dig_r64 = 64-dig, bmask = ~(~0u<<(dig_r64))};
213#if defined HAVE_UINT128_T
214 const uint128_t m = ((uint128_t)1 << dig) | 1;
215 uint128_t x = ((uint128_t)a << 32) | b;
216 r = (double)(uint64_t)((x * m) >> 64);
217#elif defined HAVE_UINT64_T && !MSC_VERSION_BEFORE(1300)
218 uint64_t x = ((uint64_t)a << dig_u) +
219 (((uint64_t)b + (a >> dig_u)) >> dig_r64);
223 b = (b >> dig_r64) + (((a >> dig_u) + (b & bmask)) >> dig_r64);
224 r = (double)a * (1 << dig_u) + b;
226 return r * dbl_reduce_scale;
232static ID id_rand, id_bytes;
233NORETURN(
static void domain_error(
void));
236#define random_mark rb_random_mark
239random_mark(
void *ptr)
244#define random_free RUBY_TYPED_DEFAULT_FREE
247random_memsize(
const void *ptr)
259 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
262#define random_mt_mark rb_random_mark
263#define random_mt_free RUBY_TYPED_DEFAULT_FREE
266random_mt_memsize(
const void *ptr)
279 (
void *)&random_mt_if,
280 RUBY_TYPED_FREE_IMMEDIATELY
302try_get_rnd(VALUE obj)
305 return rand_start(default_rand());
312 rb_raise(rb_eArgError,
"uninitialized random: %s",
321 if (rnd == &default_rand()->base) {
322 return &random_mt_if;
336random_alloc(VALUE klass)
347 VALUE seed, buf0 = 0;
349 uint32_t *buf =
ALLOCV_N(uint32_t, buf0, len+1);
351 fill_random_seed(buf, len);
352 rng->
init(rnd, buf, len);
353 seed = make_seed_value(buf, len);
354 explicit_bzero(buf, len *
sizeof(*buf));
368 if (len == 0) len = 1;
369 buf =
ALLOCV_N(uint32_t, buf0, len);
375 if (sign != 2 && buf[len-1] == 1)
378 rng->
init(rnd, buf, len);
379 explicit_bzero(buf, len *
sizeof(*buf));
394random_init(
int argc, VALUE *argv, VALUE obj)
400 rb_raise(rb_eTypeError,
"undefined random interface: %s",
406 rnd->
seed = rand_init_default(rng, rnd);
409 rnd->
seed = rand_init(rng, rnd, rb_to_int(argv[0]));
414#define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int32_t))
416#if defined(S_ISCHR) && !defined(DOSISH)
417# define USE_DEV_URANDOM 1
419# define USE_DEV_URANDOM 0
422#ifdef HAVE_GETENTROPY
423# define MAX_SEED_LEN_PER_READ 256
425fill_random_bytes_urandom(
void *seed,
size_t size)
427 unsigned char *p = (
unsigned char *)seed;
429 size_t len = size < MAX_SEED_LEN_PER_READ ? size : MAX_SEED_LEN_PER_READ;
430 if (getentropy(p, len) != 0) {
440fill_random_bytes_urandom(
void *seed,
size_t size)
459 if (fd < 0)
return -1;
461 if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
463 ret = read(fd, ((
char*)seed) + offset, size - offset);
468 offset += (size_t)ret;
469 }
while (offset < size);
475# define fill_random_bytes_urandom(seed, size) -1
478#if ! defined HAVE_GETRANDOM && defined __linux__ && defined __NR_getrandom
479# ifndef GRND_NONBLOCK
480# define GRND_NONBLOCK 0x0001
482# define getrandom(ptr, size, flags) \
483 (ssize_t)syscall(__NR_getrandom, (ptr), (size), (flags))
484# define HAVE_GETRANDOM 1
488#elif defined MAC_OS_X_VERSION_10_7 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
490# if defined MAC_OS_X_VERSION_10_10 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
491# include <CommonCrypto/CommonCryptoError.h>
492# include <CommonCrypto/CommonRandom.h>
493# define USE_COMMON_RANDOM 1
495# include <Security/SecRandom.h>
496# define USE_COMMON_RANDOM 0
500fill_random_bytes_syscall(
void *seed,
size_t size,
int unused)
503 int failed = CCRandomGenerateBytes(seed, size) != kCCSuccess;
505 int failed = SecRandomCopyBytes(kSecRandomDefault, size, seed) != errSecSuccess;
510# if USE_COMMON_RANDOM
513 CFStringRef s = SecCopyErrorMessageString(status, NULL);
514 const char *m = s ? CFStringGetCStringPtr(s, kCFStringEncodingUTF8) : NULL;
515 fprintf(stderr,
"SecRandomCopyBytes failed: %d: %s\n", status,
524#elif defined(HAVE_ARC4RANDOM_BUF)
526fill_random_bytes_syscall(
void *buf,
size_t size,
int unused)
528#if (defined(__OpenBSD__) && OpenBSD >= 201411) || \
529 (defined(__NetBSD__) && __NetBSD_Version__ >= 700000000) || \
530 (defined(__FreeBSD__) && __FreeBSD_version >= 1200079)
531 arc4random_buf(buf, size);
540# define DWORD_MAX (~(DWORD)0UL)
543# if defined(CRYPT_VERIFYCONTEXT)
544STATIC_ASSERT(sizeof_HCRYPTPROV,
sizeof(HCRYPTPROV) ==
sizeof(
size_t));
548static const HCRYPTPROV INVALID_HCRYPTPROV = (HCRYPTPROV)INVALID_HANDLE_VALUE;
551release_crypt(
void *p)
554 HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_SIZE_EXCHANGE(*ptr, INVALID_HCRYPTPROV);
555 if (prov && prov != INVALID_HCRYPTPROV) {
556 CryptReleaseContext(prov, 0);
561fill_random_bytes_crypt(
void *seed,
size_t size)
563 static HCRYPTPROV perm_prov;
564 HCRYPTPROV prov = perm_prov, old_prov;
566 if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
567 prov = INVALID_HCRYPTPROV;
569 old_prov = (HCRYPTPROV)ATOMIC_SIZE_CAS(perm_prov, 0, prov);
570 if (LIKELY(!old_prov)) {
571 if (prov != INVALID_HCRYPTPROV) {
572#undef RUBY_UNTYPED_DATA_WARNING
573#define RUBY_UNTYPED_DATA_WARNING 0
578 if (prov != INVALID_HCRYPTPROV) {
579 CryptReleaseContext(prov, 0);
584 if (prov == INVALID_HCRYPTPROV)
return -1;
586 DWORD n = (size > (size_t)DWORD_MAX) ? DWORD_MAX : (DWORD)size;
587 if (!CryptGenRandom(prov, n, seed))
return -1;
588 seed = (
char *)seed + n;
594# define fill_random_bytes_crypt(seed, size) -1
598fill_random_bytes_bcrypt(
void *seed,
size_t size)
601 ULONG n = (size > (size_t)ULONG_MAX) ? LONG_MAX : (ULONG)size;
602 if (BCryptGenRandom(NULL, seed, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG))
604 seed = (
char *)seed + n;
611fill_random_bytes_syscall(
void *seed,
size_t size,
int unused)
613 if (fill_random_bytes_bcrypt(seed, size) == 0)
return 0;
614 return fill_random_bytes_crypt(seed, size);
616#elif defined HAVE_GETRANDOM
618fill_random_bytes_syscall(
void *seed,
size_t size,
int need_secure)
620 static rb_atomic_t try_syscall = 1;
625 flags = GRND_NONBLOCK;
628 ssize_t ret = getrandom(((
char*)seed) + offset, size - offset, flags);
630 ATOMIC_SET(try_syscall, 0);
633 offset += (size_t)ret;
634 }
while (offset < size);
640# define fill_random_bytes_syscall(seed, size, need_secure) -1
644ruby_fill_random_bytes(
void *seed,
size_t size,
int need_secure)
646 int ret = fill_random_bytes_syscall(seed, size, need_secure);
647 if (ret == 0)
return ret;
648 return fill_random_bytes_urandom(seed, size);
651#define fill_random_bytes ruby_fill_random_bytes
655fill_random_seed(uint32_t *seed,
size_t cnt)
657 static rb_atomic_t n = 0;
658#if defined HAVE_CLOCK_GETTIME
660#elif defined HAVE_GETTIMEOFDAY
663 size_t len = cnt *
sizeof(*seed);
665 memset(seed, 0, len);
667 fill_random_bytes(seed, len, FALSE);
669#if defined HAVE_CLOCK_GETTIME
670 clock_gettime(CLOCK_REALTIME, &tv);
671 seed[0] ^= tv.tv_nsec;
672#elif defined HAVE_GETTIMEOFDAY
673 gettimeofday(&tv, 0);
674 seed[0] ^= tv.tv_usec;
676 seed[1] ^= (uint32_t)tv.tv_sec;
677#
if SIZEOF_TIME_T > SIZEOF_INT
678 seed[0] ^= (uint32_t)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
680 seed[2] ^= getpid() ^ (ATOMIC_FETCH_ADD(n, 1) << 16);
681 seed[3] ^= (uint32_t)(VALUE)&seed;
682#if SIZEOF_VOIDP > SIZEOF_INT
683 seed[2] ^= (uint32_t)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
688make_seed_value(uint32_t *ptr,
size_t len)
692 if (ptr[len-1] <= 1) {
703#define with_random_seed(size, add) \
704 for (uint32_t seedbuf[(size)+(add)], loop = (fill_random_seed(seedbuf, (size)), 1); \
705 loop; explicit_bzero(seedbuf, (size)*sizeof(seedbuf[0])), loop = 0)
719 with_random_seed(DEFAULT_SEED_CNT, 1) {
720 v = make_seed_value(seedbuf, DEFAULT_SEED_CNT);
742random_raw_seed(VALUE
self, VALUE size)
746 if (n == 0)
return buf;
748 rb_raise(rb_eRuntimeError,
"failed to get urandom");
767random_get_seed(VALUE obj)
769 return get_rnd(obj)->
seed;
774rand_mt_copy(VALUE obj, VALUE orig)
781 rnd1 = get_rnd_mt(obj);
782 rnd2 = get_rnd_mt(orig);
786 mt->next = mt->state + numberof(mt->state) - mt->left + 1;
791mt_state(
const struct MT *mt)
794 sizeof(*mt->state), 0,
800rand_mt_state(VALUE obj)
803 return mt_state(&rnd->mt);
808random_s_state(VALUE klass)
810 return mt_state(&default_rand()->mt);
815rand_mt_left(VALUE obj)
823random_s_left(VALUE klass)
825 return INT2FIX(default_rand()->mt.left);
830rand_mt_dump(VALUE obj)
844rand_mt_load(VALUE obj, VALUE dump)
847 struct MT *mt = &rnd->mt;
851 rb_check_copyable(obj, dump);
862 rb_raise(rb_eArgError,
"wrong dump data");
865 sizeof(*mt->state), 0,
868 if (x > numberof(mt->state)) {
869 rb_raise(rb_eArgError,
"wrong value");
871 mt->left = (
unsigned int)x;
872 mt->next = mt->state + numberof(mt->state) - x + 1;
873 rnd->base.
seed = rb_to_int(seed);
879rand_mt_init(
rb_random_t *rnd,
const uint32_t *buf,
size_t len)
883 init_genrand(mt, len ? buf[0] : 0);
886 init_by_array(mt, buf, (
int)len);
894 return genrand_int32(mt);
898rand_mt_get_bytes(
rb_random_t *rnd,
void *ptr,
size_t n)
927rb_f_srand(
int argc, VALUE *argv, VALUE obj)
933 seed = random_seed(obj);
936 seed = rb_to_int(argv[0]);
939 rand_init(&random_mt_if, &r->base, seed);
946make_mask(
unsigned long x)
963 unsigned long val, mask;
965 if (!limit)
return 0;
966 mask = make_mask(limit);
969 if (0xffffffff < limit) {
973 for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
974 if ((mask >> (i * 32)) & 0xffffffff) {
975 val |= (
unsigned long)rng->
get_int32(rnd) << (i * 32);
987 }
while (limit < val);
1001 uint32_t *tmp, *lim_array, *rnd_array;
1006 tmp =
ALLOCV_N(uint32_t, vtmp, len*2);
1008 rnd_array = tmp + len;
1015 for (i = len-1; 0 <= i; i--) {
1017 uint32_t lim = lim_array[i];
1018 mask = mask ? 0xffffffff : (uint32_t)make_mask(lim);
1047 return limited_rand(&random_mt_if, &mt->base, limit);
1051obj_random_bytes(VALUE obj,
void *p,
long n)
1059 rb_raise(rb_eRangeError,
"random data too short %ld", l);
1061 rb_raise(rb_eRangeError,
"random data too long %ld", l);
1078 obj_random_bytes(obj, &x,
sizeof(x));
1079 return (
unsigned int)x;
1081 return random_int32(try_rand_if(obj, rnd), rnd);
1090 uint32_t x[2] = {0, 0};
1091 obj_random_bytes(obj, x,
sizeof(x));
1098 a = random_int32(rng, rnd);
1099 b = random_int32(rng, rnd);
1108 return int_pair_to_real_exclusive(a, b);
1111 return int_pair_to_real_inclusive(a, b);
1123 rb_raise(rb_eRangeError,
"random number too small %g", d);
1125 else if (d >= 1.0) {
1126 rb_raise(rb_eRangeError,
"random number too big %g", d);
1130 return random_real(obj, rnd, TRUE);
1134ulong_to_num_plus_1(
unsigned long n)
1139 if (n >= ULONG_MAX) {
1147random_ulong_limited(VALUE obj,
rb_random_t *rnd,
unsigned long limit)
1149 if (!limit)
return 0;
1151 const int w =
sizeof(limit) * CHAR_BIT - nlz_long(limit);
1152 const int n = w > 32 ?
sizeof(
unsigned long) :
sizeof(uint32_t);
1153 const unsigned long mask = ~(~0UL << w);
1154 const unsigned long full =
1155 (size_t)n >=
sizeof(
unsigned long) ? ~0UL :
1156 ~(~0UL << n * CHAR_BIT);
1157 unsigned long val, bits = 0, rest = 0;
1160 union {uint32_t u32;
unsigned long ul;} buf;
1161 obj_random_bytes(obj, &buf, n);
1163 bits = (n ==
sizeof(uint32_t)) ? buf.u32 : buf.ul;
1169 }
while (limit < val);
1172 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1180 VALUE lim = ulong_to_num_plus_1(limit);
1183 if (rb_num_negative_p(v)) {
1184 rb_raise(rb_eRangeError,
"random number too small %ld", r);
1187 rb_raise(rb_eRangeError,
"random number too big %ld", r);
1191 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1195random_ulong_limited_big(VALUE obj,
rb_random_t *rnd, VALUE vmax)
1200 uint32_t *tmp =
ALLOCV_N(uint32_t, vtmp, len * 2);
1201 uint32_t mask = (uint32_t)~0 >> nlz;
1202 uint32_t *lim_array = tmp;
1203 uint32_t *rnd_array = tmp + len;
1208 obj_random_bytes(obj, rnd_array, len *
sizeof(uint32_t));
1209 rnd_array[0] &= mask;
1210 for (i = 0; i < len; ++i) {
1211 if (lim_array[i] < rnd_array[i])
1213 if (rnd_array[i] < lim_array[i])
1220 return limited_big_rand(try_rand_if(obj, rnd), rnd, vmax);
1244random_bytes(VALUE obj, VALUE len)
1256 for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
1278 return obj_random_bytes(obj, NULL, n);
1280 return rand_bytes(try_rand_if(obj, rnd), rnd, n);
1290random_s_bytes(VALUE obj, VALUE len)
1293 return rand_bytes(&random_mt_if, rnd,
NUM2LONG(rb_to_int(len)));
1312random_s_seed(VALUE obj)
1315 return rnd->base.
seed;
1319range_values(VALUE vmax, VALUE *begp, VALUE *endp,
int *exclp)
1324 if (begp) *begp = beg;
1326 if (endp) *endp = end;
1328 return rb_check_funcall_default(end, id_minus, 1, begp,
Qfalse);
1332rand_int(VALUE obj,
rb_random_t *rnd, VALUE vmax,
int restrictive)
1339 if (!max)
return Qnil;
1341 if (restrictive)
return Qnil;
1344 r = random_ulong_limited(obj, rnd, (
unsigned long)max - 1);
1350 if (!BIGNUM_SIGN(vmax)) {
1351 if (restrictive)
return Qnil;
1352 vmax = rb_big_uminus(vmax);
1357 if (max == -1)
return Qnil;
1358 r = random_ulong_limited(obj, rnd, max);
1361 ret = random_ulong_limited_big(obj, rnd, vmax);
1371 rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError));
1374NORETURN(
static void invalid_argument(VALUE));
1376invalid_argument(VALUE arg0)
1378 rb_raise(rb_eArgError,
"invalid argument - %"PRIsVALUE, arg0);
1382check_random_number(VALUE v,
const VALUE *argv)
1389 invalid_argument(argv[0]);
1405rand_range(VALUE obj,
rb_random_t* rnd, VALUE range)
1410 if ((v = vmax = range_values(range, &beg, &end, &excl)) ==
Qfalse)
1412 if (
NIL_P(v)) domain_error();
1419 if ((max =
FIX2LONG(vmax) - excl) >= 0) {
1420 unsigned long r = random_ulong_limited(obj, rnd, (
unsigned long)max);
1430 v = random_ulong_limited_big(obj, rnd, vmax);
1433 else if (v = rb_check_to_float(vmax), !
NIL_P(v)) {
1437 double min = float_value(rb_to_float(beg)) / 2.0;
1438 max = float_value(rb_to_float(end)) / 2.0;
1443 else if (isnan(max)) {
1448 r = random_real(obj, rnd, excl);
1450 return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
1454 else if (max == 0.0 && !excl) {
1469 VALUE f = rb_check_to_float(beg);
1481static VALUE rand_random(
int argc, VALUE *argv, VALUE obj,
rb_random_t *rnd);
1514random_rand(
int argc, VALUE *argv, VALUE obj)
1516 VALUE v = rand_random(argc, argv, obj, try_get_rnd(obj));
1517 check_random_number(v, argv);
1522rand_random(
int argc, VALUE *argv, VALUE obj,
rb_random_t *rnd)
1532 v = rb_check_to_int(vmax);
1533 if (!
NIL_P(v))
return rand_int(obj, rnd, v, 1);
1535 v = rb_check_to_float(vmax);
1537 const double max = float_value(v);
1542 double r = random_real(obj, rnd, TRUE);
1543 if (max > 0.0) r *= max;
1547 return rand_range(obj, rnd, vmax);
1563rand_random_number(
int argc, VALUE *argv, VALUE obj)
1566 VALUE v = rand_random(argc, argv, obj, rnd);
1567 if (
NIL_P(v)) v = rand_random(0, 0, obj, rnd);
1568 else if (!v) invalid_argument(argv[0]);
1597rand_mt_equal(VALUE
self, VALUE other)
1600 if (rb_obj_class(
self) != rb_obj_class(other))
return Qfalse;
1601 r1 = get_rnd_mt(
self);
1602 r2 = get_rnd_mt(other);
1603 if (memcmp(r1->mt.state, r2->mt.state,
sizeof(r1->mt.state)))
return Qfalse;
1604 if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state))
return Qfalse;
1605 if (r1->mt.left != r2->mt.left)
return Qfalse;
1606 return rb_equal(r1->base.seed, r2->base.seed);
1641rb_f_rand(
int argc, VALUE *argv, VALUE obj)
1647 VALUE v = rand_range(obj, rnd, vmax);
1648 if (v !=
Qfalse)
return v;
1649 vmax = rb_to_int(vmax);
1651 v = rand_int(obj, rnd, vmax, 0);
1652 if (!
NIL_P(v))
return v;
1655 return DBL2NUM(random_real(obj, rnd, TRUE));
1669random_s_rand(
int argc, VALUE *argv, VALUE obj)
1671 VALUE v = rand_random(argc, argv,
Qnil, rand_start(default_rand()));
1672 check_random_number(v, argv);
1676#define SIP_HASH_STREAMING 0
1677#define sip_hash13 ruby_sip_hash13
1678#if !defined _WIN32 && !defined BYTE_ORDER
1679# ifdef WORDS_BIGENDIAN
1680# define BYTE_ORDER BIG_ENDIAN
1682# define BYTE_ORDER LITTLE_ENDIAN
1684# ifndef LITTLE_ENDIAN
1685# define LITTLE_ENDIAN 1234
1688# define BIG_ENDIAN 4321
1704init_hash_salt(
struct MT *mt)
1708 for (i = 0; i < numberof(hash_salt.u32); ++i)
1709 hash_salt.u32[i] = genrand_int32(mt);
1712NO_SANITIZE(
"unsigned-integer-overflow",
extern st_index_t
rb_hash_start(st_index_t h));
1716 return st_hash_start(hash_salt.key.hash + h);
1722 sip_uint64_t h = sip_hash13(hash_salt.key.sip, ptr, len);
1724 return (st_index_t)h;
1726 return (st_index_t)(h.u32[0] ^ h.u32[1]);
1733Init_RandomSeedCore(
void)
1735 if (!fill_random_bytes(&hash_salt,
sizeof(hash_salt), FALSE))
return;
1746 with_random_seed(DEFAULT_SEED_CNT, 0) {
1747 init_by_array(&mt, seedbuf, DEFAULT_SEED_CNT);
1750 init_hash_salt(&mt);
1751 explicit_bzero(&mt,
sizeof(mt));
1758 uninit_genrand(&r->mt);
1796 base = rb_define_class_id(id_base, rb_cObject);
#define rb_define_singleton_method(klass, mid, func, arity)
Defines klass.mid.
#define rb_define_private_method(klass, mid, func, arity)
Defines klass#mid and makes it private.
VALUE rb_float_new(double d)
Converts a C's double into an instance of rb_cFloat.
void rb_include_module(VALUE klass, VALUE module)
Includes a module to a class.
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a method.
void rb_define_global_function(const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a global function.
#define TYPE(_)
Old name of rb_type.
#define NUM2ULONG
Old name of RB_NUM2ULONG.
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
#define RFLOAT_VALUE
Old name of rb_float_value.
#define T_STRING
Old name of RUBY_T_STRING.
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
#define T_NIL
Old name of RUBY_T_NIL.
#define T_FLOAT
Old name of RUBY_T_FLOAT.
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
#define ULONG2NUM
Old name of RB_ULONG2NUM.
#define ZALLOC
Old name of RB_ZALLOC.
#define CLASS_OF
Old name of rb_class_of.
#define NUM2DBL
Old name of rb_num2dbl.
#define LONG2NUM
Old name of RB_LONG2NUM.
#define ULL2NUM
Old name of RB_ULL2NUM.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
#define T_ARRAY
Old name of RUBY_T_ARRAY.
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
#define DBL2NUM
Old name of rb_float_new.
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
#define NUM2LONG
Old name of RB_NUM2LONG.
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define rb_ary_new2
Old name of rb_ary_new_capa.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
void rb_raise(VALUE exc, const char *fmt,...)
Exception entry point.
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
VALUE rb_cRandom
Random class.
VALUE rb_funcallv(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcall(), except it takes the method arguments as a C array.
VALUE rb_funcallv_public(VALUE recv, ID mid, int argc, const VALUE *argv)
Identical to rb_funcallv(), except it only takes public methods into account.
void rb_gc_register_mark_object(VALUE object)
Inform the garbage collector that object is a live Ruby object that should not be moved.
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
int rb_integer_pack(VALUE val, void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Exports an integer into a buffer.
VALUE rb_big_minus(VALUE x, VALUE y)
Performs subtraction of the passed two objects.
int rb_bigzero_p(VALUE x)
Queries if the passed bignum instance is a "bigzro".
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
VALUE rb_big_plus(VALUE x, VALUE y)
Performs addition of the passed two objects.
size_t rb_absint_numwords(VALUE val, size_t word_numbits, size_t *nlz_bits_ret)
Calculates the number of words needed represent the absolute value of the passed integer.
VALUE rb_integer_unpack(const void *words, size_t numwords, size_t wordsize, size_t nails, int flags)
Import an integer from a buffer.
#define INTEGER_PACK_MSWORD_FIRST
Stores/interprets the most significant word as the first word.
VALUE rb_big_norm(VALUE x)
Normalises the passed bignum.
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
#define rb_check_frozen
Just another name of rb_check_frozen.
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
void rb_gc_mark(VALUE obj)
Marks an object.
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
unsigned long rb_genrand_ulong_limited(unsigned long i)
Generates a random number whose upper limit is i.
double rb_random_real(VALUE rnd)
Identical to rb_genrand_real(), except it generates using the passed RNG.
unsigned int rb_random_int32(VALUE rnd)
Identical to rb_genrand_int32(), except it generates using the passed RNG.
void rb_reset_random_seed(void)
Resets the RNG behind rb_genrand_int32()/rb_genrand_real().
VALUE rb_random_bytes(VALUE rnd, long n)
Generates a String of random bytes.
double rb_genrand_real(void)
Generates a double random number.
unsigned long rb_random_ulong_limited(VALUE rnd, unsigned long limit)
Identical to rb_genrand_ulong_limited(), except it generates using the passed RNG.
unsigned int rb_genrand_int32(void)
Generates a 32 bit random number.
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
VALUE rb_str_new(const char *ptr, long len)
Allocates an instance of rb_cString.
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
void rb_define_alloc_func(VALUE klass, rb_alloc_func_t func)
Sets the allocator function of a class.
static ID rb_intern_const(const char *str)
This is a "tiny optimisation" over rb_intern().
ID rb_intern(const char *name)
Finds or creates a symbol of the given name.
void rb_deprecate_constant(VALUE mod, const char *name)
Asserts that the given constant is deprecated.
void rb_define_const(VALUE klass, const char *name, VALUE val)
Defines a Ruby level constant under a namespace.
const rb_data_type_t rb_random_data_type
The data that holds the backend type of rb_cRandom.
#define RB_RANDOM_INTERFACE_DEFINE(prefix)
This utility macro expands to the names declared using RB_RANDOM_INTERFACE_DECLARE.
struct rb_random_struct rb_random_t
#define RB_RANDOM_INTERFACE_DECLARE(prefix)
This utility macro defines 3 functions named prefix_init, prefix_get_int32, prefix_get_bytes.
void rb_rand_bytes_int32(rb_random_get_int32_func *func, rb_random_t *prng, void *buff, size_t size)
Repeatedly calls the passed function over and over again until the passed buffer is filled with rando...
unsigned int rb_random_get_int32_func(rb_random_t *rng)
This is the type of functions called from your object's #rand method.
double rb_int_pair_to_real(uint32_t a, uint32_t b, int excl)
Generates a 64 bit floating point number by concatenating two 32bit unsigned integers.
static const rb_random_interface_t * rb_rand_if(VALUE obj)
Queries the interface of the passed random object.
void rb_random_base_init(rb_random_t *rnd)
Initialises an allocated rb_random_t instance.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
void * rb_ractor_local_storage_ptr(rb_ractor_local_key_t key)
Identical to rb_ractor_local_storage_value() except the return type.
void rb_ractor_local_storage_ptr_set(rb_ractor_local_key_t key, void *ptr)
Identical to rb_ractor_local_storage_value_set() except the parameter type.
rb_ractor_local_key_t rb_ractor_local_storage_ptr_newkey(const struct rb_ractor_local_storage_type *type)
Extended version of rb_ractor_local_storage_value_newkey().
#define RARRAY_LEN
Just another name of rb_array_len.
#define RARRAY_AREF(a, i)
#define Data_Wrap_Struct(klass, mark, free, sval)
Converts sval, a pointer to your struct, into a Ruby object.
#define DATA_PTR(obj)
Convenient getter macro.
static long RSTRING_LEN(VALUE str)
Queries the length of the string.
static char * RSTRING_PTR(VALUE str)
Queries the contents pointer of the string.
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
#define TypedData_Make_Struct(klass, type, data_type, sval)
Identical to TypedData_Wrap_Struct, except it allocates a new data region internally instead of takin...
static const struct rb_data_type_struct * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
#define InitVM(ext)
This macro is for internal use.
#define _(args)
This was a transition path from K&R to ANSI.
This is the struct that holds necessary info for a struct.
Type that defines a ractor-local storage.
PRNG algorithmic interface, analogous to Ruby level classes.
rb_random_init_func * init
Initialiser function.
size_t default_seed_bits
Number of bits of seed numbers.
rb_random_get_int32_func * get_int32
Function to obtain a random integer.
rb_random_get_real_func * get_real
Function to obtain a random double.
rb_random_get_bytes_func * get_bytes
Function to obtain a series of random bytes.
Base components of the random interface.
VALUE seed
Seed, passed through e.g.
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
void ruby_xfree(void *ptr)
Deallocates a storage instance.