Ruby 3.5.0dev (2025-07-02 revision d31467311573b39bd07e182f863a26069f21d481)
random.c (d31467311573b39bd07e182f863a26069f21d481)
1/**********************************************************************
2
3 random.c -
4
5 $Author$
6 created at: Fri Dec 24 16:39:21 JST 1993
7
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9
10**********************************************************************/
11
12#include "ruby/internal/config.h"
13
14#include <errno.h>
15#include <limits.h>
16#include <math.h>
17#include <float.h>
18#include <time.h>
19
20#ifdef HAVE_UNISTD_H
21# include <unistd.h>
22#endif
23
24#include <sys/types.h>
25#include <sys/stat.h>
26
27#ifdef HAVE_FCNTL_H
28# include <fcntl.h>
29#endif
30
31#if defined(HAVE_SYS_TIME_H)
32# include <sys/time.h>
33#endif
34
35#ifdef HAVE_SYSCALL_H
36# include <syscall.h>
37#elif defined HAVE_SYS_SYSCALL_H
38# include <sys/syscall.h>
39#endif
40
41#ifdef _WIN32
42# include <winsock2.h>
43# include <windows.h>
44# include <wincrypt.h>
45# include <bcrypt.h>
46#endif
47
48#if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__NetBSD__)
49/* to define OpenBSD and FreeBSD for version check */
50# include <sys/param.h>
51#endif
52
53#if defined HAVE_GETRANDOM || defined HAVE_GETENTROPY
54# if defined(HAVE_SYS_RANDOM_H)
55# include <sys/random.h>
56# endif
57#elif defined __linux__ && defined __NR_getrandom
58# include <linux/random.h>
59#endif
60
61#if defined __APPLE__
62# include <AvailabilityMacros.h>
63#endif
64
65#include "internal.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"
73#include "ruby/random.h"
74#include "ruby/ractor.h"
75
76STATIC_ASSERT(int_must_be_32bit_at_least, sizeof(int) * CHAR_BIT >= 32);
77
78#include "missing/mt19937.c"
79
80/* generates a random number on [0,1) with 53-bit resolution*/
81static double int_pair_to_real_exclusive(uint32_t a, uint32_t b);
82static double
83genrand_real(struct MT *mt)
84{
85 /* mt must be initialized */
86 unsigned int a = genrand_int32(mt), b = genrand_int32(mt);
87 return int_pair_to_real_exclusive(a, b);
88}
89
90static const double dbl_reduce_scale = /* 2**(-DBL_MANT_DIG) */
91 (1.0
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)));
95
96static double
97int_pair_to_real_exclusive(uint32_t a, uint32_t b)
98{
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;
103 a >>= a_shift;
104 b >>= b_shift;
105 return (a*(double)(1ul<<(32-b_shift))+b)*dbl_reduce_scale;
106}
107
108/* generates a random number on [0,1] with 53-bit resolution*/
109static double int_pair_to_real_inclusive(uint32_t a, uint32_t b);
110#if 0
111static double
112genrand_real2(struct MT *mt)
113{
114 /* mt must be initialized */
115 uint32_t a = genrand_int32(mt), b = genrand_int32(mt);
116 return int_pair_to_real_inclusive(a, b);
117}
118#endif
119
120/* These real versions are due to Isaku Wada, 2002/01/09 added */
121
122#undef N
123#undef M
124
125typedef struct {
126 rb_random_t base;
127 struct MT mt;
129
130#define DEFAULT_SEED_CNT 4
131
132static VALUE rand_init(const rb_random_interface_t *, rb_random_t *, VALUE);
133static VALUE random_seed(VALUE);
134static void fill_random_seed(uint32_t *seed, size_t cnt, bool try_bytes);
135static VALUE make_seed_value(uint32_t *ptr, size_t len);
136#define fill_random_bytes ruby_fill_random_bytes
137
139static const rb_random_interface_t random_mt_if = {
140 DEFAULT_SEED_CNT * 32,
142};
143
144static rb_random_mt_t *
145rand_mt_start(rb_random_mt_t *r)
146{
147 if (!genrand_initialized(&r->mt)) {
148 r->base.seed = rand_init(&random_mt_if, &r->base, random_seed(Qundef));
149 }
150 return r;
151}
152
153static rb_random_t *
154rand_start(rb_random_mt_t *r)
155{
156 return &rand_mt_start(r)->base;
157}
158
159static rb_ractor_local_key_t default_rand_key;
160
161void
162rb_free_default_rand_key(void)
163{
164 xfree(default_rand_key);
165}
166
167static void
168default_rand_mark(void *ptr)
169{
170 rb_random_mt_t *rnd = (rb_random_mt_t *)ptr;
171 rb_gc_mark(rnd->base.seed);
172}
173
174static const struct rb_ractor_local_storage_type default_rand_key_storage_type = {
175 default_rand_mark,
176 ruby_xfree,
177};
178
179static rb_random_mt_t *
180default_rand(void)
181{
182 rb_random_mt_t *rnd;
183
184 if ((rnd = rb_ractor_local_storage_ptr(default_rand_key)) == NULL) {
185 rnd = ZALLOC(rb_random_mt_t);
186 rb_ractor_local_storage_ptr_set(default_rand_key, rnd);
187 }
188
189 return rnd;
190}
191
192static rb_random_mt_t *
193default_mt(void)
194{
195 return rand_mt_start(default_rand());
196}
197
198unsigned int
200{
201 struct MT *mt = &default_mt()->mt;
202 return genrand_int32(mt);
203}
204
205double
207{
208 struct MT *mt = &default_mt()->mt;
209 return genrand_real(mt);
210}
211
212#define SIZEOF_INT32 (31/CHAR_BIT + 1)
213
214static double
215int_pair_to_real_inclusive(uint32_t a, uint32_t b)
216{
217 double r;
218 enum {dig = DBL_MANT_DIG};
219 enum {dig_u = dig-32, dig_r64 = 64-dig, bmask = ~(~0u<<(dig_r64))};
220#if defined HAVE_UINT128_T
221 const uint128_t m = ((uint128_t)1 << dig) | 1;
222 uint128_t x = ((uint128_t)a << 32) | b;
223 r = (double)(uint64_t)((x * m) >> 64);
224#elif defined HAVE_UINT64_T && !MSC_VERSION_BEFORE(1300)
225 uint64_t x = ((uint64_t)a << dig_u) +
226 (((uint64_t)b + (a >> dig_u)) >> dig_r64);
227 r = (double)x;
228#else
229 /* shift then add to get rid of overflow */
230 b = (b >> dig_r64) + (((a >> dig_u) + (b & bmask)) >> dig_r64);
231 r = (double)a * (1 << dig_u) + b;
232#endif
233 return r * dbl_reduce_scale;
234}
235
237#define id_minus '-'
238#define id_plus '+'
239static ID id_rand, id_bytes;
240NORETURN(static void domain_error(void));
241
242/* :nodoc: */
243#define random_mark rb_random_mark
244
245void
246random_mark(void *ptr)
247{
248 rb_gc_mark(((rb_random_t *)ptr)->seed);
249}
250
251#define random_free RUBY_TYPED_DEFAULT_FREE
252
253static size_t
254random_memsize(const void *ptr)
255{
256 return sizeof(rb_random_t);
257}
258
259const rb_data_type_t rb_random_data_type = {
260 "random",
261 {
262 random_mark,
263 random_free,
264 random_memsize,
265 },
266 0, 0, RUBY_TYPED_FREE_IMMEDIATELY
267};
268
269#define random_mt_mark rb_random_mark
270#define random_mt_free RUBY_TYPED_DEFAULT_FREE
271
272static size_t
273random_mt_memsize(const void *ptr)
274{
275 return sizeof(rb_random_mt_t);
276}
277
278static const rb_data_type_t random_mt_type = {
279 "random/MT",
280 {
281 random_mt_mark,
282 random_mt_free,
283 random_mt_memsize,
284 },
285 &rb_random_data_type,
286 (void *)&random_mt_if,
287 RUBY_TYPED_FREE_IMMEDIATELY
288};
289
290static rb_random_t *
291get_rnd(VALUE obj)
292{
293 rb_random_t *ptr;
294 TypedData_Get_Struct(obj, rb_random_t, &rb_random_data_type, ptr);
295 if (RTYPEDDATA_TYPE(obj) == &random_mt_type)
296 return rand_start((rb_random_mt_t *)ptr);
297 return ptr;
298}
299
300static rb_random_mt_t *
301get_rnd_mt(VALUE obj)
302{
303 rb_random_mt_t *ptr;
304 TypedData_Get_Struct(obj, rb_random_mt_t, &random_mt_type, ptr);
305 return ptr;
306}
307
308static rb_random_t *
309try_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, &rb_random_data_type)) return NULL;
315 if (RTYPEDDATA_TYPE(obj) == &random_mt_type)
316 return rand_start(DATA_PTR(obj));
317 rb_random_t *rnd = DATA_PTR(obj);
318 if (!rnd) {
319 rb_raise(rb_eArgError, "uninitialized random: %s",
320 RTYPEDDATA_TYPE(obj)->wrap_struct_name);
321 }
322 return rnd;
323}
324
325static const rb_random_interface_t *
326try_rand_if(VALUE obj, rb_random_t *rnd)
327{
328 if (rnd == &default_rand()->base) {
329 return &random_mt_if;
330 }
331 return rb_rand_if(obj);
332}
333
334/* :nodoc: */
335void
337{
338 rnd->seed = INT2FIX(0);
339}
340
341/* :nodoc: */
342static VALUE
343random_alloc(VALUE klass)
344{
345 rb_random_mt_t *rnd;
346 VALUE obj = TypedData_Make_Struct(klass, rb_random_mt_t, &random_mt_type, rnd);
347 rb_random_base_init(&rnd->base);
348 return obj;
349}
350
351static VALUE
352rand_init_default(const rb_random_interface_t *rng, rb_random_t *rnd)
353{
354 VALUE seed, buf0 = 0;
355 size_t len = roomof(rng->default_seed_bits, 32);
356 uint32_t *buf = ALLOCV_N(uint32_t, buf0, len+1);
357
358 fill_random_seed(buf, len, true);
359 rng->init(rnd, buf, len);
360 seed = make_seed_value(buf, len);
361 explicit_bzero(buf, len * sizeof(*buf));
362 ALLOCV_END(buf0);
363 return seed;
364}
365
366static VALUE
367rand_init(const rb_random_interface_t *rng, rb_random_t *rnd, VALUE seed)
368{
369 uint32_t *buf;
370 VALUE buf0 = 0;
371 size_t len;
372 int sign;
373
374 len = rb_absint_numwords(seed, 32, NULL);
375 if (len == 0) len = 1;
376 buf = ALLOCV_N(uint32_t, buf0, len);
377 sign = rb_integer_pack(seed, buf, len, sizeof(uint32_t), 0,
379 if (sign < 0)
380 sign = -sign;
381 if (len == 1) {
382 rng->init_int32(rnd, buf[0]);
383 }
384 else {
385 if (sign != 2 && buf[len-1] == 1) /* remove leading-zero-guard */
386 len--;
387 rng->init(rnd, buf, len);
388 }
389 explicit_bzero(buf, len * sizeof(*buf));
390 ALLOCV_END(buf0);
391 return seed;
392}
393
394/*
395 * call-seq:
396 * Random.new(seed = Random.new_seed) -> prng
397 *
398 * Creates a new PRNG using +seed+ to set the initial state. If +seed+ is
399 * omitted, the generator is initialized with Random.new_seed.
400 *
401 * See Random.srand for more information on the use of seed values.
402 */
403static VALUE
404random_init(int argc, VALUE *argv, VALUE obj)
405{
406 rb_random_t *rnd = try_get_rnd(obj);
407 const rb_random_interface_t *rng = rb_rand_if(obj);
408
409 if (!rng) {
410 rb_raise(rb_eTypeError, "undefined random interface: %s",
411 RTYPEDDATA_TYPE(obj)->wrap_struct_name);
412 }
413
414 unsigned int major = rng->version.major;
415 unsigned int minor = rng->version.minor;
416 if (major != RUBY_RANDOM_INTERFACE_VERSION_MAJOR) {
417 rb_raise(rb_eTypeError, "Random interface version "
418 STRINGIZE(RUBY_RANDOM_INTERFACE_VERSION_MAJOR) "."
419 STRINGIZE(RUBY_RANDOM_INTERFACE_VERSION_MINOR) " "
420 "expected: %d.%d", major, minor);
421 }
422 argc = rb_check_arity(argc, 0, 1);
423 rb_check_frozen(obj);
424 if (argc == 0) {
425 rnd->seed = rand_init_default(rng, rnd);
426 }
427 else {
428 rnd->seed = rand_init(rng, rnd, rb_to_int(argv[0]));
429 }
430 return obj;
431}
432
433#define DEFAULT_SEED_LEN (DEFAULT_SEED_CNT * (int)sizeof(int32_t))
434
435#if defined(S_ISCHR) && !defined(DOSISH)
436# define USE_DEV_URANDOM 1
437#else
438# define USE_DEV_URANDOM 0
439#endif
440
441#if ! defined HAVE_GETRANDOM && defined __linux__ && defined __NR_getrandom
442# ifndef GRND_NONBLOCK
443# define GRND_NONBLOCK 0x0001 /* not defined in musl libc */
444# endif
445# define getrandom(ptr, size, flags) \
446 (ssize_t)syscall(__NR_getrandom, (ptr), (size), (flags))
447# define HAVE_GETRANDOM 1
448#endif
449
450/* fill random bytes by reading random device directly */
451#if USE_DEV_URANDOM
452static int
453fill_random_bytes_urandom(void *seed, size_t size)
454{
455 /*
456 O_NONBLOCK and O_NOCTTY is meaningless if /dev/urandom correctly points
457 to a urandom device. But it protects from several strange hazard if
458 /dev/urandom is not a urandom device.
459 */
460 int fd = rb_cloexec_open("/dev/urandom",
461# ifdef O_NONBLOCK
462 O_NONBLOCK|
463# endif
464# ifdef O_NOCTTY
465 O_NOCTTY|
466# endif
467 O_RDONLY, 0);
468 struct stat statbuf;
469 ssize_t ret = 0;
470 size_t offset = 0;
471
472 if (fd < 0) return -1;
474 if (fstat(fd, &statbuf) == 0 && S_ISCHR(statbuf.st_mode)) {
475 do {
476 ret = read(fd, ((char*)seed) + offset, size - offset);
477 if (ret < 0) {
478 close(fd);
479 return -1;
480 }
481 offset += (size_t)ret;
482 } while (offset < size);
483 }
484 close(fd);
485 return 0;
486}
487#else
488# define fill_random_bytes_urandom(seed, size) -1
489#endif
490
491/* fill random bytes by library */
492#if 0
493#elif defined MAC_OS_X_VERSION_10_7 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7
494
495# if defined(USE_COMMON_RANDOM)
496# elif defined MAC_OS_X_VERSION_10_10 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_10
497# define USE_COMMON_RANDOM 1
498# else
499# define USE_COMMON_RANDOM 0
500# endif
501# if USE_COMMON_RANDOM
502# include <CommonCrypto/CommonCryptoError.h> /* for old Xcode */
503# include <CommonCrypto/CommonRandom.h>
504# else
505# include <Security/SecRandom.h>
506# endif
507
508static int
509fill_random_bytes_lib(void *seed, size_t size)
510{
511#if USE_COMMON_RANDOM
512 CCRNGStatus status = CCRandomGenerateBytes(seed, size);
513 int failed = status != kCCSuccess;
514#else
515 int status = SecRandomCopyBytes(kSecRandomDefault, size, seed);
516 int failed = status != errSecSuccess;
517#endif
518
519 if (failed) {
520# if 0
521# if USE_COMMON_RANDOM
522 /* How to get the error message? */
523 fprintf(stderr, "CCRandomGenerateBytes failed: %d\n", status);
524# else
525 CFStringRef s = SecCopyErrorMessageString(status, NULL);
526 const char *m = s ? CFStringGetCStringPtr(s, kCFStringEncodingUTF8) : NULL;
527 fprintf(stderr, "SecRandomCopyBytes failed: %d: %s\n", status,
528 m ? m : "unknown");
529 if (s) CFRelease(s);
530# endif
531# endif
532 return -1;
533 }
534 return 0;
535}
536#elif defined(HAVE_ARC4RANDOM_BUF) && \
537 ((defined(__OpenBSD__) && OpenBSD >= 201411) || \
538 (defined(__NetBSD__) && __NetBSD_Version__ >= 700000000) || \
539 (defined(__FreeBSD__) && __FreeBSD_version >= 1200079))
540// [Bug #15039] arc4random_buf(3) should used only if we know it is fork-safe
541static int
542fill_random_bytes_lib(void *buf, size_t size)
543{
544 arc4random_buf(buf, size);
545 return 0;
546}
547#elif defined(_WIN32)
548
549#ifndef DWORD_MAX
550# define DWORD_MAX (~(DWORD)0UL)
551#endif
552
553# if defined(CRYPT_VERIFYCONTEXT)
554/* Although HCRYPTPROV is not a HANDLE, it looks like
555 * INVALID_HANDLE_VALUE is not a valid value */
556static const HCRYPTPROV INVALID_HCRYPTPROV = (HCRYPTPROV)INVALID_HANDLE_VALUE;
557
558static void
559release_crypt(void *p)
560{
561 HCRYPTPROV *ptr = p;
562 HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_PTR_EXCHANGE(*ptr, INVALID_HCRYPTPROV);
563 if (prov && prov != INVALID_HCRYPTPROV) {
564 CryptReleaseContext(prov, 0);
565 }
566}
567
568static const rb_data_type_t crypt_prov_type = {
569 "HCRYPTPROV",
570 {0, release_crypt,},
571 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_EMBEDDABLE
572};
573
574static int
575fill_random_bytes_crypt(void *seed, size_t size)
576{
577 static HCRYPTPROV perm_prov;
578 HCRYPTPROV prov = perm_prov, old_prov;
579 if (!prov) {
580 VALUE wrapper = TypedData_Wrap_Struct(0, &crypt_prov_type, 0);
581 if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
582 prov = INVALID_HCRYPTPROV;
583 }
584 old_prov = (HCRYPTPROV)ATOMIC_PTR_CAS(perm_prov, 0, prov);
585 if (LIKELY(!old_prov)) { /* no other threads acquired */
586 if (prov != INVALID_HCRYPTPROV) {
587 DATA_PTR(wrapper) = (void *)prov;
588 rb_vm_register_global_object(wrapper);
589 }
590 }
591 else { /* another thread acquired */
592 if (prov != INVALID_HCRYPTPROV) {
593 CryptReleaseContext(prov, 0);
594 }
595 prov = old_prov;
596 }
597 }
598 if (prov == INVALID_HCRYPTPROV) return -1;
599 while (size > 0) {
600 DWORD n = (size > (size_t)DWORD_MAX) ? DWORD_MAX : (DWORD)size;
601 if (!CryptGenRandom(prov, n, seed)) return -1;
602 seed = (char *)seed + n;
603 size -= n;
604 }
605 return 0;
606}
607# else
608# define fill_random_bytes_crypt(seed, size) -1
609# endif
610
611static int
612fill_random_bytes_bcrypt(void *seed, size_t size)
613{
614 while (size > 0) {
615 ULONG n = (size > (size_t)ULONG_MAX) ? LONG_MAX : (ULONG)size;
616 if (BCryptGenRandom(NULL, seed, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG))
617 return -1;
618 seed = (char *)seed + n;
619 size -= n;
620 }
621 return 0;
622}
623
624static int
625fill_random_bytes_lib(void *seed, size_t size)
626{
627 if (fill_random_bytes_bcrypt(seed, size) == 0) return 0;
628 return fill_random_bytes_crypt(seed, size);
629}
630#else
631# define fill_random_bytes_lib(seed, size) -1
632#endif
633
634/* fill random bytes by dedicated syscall */
635#if 0
636#elif defined HAVE_GETRANDOM
637static int
638fill_random_bytes_syscall(void *seed, size_t size, int need_secure)
639{
640 static rb_atomic_t try_syscall = 1;
641 if (try_syscall) {
642 size_t offset = 0;
643 int flags = 0;
644 if (!need_secure)
645 flags = GRND_NONBLOCK;
646 do {
647 errno = 0;
648 ssize_t ret = getrandom(((char*)seed) + offset, size - offset, flags);
649 if (ret == -1) {
650 ATOMIC_SET(try_syscall, 0);
651 return -1;
652 }
653 offset += (size_t)ret;
654 } while (offset < size);
655 return 0;
656 }
657 return -1;
658}
659#elif defined(HAVE_GETENTROPY)
660/*
661 * The Open Group Base Specifications Issue 8 - IEEE Std 1003.1-2024
662 * https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html
663 *
664 * NOTE: `getentropy`(3) on Linux is implemented using `getrandom`(2),
665 * prefer the latter over this if both are defined.
666 */
667#ifndef GETENTROPY_MAX
668# define GETENTROPY_MAX 256
669#endif
670static int
671fill_random_bytes_syscall(void *seed, size_t size, int need_secure)
672{
673 unsigned char *p = (unsigned char *)seed;
674 while (size) {
675 size_t len = size < GETENTROPY_MAX ? size : GETENTROPY_MAX;
676 if (getentropy(p, len) != 0) {
677 return -1;
678 }
679 p += len;
680 size -= len;
681 }
682 return 0;
683}
684#else
685# define fill_random_bytes_syscall(seed, size, need_secure) -1
686#endif
687
688int
689ruby_fill_random_bytes(void *seed, size_t size, int need_secure)
690{
691 int ret = fill_random_bytes_syscall(seed, size, need_secure);
692 if (ret == 0) return ret;
693 if (fill_random_bytes_lib(seed, size) == 0) return 0;
694 return fill_random_bytes_urandom(seed, size);
695}
696
697/* cnt must be 4 or more */
698static void
699fill_random_seed(uint32_t *seed, size_t cnt, bool try_bytes)
700{
701 static rb_atomic_t n = 0;
702#if defined HAVE_CLOCK_GETTIME
703 struct timespec tv;
704#elif defined HAVE_GETTIMEOFDAY
705 struct timeval tv;
706#endif
707 size_t len = cnt * sizeof(*seed);
708
709 if (try_bytes) {
710 fill_random_bytes(seed, len, FALSE);
711 return;
712 }
713
714 memset(seed, 0, len);
715#if defined HAVE_CLOCK_GETTIME
716 clock_gettime(CLOCK_REALTIME, &tv);
717 seed[0] ^= tv.tv_nsec;
718#elif defined HAVE_GETTIMEOFDAY
719 gettimeofday(&tv, 0);
720 seed[0] ^= tv.tv_usec;
721#endif
722 seed[1] ^= (uint32_t)tv.tv_sec;
723#if SIZEOF_TIME_T > SIZEOF_INT
724 seed[0] ^= (uint32_t)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
725#endif
726 seed[2] ^= getpid() ^ (ATOMIC_FETCH_ADD(n, 1) << 16);
727 seed[3] ^= (uint32_t)(VALUE)&seed;
728#if SIZEOF_VOIDP > SIZEOF_INT
729 seed[2] ^= (uint32_t)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
730#endif
731}
732
733static VALUE
734make_seed_value(uint32_t *ptr, size_t len)
735{
736 VALUE seed;
737
738 if (ptr[len-1] <= 1) {
739 /* set leading-zero-guard */
740 ptr[len++] = 1;
741 }
742
743 seed = rb_integer_unpack(ptr, len, sizeof(uint32_t), 0,
745
746 return seed;
747}
748
749#define with_random_seed(size, add, try_bytes) \
750 for (uint32_t seedbuf[(size)+(add)], loop = (fill_random_seed(seedbuf, (size), try_bytes), 1); \
751 loop; explicit_bzero(seedbuf, (size)*sizeof(seedbuf[0])), loop = 0)
752
753/*
754 * call-seq: Random.new_seed -> integer
755 *
756 * Returns an arbitrary seed value. This is used by Random.new
757 * when no seed value is specified as an argument.
758 *
759 * Random.new_seed #=> 115032730400174366788466674494640623225
760 */
761static VALUE
762random_seed(VALUE _)
763{
764 VALUE v;
765 with_random_seed(DEFAULT_SEED_CNT, 1, true) {
766 v = make_seed_value(seedbuf, DEFAULT_SEED_CNT);
767 }
768 return v;
769}
770
771/*
772 * call-seq: Random.urandom(size) -> string
773 *
774 * Returns a string, using platform providing features.
775 * Returned value is expected to be a cryptographically secure
776 * pseudo-random number in binary form.
777 * This method raises a RuntimeError if the feature provided by platform
778 * failed to prepare the result.
779 *
780 * In 2017, Linux manpage random(7) writes that "no cryptographic
781 * primitive available today can hope to promise more than 256 bits of
782 * security". So it might be questionable to pass size > 32 to this
783 * method.
784 *
785 * Random.urandom(8) #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"
786 */
787static VALUE
788random_raw_seed(VALUE self, VALUE size)
789{
790 long n = NUM2ULONG(size);
791 VALUE buf = rb_str_new(0, n);
792 if (n == 0) return buf;
793 if (fill_random_bytes(RSTRING_PTR(buf), n, TRUE))
794 rb_raise(rb_eRuntimeError, "failed to get urandom");
795 return buf;
796}
797
798/*
799 * call-seq: prng.seed -> integer
800 *
801 * Returns the seed value used to initialize the generator. This may be used to
802 * initialize another generator with the same state at a later time, causing it
803 * to produce the same sequence of numbers.
804 *
805 * prng1 = Random.new(1234)
806 * prng1.seed #=> 1234
807 * prng1.rand(100) #=> 47
808 *
809 * prng2 = Random.new(prng1.seed)
810 * prng2.rand(100) #=> 47
811 */
812static VALUE
813random_get_seed(VALUE obj)
814{
815 return get_rnd(obj)->seed;
816}
817
818/* :nodoc: */
819static VALUE
820rand_mt_copy(VALUE obj, VALUE orig)
821{
822 rb_random_mt_t *rnd1, *rnd2;
823 struct MT *mt;
824
825 if (!OBJ_INIT_COPY(obj, orig)) return obj;
826
827 rnd1 = get_rnd_mt(obj);
828 rnd2 = get_rnd_mt(orig);
829 mt = &rnd1->mt;
830
831 *rnd1 = *rnd2;
832 mt->next = mt->state + numberof(mt->state) - mt->left + 1;
833 return obj;
834}
835
836static VALUE
837mt_state(const struct MT *mt)
838{
839 return rb_integer_unpack(mt->state, numberof(mt->state),
840 sizeof(*mt->state), 0,
842}
843
844/* :nodoc: */
845static VALUE
846rand_mt_state(VALUE obj)
847{
848 rb_random_mt_t *rnd = get_rnd_mt(obj);
849 return mt_state(&rnd->mt);
850}
851
852/* :nodoc: */
853static VALUE
854random_s_state(VALUE klass)
855{
856 return mt_state(&default_rand()->mt);
857}
858
859/* :nodoc: */
860static VALUE
861rand_mt_left(VALUE obj)
862{
863 rb_random_mt_t *rnd = get_rnd_mt(obj);
864 return INT2FIX(rnd->mt.left);
865}
866
867/* :nodoc: */
868static VALUE
869random_s_left(VALUE klass)
870{
871 return INT2FIX(default_rand()->mt.left);
872}
873
874/* :nodoc: */
875static VALUE
876rand_mt_dump(VALUE obj)
877{
878 rb_random_mt_t *rnd = rb_check_typeddata(obj, &random_mt_type);
879 VALUE dump = rb_ary_new2(3);
880
881 rb_ary_push(dump, mt_state(&rnd->mt));
882 rb_ary_push(dump, INT2FIX(rnd->mt.left));
883 rb_ary_push(dump, rnd->base.seed);
884
885 return dump;
886}
887
888/* :nodoc: */
889static VALUE
890rand_mt_load(VALUE obj, VALUE dump)
891{
892 rb_random_mt_t *rnd = rb_check_typeddata(obj, &random_mt_type);
893 struct MT *mt = &rnd->mt;
894 VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
895 unsigned long x;
896
897 rb_check_copyable(obj, dump);
898 Check_Type(dump, T_ARRAY);
899 switch (RARRAY_LEN(dump)) {
900 case 3:
901 seed = RARRAY_AREF(dump, 2);
902 case 2:
903 left = RARRAY_AREF(dump, 1);
904 case 1:
905 state = RARRAY_AREF(dump, 0);
906 break;
907 default:
908 rb_raise(rb_eArgError, "wrong dump data");
909 }
910 rb_integer_pack(state, mt->state, numberof(mt->state),
911 sizeof(*mt->state), 0,
913 x = NUM2ULONG(left);
914 if (x > numberof(mt->state) || x == 0) {
915 rb_raise(rb_eArgError, "wrong value");
916 }
917 mt->left = (unsigned int)x;
918 mt->next = mt->state + numberof(mt->state) - x + 1;
919 rnd->base.seed = rb_to_int(seed);
920
921 return obj;
922}
923
924static void
925rand_mt_init_int32(rb_random_t *rnd, uint32_t data)
926{
927 struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
928 init_genrand(mt, data);
929}
930
931static void
932rand_mt_init(rb_random_t *rnd, const uint32_t *buf, size_t len)
933{
934 struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
935 init_by_array(mt, buf, (int)len);
936}
937
938static unsigned int
939rand_mt_get_int32(rb_random_t *rnd)
940{
941 struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
942 return genrand_int32(mt);
943}
944
945static void
946rand_mt_get_bytes(rb_random_t *rnd, void *ptr, size_t n)
947{
948 rb_rand_bytes_int32(rand_mt_get_int32, rnd, ptr, n);
949}
950
951/*
952 * call-seq:
953 * srand(number = Random.new_seed) -> old_seed
954 *
955 * Seeds the system pseudo-random number generator, with +number+.
956 * The previous seed value is returned.
957 *
958 * If +number+ is omitted, seeds the generator using a source of entropy
959 * provided by the operating system, if available (/dev/urandom on Unix systems
960 * or the RSA cryptographic provider on Windows), which is then combined with
961 * the time, the process id, and a sequence number.
962 *
963 * srand may be used to ensure repeatable sequences of pseudo-random numbers
964 * between different runs of the program. By setting the seed to a known value,
965 * programs can be made deterministic during testing.
966 *
967 * srand 1234 # => 268519324636777531569100071560086917274
968 * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
969 * [ rand(10), rand(1000) ] # => [4, 664]
970 * srand 1234 # => 1234
971 * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
972 */
973
974static VALUE
975rb_f_srand(int argc, VALUE *argv, VALUE obj)
976{
977 VALUE seed, old;
978 rb_random_mt_t *r = rand_mt_start(default_rand());
979
980 if (rb_check_arity(argc, 0, 1) == 0) {
981 seed = random_seed(obj);
982 }
983 else {
984 seed = rb_to_int(argv[0]);
985 }
986 old = r->base.seed;
987 rand_init(&random_mt_if, &r->base, seed);
988 r->base.seed = seed;
989
990 return old;
991}
992
993static unsigned long
994make_mask(unsigned long x)
995{
996 x = x | x >> 1;
997 x = x | x >> 2;
998 x = x | x >> 4;
999 x = x | x >> 8;
1000 x = x | x >> 16;
1001#if 4 < SIZEOF_LONG
1002 x = x | x >> 32;
1003#endif
1004 return x;
1005}
1006
1007static unsigned long
1008limited_rand(const rb_random_interface_t *rng, rb_random_t *rnd, unsigned long limit)
1009{
1010 /* mt must be initialized */
1011 unsigned long val, mask;
1012
1013 if (!limit) return 0;
1014 mask = make_mask(limit);
1015
1016#if 4 < SIZEOF_LONG
1017 if (0xffffffff < limit) {
1018 int i;
1019 retry:
1020 val = 0;
1021 for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
1022 if ((mask >> (i * 32)) & 0xffffffff) {
1023 val |= (unsigned long)rng->get_int32(rnd) << (i * 32);
1024 val &= mask;
1025 if (limit < val)
1026 goto retry;
1027 }
1028 }
1029 return val;
1030 }
1031#endif
1032
1033 do {
1034 val = rng->get_int32(rnd) & mask;
1035 } while (limit < val);
1036 return val;
1037}
1038
1039static VALUE
1040limited_big_rand(const rb_random_interface_t *rng, rb_random_t *rnd, VALUE limit)
1041{
1042 /* mt must be initialized */
1043
1044 uint32_t mask;
1045 long i;
1046 int boundary;
1047
1048 size_t len;
1049 uint32_t *tmp, *lim_array, *rnd_array;
1050 VALUE vtmp;
1051 VALUE val;
1052
1053 len = rb_absint_numwords(limit, 32, NULL);
1054 tmp = ALLOCV_N(uint32_t, vtmp, len*2);
1055 lim_array = tmp;
1056 rnd_array = tmp + len;
1057 rb_integer_pack(limit, lim_array, len, sizeof(uint32_t), 0,
1059
1060 retry:
1061 mask = 0;
1062 boundary = 1;
1063 for (i = len-1; 0 <= i; i--) {
1064 uint32_t r = 0;
1065 uint32_t lim = lim_array[i];
1066 mask = mask ? 0xffffffff : (uint32_t)make_mask(lim);
1067 if (mask) {
1068 r = rng->get_int32(rnd) & mask;
1069 if (boundary) {
1070 if (lim < r)
1071 goto retry;
1072 if (r < lim)
1073 boundary = 0;
1074 }
1075 }
1076 rnd_array[i] = r;
1077 }
1078 val = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0,
1080 ALLOCV_END(vtmp);
1081
1082 return val;
1083}
1084
1085/*
1086 * Returns random unsigned long value in [0, +limit+].
1087 *
1088 * Note that +limit+ is included, and the range of the argument and the
1089 * return value depends on environments.
1090 */
1091unsigned long
1092rb_genrand_ulong_limited(unsigned long limit)
1093{
1094 rb_random_mt_t *mt = default_mt();
1095 return limited_rand(&random_mt_if, &mt->base, limit);
1096}
1097
1098static VALUE
1099obj_random_bytes(VALUE obj, void *p, long n)
1100{
1101 VALUE len = LONG2NUM(n);
1102 VALUE v = rb_funcallv_public(obj, id_bytes, 1, &len);
1103 long l;
1104 Check_Type(v, T_STRING);
1105 l = RSTRING_LEN(v);
1106 if (l < n)
1107 rb_raise(rb_eRangeError, "random data too short %ld", l);
1108 else if (l > n)
1109 rb_raise(rb_eRangeError, "random data too long %ld", l);
1110 if (p) memcpy(p, RSTRING_PTR(v), n);
1111 return v;
1112}
1113
1114static unsigned int
1115random_int32(const rb_random_interface_t *rng, rb_random_t *rnd)
1116{
1117 return rng->get_int32(rnd);
1118}
1119
1120unsigned int
1122{
1123 rb_random_t *rnd = try_get_rnd(obj);
1124 if (!rnd) {
1125 uint32_t x;
1126 obj_random_bytes(obj, &x, sizeof(x));
1127 return (unsigned int)x;
1128 }
1129 return random_int32(try_rand_if(obj, rnd), rnd);
1130}
1131
1132static double
1133random_real(VALUE obj, rb_random_t *rnd, int excl)
1134{
1135 uint32_t a, b;
1136
1137 if (!rnd) {
1138 uint32_t x[2] = {0, 0};
1139 obj_random_bytes(obj, x, sizeof(x));
1140 a = x[0];
1141 b = x[1];
1142 }
1143 else {
1144 const rb_random_interface_t *rng = try_rand_if(obj, rnd);
1145 if (rng->get_real) return rng->get_real(rnd, excl);
1146 a = random_int32(rng, rnd);
1147 b = random_int32(rng, rnd);
1148 }
1149 return rb_int_pair_to_real(a, b, excl);
1150}
1151
1152double
1153rb_int_pair_to_real(uint32_t a, uint32_t b, int excl)
1154{
1155 if (excl) {
1156 return int_pair_to_real_exclusive(a, b);
1157 }
1158 else {
1159 return int_pair_to_real_inclusive(a, b);
1160 }
1161}
1162
1163double
1165{
1166 rb_random_t *rnd = try_get_rnd(obj);
1167 if (!rnd) {
1168 VALUE v = rb_funcallv(obj, id_rand, 0, 0);
1169 double d = NUM2DBL(v);
1170 if (d < 0.0) {
1171 rb_raise(rb_eRangeError, "random number too small %g", d);
1172 }
1173 else if (d >= 1.0) {
1174 rb_raise(rb_eRangeError, "random number too big %g", d);
1175 }
1176 return d;
1177 }
1178 return random_real(obj, rnd, TRUE);
1179}
1180
1181static inline VALUE
1182ulong_to_num_plus_1(unsigned long n)
1183{
1184#if HAVE_LONG_LONG
1185 return ULL2NUM((LONG_LONG)n+1);
1186#else
1187 if (n >= ULONG_MAX) {
1188 return rb_big_plus(ULONG2NUM(n), INT2FIX(1));
1189 }
1190 return ULONG2NUM(n+1);
1191#endif
1192}
1193
1194static unsigned long
1195random_ulong_limited(VALUE obj, rb_random_t *rnd, unsigned long limit)
1196{
1197 if (!limit) return 0;
1198 if (!rnd) {
1199 const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit);
1200 const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t);
1201 const unsigned long mask = ~(~0UL << w);
1202 const unsigned long full =
1203 (size_t)n >= sizeof(unsigned long) ? ~0UL :
1204 ~(~0UL << n * CHAR_BIT);
1205 unsigned long val, bits = 0, rest = 0;
1206 do {
1207 if (mask & ~rest) {
1208 union {uint32_t u32; unsigned long ul;} buf;
1209 obj_random_bytes(obj, &buf, n);
1210 rest = full;
1211 bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul;
1212 }
1213 val = bits;
1214 bits >>= w;
1215 rest >>= w;
1216 val &= mask;
1217 } while (limit < val);
1218 return val;
1219 }
1220 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1221}
1222
1223unsigned long
1224rb_random_ulong_limited(VALUE obj, unsigned long limit)
1225{
1226 rb_random_t *rnd = try_get_rnd(obj);
1227 if (!rnd) {
1228 VALUE lim = ulong_to_num_plus_1(limit);
1229 VALUE v = rb_to_int(rb_funcallv_public(obj, id_rand, 1, &lim));
1230 unsigned long r = NUM2ULONG(v);
1231 if (rb_num_negative_p(v)) {
1232 rb_raise(rb_eRangeError, "random number too small %ld", r);
1233 }
1234 if (r > limit) {
1235 rb_raise(rb_eRangeError, "random number too big %ld", r);
1236 }
1237 return r;
1238 }
1239 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1240}
1241
1242static VALUE
1243random_ulong_limited_big(VALUE obj, rb_random_t *rnd, VALUE vmax)
1244{
1245 if (!rnd) {
1246 VALUE v, vtmp;
1247 size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz);
1248 uint32_t *tmp = ALLOCV_N(uint32_t, vtmp, len * 2);
1249 uint32_t mask = (uint32_t)~0 >> nlz;
1250 uint32_t *lim_array = tmp;
1251 uint32_t *rnd_array = tmp + len;
1253 rb_integer_pack(vmax, lim_array, len, sizeof(uint32_t), 0, flag);
1254
1255 retry:
1256 obj_random_bytes(obj, rnd_array, len * sizeof(uint32_t));
1257 rnd_array[0] &= mask;
1258 for (i = 0; i < len; ++i) {
1259 if (lim_array[i] < rnd_array[i])
1260 goto retry;
1261 if (rnd_array[i] < lim_array[i])
1262 break;
1263 }
1264 v = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0, flag);
1265 ALLOCV_END(vtmp);
1266 return v;
1267 }
1268 return limited_big_rand(try_rand_if(obj, rnd), rnd, vmax);
1269}
1270
1271static VALUE
1272rand_bytes(const rb_random_interface_t *rng, rb_random_t *rnd, long n)
1273{
1274 VALUE bytes;
1275 char *ptr;
1276
1277 bytes = rb_str_new(0, n);
1278 ptr = RSTRING_PTR(bytes);
1279 rng->get_bytes(rnd, ptr, n);
1280 return bytes;
1281}
1282
1283/*
1284 * call-seq: prng.bytes(size) -> string
1285 *
1286 * Returns a random binary string containing +size+ bytes.
1287 *
1288 * random_string = Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
1289 * random_string.size # => 10
1290 */
1291static VALUE
1292random_bytes(VALUE obj, VALUE len)
1293{
1294 rb_random_t *rnd = try_get_rnd(obj);
1295 return rand_bytes(rb_rand_if(obj), rnd, NUM2LONG(rb_to_int(len)));
1296}
1297
1298void
1300 rb_random_t *rnd, void *p, size_t n)
1301{
1302 char *ptr = p;
1303 unsigned int r, i;
1304 for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
1305 r = get_int32(rnd);
1306 i = SIZEOF_INT32;
1307 do {
1308 *ptr++ = (char)r;
1309 r >>= CHAR_BIT;
1310 } while (--i);
1311 }
1312 if (n > 0) {
1313 r = get_int32(rnd);
1314 do {
1315 *ptr++ = (char)r;
1316 r >>= CHAR_BIT;
1317 } while (--n);
1318 }
1319}
1320
1321VALUE
1323{
1324 rb_random_t *rnd = try_get_rnd(obj);
1325 if (!rnd) {
1326 return obj_random_bytes(obj, NULL, n);
1327 }
1328 return rand_bytes(try_rand_if(obj, rnd), rnd, n);
1329}
1330
1331/*
1332 * call-seq: Random.bytes(size) -> string
1333 *
1334 * Returns a random binary string.
1335 * The argument +size+ specifies the length of the returned string.
1336 */
1337static VALUE
1338random_s_bytes(VALUE obj, VALUE len)
1339{
1340 rb_random_t *rnd = rand_start(default_rand());
1341 return rand_bytes(&random_mt_if, rnd, NUM2LONG(rb_to_int(len)));
1342}
1343
1344/*
1345 * call-seq: Random.seed -> integer
1346 *
1347 * Returns the seed value used to initialize the Ruby system PRNG.
1348 * This may be used to initialize another generator with the same
1349 * state at a later time, causing it to produce the same sequence of
1350 * numbers.
1351 *
1352 * Random.seed #=> 1234
1353 * prng1 = Random.new(Random.seed)
1354 * prng1.seed #=> 1234
1355 * prng1.rand(100) #=> 47
1356 * Random.seed #=> 1234
1357 * Random.rand(100) #=> 47
1358 */
1359static VALUE
1360random_s_seed(VALUE obj)
1361{
1362 rb_random_mt_t *rnd = rand_mt_start(default_rand());
1363 return rnd->base.seed;
1364}
1365
1366static VALUE
1367range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp)
1368{
1369 VALUE beg, end;
1370
1371 if (!rb_range_values(vmax, &beg, &end, exclp)) return Qfalse;
1372 if (begp) *begp = beg;
1373 if (NIL_P(beg)) return Qnil;
1374 if (endp) *endp = end;
1375 if (NIL_P(end)) return Qnil;
1376 return rb_check_funcall_default(end, id_minus, 1, begp, Qfalse);
1377}
1378
1379static VALUE
1380rand_int(VALUE obj, rb_random_t *rnd, VALUE vmax, int restrictive)
1381{
1382 /* mt must be initialized */
1383 unsigned long r;
1384
1385 if (FIXNUM_P(vmax)) {
1386 long max = FIX2LONG(vmax);
1387 if (!max) return Qnil;
1388 if (max < 0) {
1389 if (restrictive) return Qnil;
1390 max = -max;
1391 }
1392 r = random_ulong_limited(obj, rnd, (unsigned long)max - 1);
1393 return ULONG2NUM(r);
1394 }
1395 else {
1396 VALUE ret;
1397 if (rb_bigzero_p(vmax)) return Qnil;
1398 if (!BIGNUM_SIGN(vmax)) {
1399 if (restrictive) return Qnil;
1400 vmax = rb_big_uminus(vmax);
1401 }
1402 vmax = rb_big_minus(vmax, INT2FIX(1));
1403 if (FIXNUM_P(vmax)) {
1404 long max = FIX2LONG(vmax);
1405 if (max == -1) return Qnil;
1406 r = random_ulong_limited(obj, rnd, max);
1407 return LONG2NUM(r);
1408 }
1409 ret = random_ulong_limited_big(obj, rnd, vmax);
1410 RB_GC_GUARD(vmax);
1411 return ret;
1412 }
1413}
1414
1415static void
1416domain_error(void)
1417{
1418 VALUE error = INT2FIX(EDOM);
1420}
1421
1422NORETURN(static void invalid_argument(VALUE));
1423static void
1424invalid_argument(VALUE arg0)
1425{
1426 rb_raise(rb_eArgError, "invalid argument - %"PRIsVALUE, arg0);
1427}
1428
1429static VALUE
1430check_random_number(VALUE v, const VALUE *argv)
1431{
1432 switch (v) {
1433 case Qfalse:
1434 (void)NUM2LONG(argv[0]);
1435 break;
1436 case Qnil:
1437 invalid_argument(argv[0]);
1438 }
1439 return v;
1440}
1441
1442static inline double
1443float_value(VALUE v)
1444{
1445 double x = RFLOAT_VALUE(v);
1446 if (!isfinite(x)) {
1447 domain_error();
1448 }
1449 return x;
1450}
1451
1452static inline VALUE
1453rand_range(VALUE obj, rb_random_t* rnd, VALUE range)
1454{
1455 VALUE beg = Qundef, end = Qundef, vmax, v;
1456 int excl = 0;
1457
1458 if ((v = vmax = range_values(range, &beg, &end, &excl)) == Qfalse)
1459 return Qfalse;
1460 if (NIL_P(v)) domain_error();
1461 if (!RB_FLOAT_TYPE_P(vmax) && (v = rb_check_to_int(vmax), !NIL_P(v))) {
1462 long max;
1463 vmax = v;
1464 v = Qnil;
1465 fixnum:
1466 if (FIXNUM_P(vmax)) {
1467 if ((max = FIX2LONG(vmax) - excl) >= 0) {
1468 unsigned long r = random_ulong_limited(obj, rnd, (unsigned long)max);
1469 v = ULONG2NUM(r);
1470 }
1471 }
1472 else if (BUILTIN_TYPE(vmax) == T_BIGNUM && BIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
1473 vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
1474 if (FIXNUM_P(vmax)) {
1475 excl = 0;
1476 goto fixnum;
1477 }
1478 v = random_ulong_limited_big(obj, rnd, vmax);
1479 }
1480 }
1481 else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
1482 int scale = 1;
1483 double max = RFLOAT_VALUE(v), mid = 0.5, r;
1484 if (isinf(max)) {
1485 double min = float_value(rb_to_float(beg)) / 2.0;
1486 max = float_value(rb_to_float(end)) / 2.0;
1487 scale = 2;
1488 mid = max + min;
1489 max -= min;
1490 }
1491 else if (isnan(max)) {
1492 domain_error();
1493 }
1494 v = Qnil;
1495 if (max > 0.0) {
1496 r = random_real(obj, rnd, excl);
1497 if (scale > 1) {
1498 return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
1499 }
1500 v = rb_float_new(r * max);
1501 }
1502 else if (max == 0.0 && !excl) {
1503 v = rb_float_new(0.0);
1504 }
1505 }
1506
1507 if (FIXNUM_P(beg) && FIXNUM_P(v)) {
1508 long x = FIX2LONG(beg) + FIX2LONG(v);
1509 return LONG2NUM(x);
1510 }
1511 switch (TYPE(v)) {
1512 case T_NIL:
1513 break;
1514 case T_BIGNUM:
1515 return rb_big_plus(v, beg);
1516 case T_FLOAT: {
1517 VALUE f = rb_check_to_float(beg);
1518 if (!NIL_P(f)) {
1519 return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f));
1520 }
1521 }
1522 default:
1523 return rb_funcallv(beg, id_plus, 1, &v);
1524 }
1525
1526 return v;
1527}
1528
1529static VALUE rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd);
1530
1531/*
1532 * call-seq:
1533 * prng.rand -> float
1534 * prng.rand(max) -> number
1535 * prng.rand(range) -> number
1536 *
1537 * When +max+ is an Integer, +rand+ returns a random integer greater than
1538 * or equal to zero and less than +max+. Unlike Kernel.rand, when +max+
1539 * is a negative integer or zero, +rand+ raises an ArgumentError.
1540 *
1541 * prng = Random.new
1542 * prng.rand(100) # => 42
1543 *
1544 * When +max+ is a Float, +rand+ returns a random floating point number
1545 * between 0.0 and +max+, including 0.0 and excluding +max+.
1546 *
1547 * prng.rand(1.5) # => 1.4600282860034115
1548 *
1549 * When +range+ is a Range, +rand+ returns a random number where
1550 * <code>range.member?(number) == true</code>.
1551 *
1552 * prng.rand(5..9) # => one of [5, 6, 7, 8, 9]
1553 * prng.rand(5...9) # => one of [5, 6, 7, 8]
1554 * prng.rand(5.0..9.0) # => between 5.0 and 9.0, including 9.0
1555 * prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0
1556 *
1557 * Both the beginning and ending values of the range must respond to subtract
1558 * (<tt>-</tt>) and add (<tt>+</tt>)methods, or rand will raise an
1559 * ArgumentError.
1560 */
1561static VALUE
1562random_rand(int argc, VALUE *argv, VALUE obj)
1563{
1564 VALUE v = rand_random(argc, argv, obj, try_get_rnd(obj));
1565 check_random_number(v, argv);
1566 return v;
1567}
1568
1569static VALUE
1570rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd)
1571{
1572 VALUE vmax, v;
1573
1574 if (rb_check_arity(argc, 0, 1) == 0) {
1575 return rb_float_new(random_real(obj, rnd, TRUE));
1576 }
1577 vmax = argv[0];
1578 if (NIL_P(vmax)) return Qnil;
1579 if (!RB_FLOAT_TYPE_P(vmax)) {
1580 v = rb_check_to_int(vmax);
1581 if (!NIL_P(v)) return rand_int(obj, rnd, v, 1);
1582 }
1583 v = rb_check_to_float(vmax);
1584 if (!NIL_P(v)) {
1585 const double max = float_value(v);
1586 if (max < 0.0) {
1587 return Qnil;
1588 }
1589 else {
1590 double r = random_real(obj, rnd, TRUE);
1591 if (max > 0.0) r *= max;
1592 return rb_float_new(r);
1593 }
1594 }
1595 return rand_range(obj, rnd, vmax);
1596}
1597
1598/*
1599 * call-seq:
1600 * prng.random_number -> float
1601 * prng.random_number(max) -> number
1602 * prng.random_number(range) -> number
1603 * prng.rand -> float
1604 * prng.rand(max) -> number
1605 * prng.rand(range) -> number
1606 *
1607 * Generates formatted random number from raw random bytes.
1608 * See Random#rand.
1609 */
1610static VALUE
1611rand_random_number(int argc, VALUE *argv, VALUE obj)
1612{
1613 rb_random_t *rnd = try_get_rnd(obj);
1614 VALUE v = rand_random(argc, argv, obj, rnd);
1615 if (NIL_P(v)) v = rand_random(0, 0, obj, rnd);
1616 else if (!v) invalid_argument(argv[0]);
1617 return v;
1618}
1619
1620/*
1621 * call-seq:
1622 * prng1 == prng2 -> true or false
1623 *
1624 * Returns true if the two generators have the same internal state, otherwise
1625 * false. Equivalent generators will return the same sequence of
1626 * pseudo-random numbers. Two generators will generally have the same state
1627 * only if they were initialized with the same seed
1628 *
1629 * Random.new == Random.new # => false
1630 * Random.new(1234) == Random.new(1234) # => true
1631 *
1632 * and have the same invocation history.
1633 *
1634 * prng1 = Random.new(1234)
1635 * prng2 = Random.new(1234)
1636 * prng1 == prng2 # => true
1637 *
1638 * prng1.rand # => 0.1915194503788923
1639 * prng1 == prng2 # => false
1640 *
1641 * prng2.rand # => 0.1915194503788923
1642 * prng1 == prng2 # => true
1643 */
1644static VALUE
1645rand_mt_equal(VALUE self, VALUE other)
1646{
1647 rb_random_mt_t *r1, *r2;
1648 if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
1649 r1 = get_rnd_mt(self);
1650 r2 = get_rnd_mt(other);
1651 if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
1652 if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
1653 if (r1->mt.left != r2->mt.left) return Qfalse;
1654 return rb_equal(r1->base.seed, r2->base.seed);
1655}
1656
1657/*
1658 * call-seq:
1659 * rand(max=0) -> number
1660 *
1661 * If called without an argument, or if <tt>max.to_i.abs == 0</tt>, rand
1662 * returns a pseudo-random floating point number between 0.0 and 1.0,
1663 * including 0.0 and excluding 1.0.
1664 *
1665 * rand #=> 0.2725926052826416
1666 *
1667 * When +max.abs+ is greater than or equal to 1, +rand+ returns a pseudo-random
1668 * integer greater than or equal to 0 and less than +max.to_i.abs+.
1669 *
1670 * rand(100) #=> 12
1671 *
1672 * When +max+ is a Range, +rand+ returns a random number where
1673 * <code>range.member?(number) == true</code>.
1674 *
1675 * Negative or floating point values for +max+ are allowed, but may give
1676 * surprising results.
1677 *
1678 * rand(-100) # => 87
1679 * rand(-0.5) # => 0.8130921818028143
1680 * rand(1.9) # equivalent to rand(1), which is always 0
1681 *
1682 * Kernel.srand may be used to ensure that sequences of random numbers are
1683 * reproducible between different runs of a program.
1684 *
1685 * See also Random.rand.
1686 */
1687
1688static VALUE
1689rb_f_rand(int argc, VALUE *argv, VALUE obj)
1690{
1691 VALUE vmax;
1692 rb_random_t *rnd = rand_start(default_rand());
1693
1694 if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
1695 VALUE v = rand_range(obj, rnd, vmax);
1696 if (v != Qfalse) return v;
1697 vmax = rb_to_int(vmax);
1698 if (vmax != INT2FIX(0)) {
1699 v = rand_int(obj, rnd, vmax, 0);
1700 if (!NIL_P(v)) return v;
1701 }
1702 }
1703 return DBL2NUM(random_real(obj, rnd, TRUE));
1704}
1705
1706/*
1707 * call-seq:
1708 * Random.rand -> float
1709 * Random.rand(max) -> number
1710 * Random.rand(range) -> number
1711 *
1712 * Returns a random number using the Ruby system PRNG.
1713 *
1714 * See also Random#rand.
1715 */
1716static VALUE
1717random_s_rand(int argc, VALUE *argv, VALUE obj)
1718{
1719 VALUE v = rand_random(argc, argv, Qnil, rand_start(default_rand()));
1720 check_random_number(v, argv);
1721 return v;
1722}
1723
1724#define SIP_HASH_STREAMING 0
1725#define sip_hash13 ruby_sip_hash13
1726#if !defined _WIN32 && !defined BYTE_ORDER
1727# ifdef WORDS_BIGENDIAN
1728# define BYTE_ORDER BIG_ENDIAN
1729# else
1730# define BYTE_ORDER LITTLE_ENDIAN
1731# endif
1732# ifndef LITTLE_ENDIAN
1733# define LITTLE_ENDIAN 1234
1734# endif
1735# ifndef BIG_ENDIAN
1736# define BIG_ENDIAN 4321
1737# endif
1738#endif
1739#include "siphash.c"
1740
1741typedef struct {
1742 st_index_t hash;
1743 uint8_t sip[16];
1744} hash_salt_t;
1745
1746static union {
1747 hash_salt_t key;
1748 uint32_t u32[type_roomof(hash_salt_t, uint32_t)];
1749} hash_salt;
1750
1751static void
1752init_hash_salt(struct MT *mt)
1753{
1754 int i;
1755
1756 for (i = 0; i < numberof(hash_salt.u32); ++i)
1757 hash_salt.u32[i] = genrand_int32(mt);
1758}
1759
1760NO_SANITIZE("unsigned-integer-overflow", extern st_index_t rb_hash_start(st_index_t h));
1761st_index_t
1762rb_hash_start(st_index_t h)
1763{
1764 return st_hash_start(hash_salt.key.hash + h);
1765}
1766
1767st_index_t
1768rb_memhash(const void *ptr, long len)
1769{
1770 sip_uint64_t h = sip_hash13(hash_salt.key.sip, ptr, len);
1771#ifdef HAVE_UINT64_T
1772 return (st_index_t)h;
1773#else
1774 return (st_index_t)(h.u32[0] ^ h.u32[1]);
1775#endif
1776}
1777
1778/* Initialize Ruby internal seeds. This function is called at very early stage
1779 * of Ruby startup. Thus, you can't use Ruby's object. */
1780void
1781Init_RandomSeedCore(void)
1782{
1783 if (!fill_random_bytes(&hash_salt, sizeof(hash_salt), FALSE)) return;
1784
1785 /*
1786 If failed to fill siphash's salt with random data, expand less random
1787 data with MT.
1788
1789 Don't reuse this MT for default_rand(). default_rand()::seed shouldn't
1790 provide a hint that an attacker guess siphash's seed.
1791 */
1792 struct MT mt;
1793
1794 with_random_seed(DEFAULT_SEED_CNT, 0, false) {
1795 init_by_array(&mt, seedbuf, DEFAULT_SEED_CNT);
1796 }
1797
1798 init_hash_salt(&mt);
1799 explicit_bzero(&mt, sizeof(mt));
1800}
1801
1802void
1804{
1805 rb_random_mt_t *r = default_rand();
1806 uninit_genrand(&r->mt);
1807 r->base.seed = INT2FIX(0);
1808}
1809
1810/*
1811 * Document-class: Random
1812 *
1813 * Random provides an interface to Ruby's pseudo-random number generator, or
1814 * PRNG. The PRNG produces a deterministic sequence of bits which approximate
1815 * true randomness. The sequence may be represented by integers, floats, or
1816 * binary strings.
1817 *
1818 * The generator may be initialized with either a system-generated or
1819 * user-supplied seed value by using Random.srand.
1820 *
1821 * The class method Random.rand provides the base functionality of Kernel.rand
1822 * along with better handling of floating point values. These are both
1823 * interfaces to the Ruby system PRNG.
1824 *
1825 * Random.new will create a new PRNG with a state independent of the Ruby
1826 * system PRNG, allowing multiple generators with different seed values or
1827 * sequence positions to exist simultaneously. Random objects can be
1828 * marshaled, allowing sequences to be saved and resumed.
1829 *
1830 * PRNGs are currently implemented as a modified Mersenne Twister with a period
1831 * of 2**19937-1. As this algorithm is _not_ for cryptographical use, you must
1832 * use SecureRandom for security purpose, instead of this PRNG.
1833 *
1834 * See also Random::Formatter module that adds convenience methods to generate
1835 * various forms of random data.
1836 */
1837
1838void
1839InitVM_Random(void)
1840{
1841 VALUE base;
1842 ID id_base = rb_intern_const("Base");
1843
1844 rb_define_global_function("srand", rb_f_srand, -1);
1845 rb_define_global_function("rand", rb_f_rand, -1);
1846
1847 base = rb_define_class_id(id_base, rb_cObject);
1848 rb_undef_alloc_func(base);
1849 rb_cRandom = rb_define_class("Random", base);
1850 rb_const_set(rb_cRandom, id_base, base);
1851 rb_define_alloc_func(rb_cRandom, random_alloc);
1852 rb_define_method(base, "initialize", random_init, -1);
1853 rb_define_method(base, "rand", random_rand, -1);
1854 rb_define_method(base, "bytes", random_bytes, 1);
1855 rb_define_method(base, "seed", random_get_seed, 0);
1856 rb_define_method(rb_cRandom, "initialize_copy", rand_mt_copy, 1);
1857 rb_define_private_method(rb_cRandom, "marshal_dump", rand_mt_dump, 0);
1858 rb_define_private_method(rb_cRandom, "marshal_load", rand_mt_load, 1);
1859 rb_define_private_method(rb_cRandom, "state", rand_mt_state, 0);
1860 rb_define_private_method(rb_cRandom, "left", rand_mt_left, 0);
1861 rb_define_method(rb_cRandom, "==", rand_mt_equal, 1);
1862
1863#if 0 /* for RDoc: it can't handle unnamed base class */
1864 rb_define_method(rb_cRandom, "initialize", random_init, -1);
1865 rb_define_method(rb_cRandom, "rand", random_rand, -1);
1866 rb_define_method(rb_cRandom, "bytes", random_bytes, 1);
1867 rb_define_method(rb_cRandom, "seed", random_get_seed, 0);
1868#endif
1869
1870 rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
1871 rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1);
1872 rb_define_singleton_method(rb_cRandom, "bytes", random_s_bytes, 1);
1873 rb_define_singleton_method(rb_cRandom, "seed", random_s_seed, 0);
1874 rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
1875 rb_define_singleton_method(rb_cRandom, "urandom", random_raw_seed, 1);
1876 rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
1877 rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
1878
1879 {
1880 /*
1881 * Generate a random number in the given range as Random does
1882 *
1883 * prng.random_number #=> 0.5816771641321361
1884 * prng.random_number(1000) #=> 485
1885 * prng.random_number(1..6) #=> 3
1886 * prng.rand #=> 0.5816771641321361
1887 * prng.rand(1000) #=> 485
1888 * prng.rand(1..6) #=> 3
1889 */
1890 VALUE m = rb_define_module_under(rb_cRandom, "Formatter");
1891 rb_include_module(base, m);
1892 rb_extend_object(base, m);
1893 rb_define_method(m, "random_number", rand_random_number, -1);
1894 rb_define_method(m, "rand", rand_random_number, -1);
1895 }
1896
1897 default_rand_key = rb_ractor_local_storage_ptr_newkey(&default_rand_key_storage_type);
1898}
1899
1900#undef rb_intern
1901void
1902Init_Random(void)
1903{
1904 id_rand = rb_intern("rand");
1905 id_bytes = rb_intern("bytes");
1906
1907 InitVM(Random);
1908}
std::atomic< unsigned > rb_atomic_t
Type that is eligible for atomic operations.
Definition atomic.h:69
#define LONG_LONG
Definition long_long.h:38
#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.
Definition class.c:1696
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:1479
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1784
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
Definition class.c:1625
VALUE rb_define_class_id(ID id, VALUE super)
This is a very badly designed API that creates an anonymous class.
Definition class.c:1449
#define TYPE(_)
Old name of rb_type.
Definition value_type.h:108
#define NUM2ULONG
Old name of RB_NUM2ULONG.
Definition long.h:52
#define OBJ_INIT_COPY(obj, orig)
Old name of RB_OBJ_INIT_COPY.
Definition object.h:41
#define RFLOAT_VALUE
Old name of rb_float_value.
Definition double.h:28
#define T_STRING
Old name of RUBY_T_STRING.
Definition value_type.h:78
#define xfree
Old name of ruby_xfree.
Definition xmalloc.h:58
#define Qundef
Old name of RUBY_Qundef.
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define T_NIL
Old name of RUBY_T_NIL.
Definition value_type.h:72
#define T_FLOAT
Old name of RUBY_T_FLOAT.
Definition value_type.h:64
#define T_BIGNUM
Old name of RUBY_T_BIGNUM.
Definition value_type.h:57
#define ULONG2NUM
Old name of RB_ULONG2NUM.
Definition long.h:60
#define ZALLOC
Old name of RB_ZALLOC.
Definition memory.h:402
#define CLASS_OF
Old name of rb_class_of.
Definition globals.h:205
#define NUM2DBL
Old name of rb_num2dbl.
Definition double.h:27
#define LONG2NUM
Old name of RB_LONG2NUM.
Definition long.h:50
#define ULL2NUM
Old name of RB_ULL2NUM.
Definition long_long.h:31
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define T_ARRAY
Old name of RUBY_T_ARRAY.
Definition value_type.h:56
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
Definition memory.h:405
#define DBL2NUM
Old name of rb_float_new.
Definition double.h:29
#define BUILTIN_TYPE
Old name of RB_BUILTIN_TYPE.
Definition value_type.h:85
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define FIXNUM_P
Old name of RB_FIXNUM_P.
#define rb_ary_new2
Old name of rb_ary_new_capa.
Definition array.h:657
#define ALLOCV_END
Old name of RB_ALLOCV_END.
Definition memory.h:406
void rb_exc_raise(VALUE mesg)
Raises an exception in the current thread.
Definition eval.c:682
int rb_typeddata_is_kind_of(VALUE obj, const rb_data_type_t *data_type)
Checks if the given object is of given kind.
Definition error.c:1380
void rb_check_copyable(VALUE obj, VALUE orig)
Ensures that the passed object can be initialize_copy relationship.
Definition error.c:4226
VALUE rb_eRangeError
RangeError exception.
Definition error.c:1434
VALUE rb_eTypeError
TypeError exception.
Definition error.c:1430
VALUE rb_eRuntimeError
RuntimeError exception.
Definition error.c:1428
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.
Definition error.c:1397
VALUE rb_eSystemCallError
SystemCallError exception.
Definition error.c:1450
VALUE rb_check_to_int(VALUE val)
Identical to rb_check_to_integer(), except it uses #to_int for conversion.
Definition object.c:3229
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2166
VALUE rb_check_to_float(VALUE val)
This is complicated.
Definition object.c:3694
VALUE rb_cRandom
Random class.
Definition random.c:236
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:243
VALUE rb_to_float(VALUE val)
Identical to rb_check_to_float(), except it raises on error.
Definition object.c:3684
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:175
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3223
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.
Definition vm_eval.c:1168
VALUE rb_ary_push(VALUE ary, VALUE elem)
Special case of rb_ary_cat() that it adds only one element.
#define INTEGER_PACK_NATIVE_BYTE_ORDER
Means either INTEGER_PACK_MSBYTE_FIRST or INTEGER_PACK_LSBYTE_FIRST, depending on the host processor'...
Definition bignum.h:546
#define INTEGER_PACK_MSWORD_FIRST
Stores/interprets the most significant word as the first word.
Definition bignum.h:525
#define INTEGER_PACK_LSWORD_FIRST
Stores/interprets the least significant word as the first word.
Definition bignum.h:528
static int rb_check_arity(int argc, int min, int max)
Ensures that the passed integer is in the passed range.
Definition error.h:284
void rb_update_max_fd(int fd)
Informs the interpreter that the passed fd can be the max.
Definition io.c:248
int rb_cloexec_open(const char *pathname, int flags, mode_t mode)
Opens a file that closes on exec.
Definition io.c:328
unsigned long rb_genrand_ulong_limited(unsigned long i)
Generates a random number whose upper limit is i.
Definition random.c:1092
double rb_random_real(VALUE rnd)
Identical to rb_genrand_real(), except it generates using the passed RNG.
Definition random.c:1164
unsigned int rb_random_int32(VALUE rnd)
Identical to rb_genrand_int32(), except it generates using the passed RNG.
Definition random.c:1121
void rb_reset_random_seed(void)
Resets the RNG behind rb_genrand_int32()/rb_genrand_real().
Definition random.c:1803
VALUE rb_random_bytes(VALUE rnd, long n)
Generates a String of random bytes.
Definition random.c:1322
double rb_genrand_real(void)
Generates a double random number.
Definition random.c:206
unsigned long rb_random_ulong_limited(VALUE rnd, unsigned long limit)
Identical to rb_genrand_ulong_limited(), except it generates using the passed RNG.
Definition random.c:1224
unsigned int rb_genrand_int32(void)
Generates a 32 bit random number.
Definition random.c:199
int rb_range_values(VALUE range, VALUE *begp, VALUE *endp, int *exclp)
Deconstructs a range into its components.
Definition range.c:1838
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1768
#define rb_str_new(str, len)
Allocates an instance of rb_cString.
Definition string.h:1498
st_index_t rb_hash_start(st_index_t i)
Starts a series of hashing.
Definition random.c:1762
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:4050
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1419
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().
Definition symbol.h:284
int len
Length of the buffer.
Definition io.h:8
void * rb_ractor_local_storage_ptr(rb_ractor_local_key_t key)
Identical to rb_ractor_local_storage_value() except the return type.
Definition ractor.c:2141
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.
Definition ractor.c:2153
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().
Definition ractor.c:2045
#define RB_RANDOM_INTERFACE_DEFINE(prefix)
This utility macro expands to the names declared using RB_RANDOM_INTERFACE_DECLARE.
Definition random.h:210
struct rb_random_struct rb_random_t
Definition random.h:53
#define RB_RANDOM_INTERFACE_DECLARE(prefix)
This utility macro defines 4 functions named prefix_init, prefix_init_int32, prefix_get_int32,...
Definition random.h:182
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...
Definition random.c:1299
unsigned int rb_random_get_int32_func(rb_random_t *rng)
This is the type of functions called from your object's #rand method.
Definition random.h:88
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.
Definition random.c:1153
static const rb_random_interface_t * rb_rand_if(VALUE obj)
Queries the interface of the passed random object.
Definition random.h:333
void rb_random_base_init(rb_random_t *rnd)
Initialises an allocated rb_random_t instance.
Definition random.c:336
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define RARRAY_LEN
Just another name of rb_array_len.
Definition rarray.h:51
#define RARRAY_AREF(a, i)
Definition rarray.h:403
#define DATA_PTR(obj)
Convenient getter macro.
Definition rdata.h:67
#define TypedData_Get_Struct(obj, type, data_type, sval)
Obtains a C struct from inside of a wrapper Ruby object.
Definition rtypeddata.h:515
#define TypedData_Wrap_Struct(klass, data_type, sval)
Converts sval, a pointer to your struct, into a Ruby object.
Definition rtypeddata.h:450
#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...
Definition rtypeddata.h:497
static const struct rb_data_type_struct * RTYPEDDATA_TYPE(VALUE obj)
Queries for the type of given object.
Definition rtypeddata.h:601
#define errno
Ractor-aware version of errno.
Definition ruby.h:388
#define InitVM(ext)
This macro is for internal use.
Definition ruby.h:231
#define _(args)
This was a transition path from K&R to ANSI.
Definition stdarg.h:35
Definition mt19937.c:62
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:203
Type that defines a ractor-local storage.
Definition ractor.h:21
PRNG algorithmic interface, analogous to Ruby level classes.
Definition random.h:114
rb_random_init_func * init
Function to initialize from uint32_t array.
Definition random.h:131
rb_random_init_int32_func * init_int32
Function to initialize from single uint32_t.
Definition random.h:134
size_t default_seed_bits
Number of bits of seed numbers.
Definition random.h:116
rb_random_get_int32_func * get_int32
Function to obtain a random integer.
Definition random.h:137
rb_random_get_real_func * get_real
Function to obtain a random double.
Definition random.h:175
rb_random_get_bytes_func * get_bytes
Function to obtain a series of random bytes.
Definition random.h:155
struct rb_random_interface_t::@58 version
Major/minor versions of this interface.
Base components of the random interface.
Definition random.h:49
VALUE seed
Seed, passed through e.g.
Definition random.h:51
uintptr_t ID
Type that represents a Ruby identifier such as a variable name.
Definition value.h:52
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40
static bool RB_FLOAT_TYPE_P(VALUE obj)
Queries if the object is an instance of rb_cFloat.
Definition value_type.h:264
static void Check_Type(VALUE v, enum ruby_value_type t)
Identical to RB_TYPE_P(), except it raises exceptions on predication failure.
Definition value_type.h:433