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
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)
164 rb_gc_mark(rnd->base.
seed);
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)
278 &rb_random_data_type,
279 (
void *)&random_mt_if,
280 RUBY_TYPED_FREE_IMMEDIATELY
288 if (RTYPEDDATA_TYPE(obj) == &random_mt_type)
302try_get_rnd(
VALUE obj)
305 return rand_start(default_rand());
308 if (RTYPEDDATA_TYPE(obj) == &random_mt_type)
313 RTYPEDDATA_TYPE(obj)->wrap_struct_name);
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));
367 len = rb_absint_numwords(seed, 32, NULL);
368 if (len == 0) len = 1;
369 buf =
ALLOCV_N(uint32_t, buf0, len);
370 sign = rb_integer_pack(seed, buf, len,
sizeof(uint32_t), 0,
378 if (sign != 2 && buf[len-1] == 1)
380 rng->
init(rnd, buf, len);
382 explicit_bzero(buf, len *
sizeof(*buf));
404 RTYPEDDATA_TYPE(obj)->wrap_struct_name);
407 unsigned int major = rng->
version.major;
408 unsigned int minor = rng->
version.minor;
409 if (major != RUBY_RANDOM_INTERFACE_VERSION_MAJOR) {
411 STRINGIZE(RUBY_RANDOM_INTERFACE_VERSION_MAJOR)
"."
412 STRINGIZE(RUBY_RANDOM_INTERFACE_VERSION_MINOR)
" "
413 "expected: %d.%d", major, minor);
415 argc = rb_check_arity(argc, 0, 1);
418 rnd->
seed = rand_init_default(rng, rnd);
426#define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int32_t))
428#if defined(S_ISCHR) && !defined(DOSISH)
429# define USE_DEV_URANDOM 1
431# define USE_DEV_URANDOM 0
434#ifdef HAVE_GETENTROPY
435# define MAX_SEED_LEN_PER_READ 256
437fill_random_bytes_urandom(
void *seed,
size_t size)
439 unsigned char *p = (
unsigned char *)seed;
441 size_t len = size < MAX_SEED_LEN_PER_READ ? size : MAX_SEED_LEN_PER_READ;
442 if (getentropy(p, len) != 0) {
452fill_random_bytes_urandom(
void *seed,
size_t size)
471 if (fd < 0)
return -1;
473 if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
475 ret = read(fd, ((
char*)seed) + offset, size - offset);
480 offset += (size_t)ret;
481 }
while (offset < size);
487# define fill_random_bytes_urandom(seed, size) -1
490#if ! defined HAVE_GETRANDOM && defined __linux__ && defined __NR_getrandom
491# ifndef GRND_NONBLOCK
492# define GRND_NONBLOCK 0x0001
494# define getrandom(ptr, size, flags) \
495 (ssize_t)syscall(__NR_getrandom, (ptr), (size), (flags))
496# define HAVE_GETRANDOM 1
500#elif defined MAC_OS_X_VERSION_10_7 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
502# if defined(USE_COMMON_RANDOM)
503# elif defined MAC_OS_X_VERSION_10_10 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
504# define USE_COMMON_RANDOM 1
506# define USE_COMMON_RANDOM 0
508# if USE_COMMON_RANDOM
509# include <CommonCrypto/CommonCryptoError.h>
510# include <CommonCrypto/CommonRandom.h>
512# include <Security/SecRandom.h>
516fill_random_bytes_syscall(
void *seed,
size_t size,
int unused)
519 CCRNGStatus status = CCRandomGenerateBytes(seed, size);
520 int failed = status != kCCSuccess;
522 int status = SecRandomCopyBytes(kSecRandomDefault, size, seed);
523 int failed = status != errSecSuccess;
528# if USE_COMMON_RANDOM
530 fprintf(stderr,
"CCRandomGenerateBytes failed: %d\n", status);
532 CFStringRef s = SecCopyErrorMessageString(status, NULL);
533 const char *m = s ? CFStringGetCStringPtr(s, kCFStringEncodingUTF8) : NULL;
534 fprintf(stderr,
"SecRandomCopyBytes failed: %d: %s\n", status,
543#elif defined(HAVE_ARC4RANDOM_BUF)
545fill_random_bytes_syscall(
void *buf,
size_t size,
int unused)
547#if (defined(__OpenBSD__) && OpenBSD >= 201411) || \
548 (defined(__NetBSD__) && __NetBSD_Version__ >= 700000000) || \
549 (defined(__FreeBSD__) && __FreeBSD_version >= 1200079)
550 arc4random_buf(buf, size);
559# define DWORD_MAX (~(DWORD)0UL)
562# if defined(CRYPT_VERIFYCONTEXT)
563STATIC_ASSERT(sizeof_HCRYPTPROV,
sizeof(HCRYPTPROV) ==
sizeof(
size_t));
567static const HCRYPTPROV INVALID_HCRYPTPROV = (HCRYPTPROV)INVALID_HANDLE_VALUE;
570release_crypt(
void *p)
573 HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_SIZE_EXCHANGE(*ptr, INVALID_HCRYPTPROV);
574 if (prov && prov != INVALID_HCRYPTPROV) {
575 CryptReleaseContext(prov, 0);
580fill_random_bytes_crypt(
void *seed,
size_t size)
582 static HCRYPTPROV perm_prov;
583 HCRYPTPROV prov = perm_prov, old_prov;
585 if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
586 prov = INVALID_HCRYPTPROV;
588 old_prov = (HCRYPTPROV)ATOMIC_SIZE_CAS(perm_prov, 0, prov);
589 if (LIKELY(!old_prov)) {
590 if (prov != INVALID_HCRYPTPROV) {
591#undef RUBY_UNTYPED_DATA_WARNING
592#define RUBY_UNTYPED_DATA_WARNING 0
593 rb_gc_register_mark_object(
Data_Wrap_Struct(0, 0, release_crypt, &perm_prov));
597 if (prov != INVALID_HCRYPTPROV) {
598 CryptReleaseContext(prov, 0);
603 if (prov == INVALID_HCRYPTPROV)
return -1;
605 DWORD n = (size > (size_t)DWORD_MAX) ? DWORD_MAX : (DWORD)size;
606 if (!CryptGenRandom(prov, n, seed))
return -1;
607 seed = (
char *)seed + n;
613# define fill_random_bytes_crypt(seed, size) -1
617fill_random_bytes_bcrypt(
void *seed,
size_t size)
620 ULONG n = (size > (size_t)ULONG_MAX) ? LONG_MAX : (ULONG)size;
621 if (BCryptGenRandom(NULL, seed, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG))
623 seed = (
char *)seed + n;
630fill_random_bytes_syscall(
void *seed,
size_t size,
int unused)
632 if (fill_random_bytes_bcrypt(seed, size) == 0)
return 0;
633 return fill_random_bytes_crypt(seed, size);
635#elif defined HAVE_GETRANDOM
637fill_random_bytes_syscall(
void *seed,
size_t size,
int need_secure)
644 flags = GRND_NONBLOCK;
647 ssize_t ret = getrandom(((
char*)seed) + offset, size - offset, flags);
649 ATOMIC_SET(try_syscall, 0);
652 offset += (size_t)ret;
653 }
while (offset < size);
659# define fill_random_bytes_syscall(seed, size, need_secure) -1
663ruby_fill_random_bytes(
void *seed,
size_t size,
int need_secure)
665 int ret = fill_random_bytes_syscall(seed, size, need_secure);
666 if (ret == 0)
return ret;
667 return fill_random_bytes_urandom(seed, size);
670#define fill_random_bytes ruby_fill_random_bytes
674fill_random_seed(uint32_t *seed,
size_t cnt)
677#if defined HAVE_CLOCK_GETTIME
679#elif defined HAVE_GETTIMEOFDAY
682 size_t len = cnt *
sizeof(*seed);
684 memset(seed, 0, len);
686 fill_random_bytes(seed, len, FALSE);
688#if defined HAVE_CLOCK_GETTIME
689 clock_gettime(CLOCK_REALTIME, &tv);
690 seed[0] ^= tv.tv_nsec;
691#elif defined HAVE_GETTIMEOFDAY
692 gettimeofday(&tv, 0);
693 seed[0] ^= tv.tv_usec;
695 seed[1] ^= (uint32_t)tv.tv_sec;
696#if SIZEOF_TIME_T > SIZEOF_INT
697 seed[0] ^= (uint32_t)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
699 seed[2] ^= getpid() ^ (ATOMIC_FETCH_ADD(n, 1) << 16);
700 seed[3] ^= (uint32_t)(
VALUE)&seed;
701#if SIZEOF_VOIDP > SIZEOF_INT
702 seed[2] ^= (uint32_t)((
VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
707make_seed_value(uint32_t *ptr,
size_t len)
711 if (ptr[len-1] <= 1) {
716 seed = rb_integer_unpack(ptr, len,
sizeof(uint32_t), 0,
722#define with_random_seed(size, add) \
723 for (uint32_t seedbuf[(size)+(add)], loop = (fill_random_seed(seedbuf, (size)), 1); \
724 loop; explicit_bzero(seedbuf, (size)*sizeof(seedbuf[0])), loop = 0)
738 with_random_seed(DEFAULT_SEED_CNT, 1) {
739 v = make_seed_value(seedbuf, DEFAULT_SEED_CNT);
765 if (n == 0)
return buf;
766 if (fill_random_bytes(RSTRING_PTR(buf), n, TRUE))
786random_get_seed(
VALUE obj)
788 return get_rnd(obj)->
seed;
800 rnd1 = get_rnd_mt(obj);
801 rnd2 = get_rnd_mt(orig);
805 mt->next = mt->state + numberof(mt->state) - mt->left + 1;
810mt_state(
const struct MT *mt)
812 return rb_integer_unpack(mt->state, numberof(mt->state),
813 sizeof(*mt->state), 0,
819rand_mt_state(
VALUE obj)
822 return mt_state(&rnd->mt);
827random_s_state(
VALUE klass)
829 return mt_state(&default_rand()->mt);
834rand_mt_left(
VALUE obj)
842random_s_left(
VALUE klass)
844 return INT2FIX(default_rand()->mt.left);
849rand_mt_dump(
VALUE obj)
854 rb_ary_push(dump, mt_state(&rnd->mt));
855 rb_ary_push(dump,
INT2FIX(rnd->mt.left));
856 rb_ary_push(dump, rnd->base.
seed);
866 struct MT *mt = &rnd->mt;
883 rb_integer_pack(state, mt->state, numberof(mt->state),
884 sizeof(*mt->state), 0,
887 if (x > numberof(mt->state)) {
890 mt->left = (
unsigned int)x;
891 mt->next = mt->state + numberof(mt->state) - x + 1;
901 init_genrand(mt, data);
905rand_mt_init(
rb_random_t *rnd,
const uint32_t *buf,
size_t len)
908 init_by_array(mt, buf, (
int)len);
915 return genrand_int32(mt);
919rand_mt_get_bytes(
rb_random_t *rnd,
void *ptr,
size_t n)
953 if (rb_check_arity(argc, 0, 1) == 0) {
954 seed = random_seed(obj);
960 rand_init(&random_mt_if, &r->base, seed);
967make_mask(
unsigned long x)
984 unsigned long val, mask;
986 if (!limit)
return 0;
987 mask = make_mask(limit);
990 if (0xffffffff < limit) {
994 for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
995 if ((mask >> (i * 32)) & 0xffffffff) {
996 val |= (
unsigned long)rng->
get_int32(rnd) << (i * 32);
1008 }
while (limit < val);
1022 uint32_t *tmp, *lim_array, *rnd_array;
1026 len = rb_absint_numwords(limit, 32, NULL);
1027 tmp =
ALLOCV_N(uint32_t, vtmp, len*2);
1029 rnd_array = tmp + len;
1030 rb_integer_pack(limit, lim_array, len,
sizeof(uint32_t), 0,
1036 for (i = len-1; 0 <= i; i--) {
1038 uint32_t lim = lim_array[i];
1039 mask = mask ? 0xffffffff : (uint32_t)make_mask(lim);
1051 val = rb_integer_unpack(rnd_array, len,
sizeof(uint32_t), 0,
1068 return limited_rand(&random_mt_if, &mt->base, limit);
1072obj_random_bytes(
VALUE obj,
void *p,
long n)
1083 if (p) memcpy(p, RSTRING_PTR(v), n);
1099 obj_random_bytes(obj, &x,
sizeof(x));
1100 return (
unsigned int)x;
1102 return random_int32(try_rand_if(obj, rnd), rnd);
1111 uint32_t x[2] = {0, 0};
1112 obj_random_bytes(obj, x,
sizeof(x));
1119 a = random_int32(rng, rnd);
1120 b = random_int32(rng, rnd);
1129 return int_pair_to_real_exclusive(a, b);
1132 return int_pair_to_real_inclusive(a, b);
1141 VALUE v = rb_funcallv(obj, id_rand, 0, 0);
1146 else if (d >= 1.0) {
1151 return random_real(obj, rnd, TRUE);
1155ulong_to_num_plus_1(
unsigned long n)
1160 if (n >= ULONG_MAX) {
1170 if (!limit)
return 0;
1172 const int w =
sizeof(limit) * CHAR_BIT - nlz_long(limit);
1173 const int n = w > 32 ?
sizeof(
unsigned long) : sizeof(uint32_t);
1174 const unsigned long mask = ~(~0UL << w);
1175 const unsigned long full =
1176 (size_t)n >=
sizeof(
unsigned long) ? ~0UL :
1177 ~(~0UL << n * CHAR_BIT);
1178 unsigned long val, bits = 0, rest = 0;
1181 union {uint32_t u32;
unsigned long ul;} buf;
1182 obj_random_bytes(obj, &buf, n);
1184 bits = (n ==
sizeof(uint32_t)) ? buf.u32 : buf.ul;
1190 }
while (limit < val);
1193 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1201 VALUE lim = ulong_to_num_plus_1(limit);
1204 if (rb_num_negative_p(v)) {
1212 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1220 size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz);
1221 uint32_t *tmp =
ALLOCV_N(uint32_t, vtmp, len * 2);
1222 uint32_t mask = (uint32_t)~0 >> nlz;
1223 uint32_t *lim_array = tmp;
1224 uint32_t *rnd_array = tmp + len;
1226 rb_integer_pack(vmax, lim_array, len,
sizeof(uint32_t), 0, flag);
1229 obj_random_bytes(obj, rnd_array, len *
sizeof(uint32_t));
1230 rnd_array[0] &= mask;
1231 for (i = 0; i < len; ++i) {
1232 if (lim_array[i] < rnd_array[i])
1234 if (rnd_array[i] < lim_array[i])
1237 v = rb_integer_unpack(rnd_array, len,
sizeof(uint32_t), 0, flag);
1241 return limited_big_rand(try_rand_if(obj, rnd), rnd, vmax);
1251 ptr = RSTRING_PTR(bytes);
1277 for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
1299 return obj_random_bytes(obj, NULL, n);
1301 return rand_bytes(try_rand_if(obj, rnd), rnd, n);
1333random_s_seed(
VALUE obj)
1336 return rnd->base.
seed;
1345 if (begp) *begp = beg;
1347 if (endp) *endp = end;
1349 return rb_check_funcall_default(end, id_minus, 1, begp,
Qfalse);
1360 if (!max)
return Qnil;
1362 if (restrictive)
return Qnil;
1365 r = random_ulong_limited(obj, rnd, (
unsigned long)max - 1);
1370 if (rb_bigzero_p(vmax))
return Qnil;
1371 if (!BIGNUM_SIGN(vmax)) {
1372 if (restrictive)
return Qnil;
1373 vmax = rb_big_uminus(vmax);
1375 vmax = rb_big_minus(vmax,
INT2FIX(1));
1378 if (max == -1)
return Qnil;
1379 r = random_ulong_limited(obj, rnd, max);
1382 ret = random_ulong_limited_big(obj, rnd, vmax);
1395NORETURN(
static void invalid_argument(
VALUE));
1397invalid_argument(
VALUE arg0)
1403check_random_number(
VALUE v,
const VALUE *argv)
1410 invalid_argument(argv[0]);
1431 if ((v = vmax = range_values(range, &beg, &end, &excl)) ==
Qfalse)
1433 if (
NIL_P(v)) domain_error();
1440 if ((max =
FIX2LONG(vmax) - excl) >= 0) {
1441 unsigned long r = random_ulong_limited(obj, rnd, (
unsigned long)max);
1446 vmax = excl ? rb_big_minus(vmax,
INT2FIX(1)) : rb_big_norm(vmax);
1451 v = random_ulong_limited_big(obj, rnd, vmax);
1464 else if (isnan(max)) {
1469 r = random_real(obj, rnd, excl);
1471 return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
1473 v = rb_float_new(r * max);
1475 else if (max == 0.0 && !excl) {
1476 v = rb_float_new(0.0);
1488 return rb_big_plus(v, beg);
1496 return rb_funcallv(beg, id_plus, 1, &v);
1537 VALUE v = rand_random(argc, argv, obj, try_get_rnd(obj));
1538 check_random_number(v, argv);
1547 if (rb_check_arity(argc, 0, 1) == 0) {
1548 return rb_float_new(random_real(obj, rnd, TRUE));
1552 if (!RB_FLOAT_TYPE_P(vmax)) {
1554 if (!
NIL_P(v))
return rand_int(obj, rnd, v, 1);
1558 const double max = float_value(v);
1563 double r = random_real(obj, rnd, TRUE);
1564 if (max > 0.0) r *= max;
1565 return rb_float_new(r);
1568 return rand_range(obj, rnd, vmax);
1584rand_random_number(
int argc,
VALUE *argv,
VALUE obj)
1587 VALUE v = rand_random(argc, argv, obj, rnd);
1588 if (
NIL_P(v)) v = rand_random(0, 0, obj, rnd);
1589 else if (!v) invalid_argument(argv[0]);
1622 r1 = get_rnd_mt(self);
1623 r2 = get_rnd_mt(other);
1624 if (memcmp(r1->mt.state, r2->mt.state,
sizeof(r1->mt.state)))
return Qfalse;
1625 if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state))
return Qfalse;
1626 if (r1->mt.left != r2->mt.left)
return Qfalse;
1627 return rb_equal(r1->base.seed, r2->base.seed);
1667 if (rb_check_arity(argc, 0, 1) && !
NIL_P(vmax = argv[0])) {
1668 VALUE v = rand_range(obj, rnd, vmax);
1669 if (v !=
Qfalse)
return v;
1672 v = rand_int(obj, rnd, vmax, 0);
1673 if (!
NIL_P(v))
return v;
1676 return DBL2NUM(random_real(obj, rnd, TRUE));
1690random_s_rand(
int argc,
VALUE *argv,
VALUE obj)
1692 VALUE v = rand_random(argc, argv,
Qnil, rand_start(default_rand()));
1693 check_random_number(v, argv);
1697#define SIP_HASH_STREAMING 0
1698#define sip_hash13 ruby_sip_hash13
1699#if !defined _WIN32 && !defined BYTE_ORDER
1700# ifdef WORDS_BIGENDIAN
1701# define BYTE_ORDER BIG_ENDIAN
1703# define BYTE_ORDER LITTLE_ENDIAN
1705# ifndef LITTLE_ENDIAN
1706# define LITTLE_ENDIAN 1234
1709# define BIG_ENDIAN 4321
1725init_hash_salt(
struct MT *mt)
1729 for (i = 0; i < numberof(hash_salt.u32); ++i)
1730 hash_salt.u32[i] = genrand_int32(mt);
1733NO_SANITIZE(
"unsigned-integer-overflow",
extern st_index_t
rb_hash_start(st_index_t h));
1737 return st_hash_start(hash_salt.key.hash + h);
1743 sip_uint64_t h = sip_hash13(hash_salt.key.sip, ptr, len);
1745 return (st_index_t)h;
1747 return (st_index_t)(h.u32[0] ^ h.u32[1]);
1754Init_RandomSeedCore(
void)
1756 if (!fill_random_bytes(&hash_salt,
sizeof(hash_salt), FALSE))
return;
1767 with_random_seed(DEFAULT_SEED_CNT, 0) {
1768 init_by_array(&mt, seedbuf, DEFAULT_SEED_CNT);
1771 init_hash_salt(&mt);
1772 explicit_bzero(&mt,
sizeof(mt));
1779 uninit_genrand(&r->mt);
1815 ID id_base = rb_intern_const(
"Base");
1877 id_rand = rb_intern(
"rand");
1878 id_bytes = rb_intern(
"bytes");
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
#define rb_define_method(klass, mid, func, arity)
Defines klass#mid.
#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.
#define rb_define_global_function(mid, func, arity)
Defines rb_mKernel #mid.
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.
VALUE rb_define_class_id(ID id, VALUE super)
This is a very badly designed API that creates an anonymous class.
#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.
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
void rb_check_copyable(VALUE obj, VALUE orig)
Ensures that the passed object can be initialize_copy relationship.
VALUE rb_eRangeError
RangeError exception.
VALUE rb_eTypeError
TypeError exception.
VALUE rb_eRuntimeError
RuntimeError exception.
void * rb_check_typeddata(VALUE obj, const rb_data_type_t *data_type)
Identical to rb_typeddata_is_kind_of(), except it raises exceptions instead of returning false.
VALUE rb_eArgError
ArgumentError exception.
VALUE rb_eSystemCallError
SystemCallError exception.
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
VALUE rb_check_to_float(VALUE val)
This is complicated.
VALUE rb_cRandom
Random class.
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
VALUE rb_to_float(VALUE val)
Identical to rb_check_to_float(), except it raises on error.
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
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.
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
#define INTEGER_PACK_MSWORD_FIRST
Stores/interprets the most significant word as the first word.
#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.
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.
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
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.
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 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 4 functions named prefix_init, prefix_init_int32, prefix_get_int32,...
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.
#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.
#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...
#define InitVM(ext)
This macro is for internal use.
#define _(args)
This was a transition path from K&R to ANSI.
Type that defines a ractor-local storage.
PRNG algorithmic interface, analogous to Ruby level classes.
rb_random_init_func * init
Function to initialize from uint32_t array.
rb_random_init_int32_func * init_int32
Function to initialize from single uint32_t.
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.
struct rb_random_interface_t::@57 version
Major/minor versions of this interface.
Base components of the random interface.
VALUE seed
Seed, passed through e.g.
uintptr_t VALUE
Type that represents a Ruby object.
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.