Ruby 3.4.5p51 (2025-07-16 revision 20cda200d3ce092571d0b5d342dadca69636cb0f)
random.c
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)
537static int
538fill_random_bytes_lib(void *buf, size_t size)
539{
540#if (defined(__OpenBSD__) && OpenBSD >= 201411) || \
541 (defined(__NetBSD__) && __NetBSD_Version__ >= 700000000) || \
542 (defined(__FreeBSD__) && __FreeBSD_version >= 1200079)
543 arc4random_buf(buf, size);
544 return 0;
545#else
546 return -1;
547#endif
548}
549#elif defined(_WIN32)
550
551#ifndef DWORD_MAX
552# define DWORD_MAX (~(DWORD)0UL)
553#endif
554
555# if defined(CRYPT_VERIFYCONTEXT)
556/* Although HCRYPTPROV is not a HANDLE, it looks like
557 * INVALID_HANDLE_VALUE is not a valid value */
558static const HCRYPTPROV INVALID_HCRYPTPROV = (HCRYPTPROV)INVALID_HANDLE_VALUE;
559
560static void
561release_crypt(void *p)
562{
563 HCRYPTPROV *ptr = p;
564 HCRYPTPROV prov = (HCRYPTPROV)ATOMIC_PTR_EXCHANGE(*ptr, INVALID_HCRYPTPROV);
565 if (prov && prov != INVALID_HCRYPTPROV) {
566 CryptReleaseContext(prov, 0);
567 }
568}
569
570static const rb_data_type_t crypt_prov_type = {
571 "HCRYPTPROV",
572 {0, release_crypt,},
573 0, 0, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_EMBEDDABLE
574};
575
576static int
577fill_random_bytes_crypt(void *seed, size_t size)
578{
579 static HCRYPTPROV perm_prov;
580 HCRYPTPROV prov = perm_prov, old_prov;
581 if (!prov) {
582 VALUE wrapper = TypedData_Wrap_Struct(0, &crypt_prov_type, 0);
583 if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
584 prov = INVALID_HCRYPTPROV;
585 }
586 old_prov = (HCRYPTPROV)ATOMIC_PTR_CAS(perm_prov, 0, prov);
587 if (LIKELY(!old_prov)) { /* no other threads acquired */
588 if (prov != INVALID_HCRYPTPROV) {
589 DATA_PTR(wrapper) = (void *)prov;
590 rb_vm_register_global_object(wrapper);
591 }
592 }
593 else { /* another thread acquired */
594 if (prov != INVALID_HCRYPTPROV) {
595 CryptReleaseContext(prov, 0);
596 }
597 prov = old_prov;
598 }
599 }
600 if (prov == INVALID_HCRYPTPROV) return -1;
601 while (size > 0) {
602 DWORD n = (size > (size_t)DWORD_MAX) ? DWORD_MAX : (DWORD)size;
603 if (!CryptGenRandom(prov, n, seed)) return -1;
604 seed = (char *)seed + n;
605 size -= n;
606 }
607 return 0;
608}
609# else
610# define fill_random_bytes_crypt(seed, size) -1
611# endif
612
613static int
614fill_random_bytes_bcrypt(void *seed, size_t size)
615{
616 while (size > 0) {
617 ULONG n = (size > (size_t)ULONG_MAX) ? LONG_MAX : (ULONG)size;
618 if (BCryptGenRandom(NULL, seed, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG))
619 return -1;
620 seed = (char *)seed + n;
621 size -= n;
622 }
623 return 0;
624}
625
626static int
627fill_random_bytes_lib(void *seed, size_t size)
628{
629 if (fill_random_bytes_bcrypt(seed, size) == 0) return 0;
630 return fill_random_bytes_crypt(seed, size);
631}
632#else
633# define fill_random_bytes_lib(seed, size) -1
634#endif
635
636/* fill random bytes by dedicated syscall */
637#if 0
638#elif defined HAVE_GETRANDOM
639static int
640fill_random_bytes_syscall(void *seed, size_t size, int need_secure)
641{
642 static rb_atomic_t try_syscall = 1;
643 if (try_syscall) {
644 size_t offset = 0;
645 int flags = 0;
646 if (!need_secure)
647 flags = GRND_NONBLOCK;
648 do {
649 errno = 0;
650 ssize_t ret = getrandom(((char*)seed) + offset, size - offset, flags);
651 if (ret == -1) {
652 ATOMIC_SET(try_syscall, 0);
653 return -1;
654 }
655 offset += (size_t)ret;
656 } while (offset < size);
657 return 0;
658 }
659 return -1;
660}
661#elif defined(HAVE_GETENTROPY)
662/*
663 * The Open Group Base Specifications Issue 8 - IEEE Std 1003.1-2024
664 * https://pubs.opengroup.org/onlinepubs/9799919799/functions/getentropy.html
665 *
666 * NOTE: `getentropy`(3) on Linux is implemented using `getrandom`(2),
667 * prefer the latter over this if both are defined.
668 */
669#ifndef GETENTROPY_MAX
670# define GETENTROPY_MAX 256
671#endif
672static int
673fill_random_bytes_syscall(void *seed, size_t size, int need_secure)
674{
675 unsigned char *p = (unsigned char *)seed;
676 while (size) {
677 size_t len = size < GETENTROPY_MAX ? size : GETENTROPY_MAX;
678 if (getentropy(p, len) != 0) {
679 return -1;
680 }
681 p += len;
682 size -= len;
683 }
684 return 0;
685}
686#else
687# define fill_random_bytes_syscall(seed, size, need_secure) -1
688#endif
689
690int
691ruby_fill_random_bytes(void *seed, size_t size, int need_secure)
692{
693 int ret = fill_random_bytes_syscall(seed, size, need_secure);
694 if (ret == 0) return ret;
695 if (fill_random_bytes_lib(seed, size) == 0) return 0;
696 return fill_random_bytes_urandom(seed, size);
697}
698
699/* cnt must be 4 or more */
700static void
701fill_random_seed(uint32_t *seed, size_t cnt, bool try_bytes)
702{
703 static rb_atomic_t n = 0;
704#if defined HAVE_CLOCK_GETTIME
705 struct timespec tv;
706#elif defined HAVE_GETTIMEOFDAY
707 struct timeval tv;
708#endif
709 size_t len = cnt * sizeof(*seed);
710
711 if (try_bytes) {
712 fill_random_bytes(seed, len, FALSE);
713 return;
714 }
715
716 memset(seed, 0, len);
717#if defined HAVE_CLOCK_GETTIME
718 clock_gettime(CLOCK_REALTIME, &tv);
719 seed[0] ^= tv.tv_nsec;
720#elif defined HAVE_GETTIMEOFDAY
721 gettimeofday(&tv, 0);
722 seed[0] ^= tv.tv_usec;
723#endif
724 seed[1] ^= (uint32_t)tv.tv_sec;
725#if SIZEOF_TIME_T > SIZEOF_INT
726 seed[0] ^= (uint32_t)((time_t)tv.tv_sec >> SIZEOF_INT * CHAR_BIT);
727#endif
728 seed[2] ^= getpid() ^ (ATOMIC_FETCH_ADD(n, 1) << 16);
729 seed[3] ^= (uint32_t)(VALUE)&seed;
730#if SIZEOF_VOIDP > SIZEOF_INT
731 seed[2] ^= (uint32_t)((VALUE)&seed >> SIZEOF_INT * CHAR_BIT);
732#endif
733}
734
735static VALUE
736make_seed_value(uint32_t *ptr, size_t len)
737{
738 VALUE seed;
739
740 if (ptr[len-1] <= 1) {
741 /* set leading-zero-guard */
742 ptr[len++] = 1;
743 }
744
745 seed = rb_integer_unpack(ptr, len, sizeof(uint32_t), 0,
747
748 return seed;
749}
750
751#define with_random_seed(size, add, try_bytes) \
752 for (uint32_t seedbuf[(size)+(add)], loop = (fill_random_seed(seedbuf, (size), try_bytes), 1); \
753 loop; explicit_bzero(seedbuf, (size)*sizeof(seedbuf[0])), loop = 0)
754
755/*
756 * call-seq: Random.new_seed -> integer
757 *
758 * Returns an arbitrary seed value. This is used by Random.new
759 * when no seed value is specified as an argument.
760 *
761 * Random.new_seed #=> 115032730400174366788466674494640623225
762 */
763static VALUE
764random_seed(VALUE _)
765{
766 VALUE v;
767 with_random_seed(DEFAULT_SEED_CNT, 1, true) {
768 v = make_seed_value(seedbuf, DEFAULT_SEED_CNT);
769 }
770 return v;
771}
772
773/*
774 * call-seq: Random.urandom(size) -> string
775 *
776 * Returns a string, using platform providing features.
777 * Returned value is expected to be a cryptographically secure
778 * pseudo-random number in binary form.
779 * This method raises a RuntimeError if the feature provided by platform
780 * failed to prepare the result.
781 *
782 * In 2017, Linux manpage random(7) writes that "no cryptographic
783 * primitive available today can hope to promise more than 256 bits of
784 * security". So it might be questionable to pass size > 32 to this
785 * method.
786 *
787 * Random.urandom(8) #=> "\x78\x41\xBA\xAF\x7D\xEA\xD8\xEA"
788 */
789static VALUE
790random_raw_seed(VALUE self, VALUE size)
791{
792 long n = NUM2ULONG(size);
793 VALUE buf = rb_str_new(0, n);
794 if (n == 0) return buf;
795 if (fill_random_bytes(RSTRING_PTR(buf), n, TRUE))
796 rb_raise(rb_eRuntimeError, "failed to get urandom");
797 return buf;
798}
799
800/*
801 * call-seq: prng.seed -> integer
802 *
803 * Returns the seed value used to initialize the generator. This may be used to
804 * initialize another generator with the same state at a later time, causing it
805 * to produce the same sequence of numbers.
806 *
807 * prng1 = Random.new(1234)
808 * prng1.seed #=> 1234
809 * prng1.rand(100) #=> 47
810 *
811 * prng2 = Random.new(prng1.seed)
812 * prng2.rand(100) #=> 47
813 */
814static VALUE
815random_get_seed(VALUE obj)
816{
817 return get_rnd(obj)->seed;
818}
819
820/* :nodoc: */
821static VALUE
822rand_mt_copy(VALUE obj, VALUE orig)
823{
824 rb_random_mt_t *rnd1, *rnd2;
825 struct MT *mt;
826
827 if (!OBJ_INIT_COPY(obj, orig)) return obj;
828
829 rnd1 = get_rnd_mt(obj);
830 rnd2 = get_rnd_mt(orig);
831 mt = &rnd1->mt;
832
833 *rnd1 = *rnd2;
834 mt->next = mt->state + numberof(mt->state) - mt->left + 1;
835 return obj;
836}
837
838static VALUE
839mt_state(const struct MT *mt)
840{
841 return rb_integer_unpack(mt->state, numberof(mt->state),
842 sizeof(*mt->state), 0,
844}
845
846/* :nodoc: */
847static VALUE
848rand_mt_state(VALUE obj)
849{
850 rb_random_mt_t *rnd = get_rnd_mt(obj);
851 return mt_state(&rnd->mt);
852}
853
854/* :nodoc: */
855static VALUE
856random_s_state(VALUE klass)
857{
858 return mt_state(&default_rand()->mt);
859}
860
861/* :nodoc: */
862static VALUE
863rand_mt_left(VALUE obj)
864{
865 rb_random_mt_t *rnd = get_rnd_mt(obj);
866 return INT2FIX(rnd->mt.left);
867}
868
869/* :nodoc: */
870static VALUE
871random_s_left(VALUE klass)
872{
873 return INT2FIX(default_rand()->mt.left);
874}
875
876/* :nodoc: */
877static VALUE
878rand_mt_dump(VALUE obj)
879{
880 rb_random_mt_t *rnd = rb_check_typeddata(obj, &random_mt_type);
881 VALUE dump = rb_ary_new2(3);
882
883 rb_ary_push(dump, mt_state(&rnd->mt));
884 rb_ary_push(dump, INT2FIX(rnd->mt.left));
885 rb_ary_push(dump, rnd->base.seed);
886
887 return dump;
888}
889
890/* :nodoc: */
891static VALUE
892rand_mt_load(VALUE obj, VALUE dump)
893{
894 rb_random_mt_t *rnd = rb_check_typeddata(obj, &random_mt_type);
895 struct MT *mt = &rnd->mt;
896 VALUE state, left = INT2FIX(1), seed = INT2FIX(0);
897 unsigned long x;
898
899 rb_check_copyable(obj, dump);
900 Check_Type(dump, T_ARRAY);
901 switch (RARRAY_LEN(dump)) {
902 case 3:
903 seed = RARRAY_AREF(dump, 2);
904 case 2:
905 left = RARRAY_AREF(dump, 1);
906 case 1:
907 state = RARRAY_AREF(dump, 0);
908 break;
909 default:
910 rb_raise(rb_eArgError, "wrong dump data");
911 }
912 rb_integer_pack(state, mt->state, numberof(mt->state),
913 sizeof(*mt->state), 0,
915 x = NUM2ULONG(left);
916 if (x > numberof(mt->state) || x == 0) {
917 rb_raise(rb_eArgError, "wrong value");
918 }
919 mt->left = (unsigned int)x;
920 mt->next = mt->state + numberof(mt->state) - x + 1;
921 rnd->base.seed = rb_to_int(seed);
922
923 return obj;
924}
925
926static void
927rand_mt_init_int32(rb_random_t *rnd, uint32_t data)
928{
929 struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
930 init_genrand(mt, data);
931}
932
933static void
934rand_mt_init(rb_random_t *rnd, const uint32_t *buf, size_t len)
935{
936 struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
937 init_by_array(mt, buf, (int)len);
938}
939
940static unsigned int
941rand_mt_get_int32(rb_random_t *rnd)
942{
943 struct MT *mt = &((rb_random_mt_t *)rnd)->mt;
944 return genrand_int32(mt);
945}
946
947static void
948rand_mt_get_bytes(rb_random_t *rnd, void *ptr, size_t n)
949{
950 rb_rand_bytes_int32(rand_mt_get_int32, rnd, ptr, n);
951}
952
953/*
954 * call-seq:
955 * srand(number = Random.new_seed) -> old_seed
956 *
957 * Seeds the system pseudo-random number generator, with +number+.
958 * The previous seed value is returned.
959 *
960 * If +number+ is omitted, seeds the generator using a source of entropy
961 * provided by the operating system, if available (/dev/urandom on Unix systems
962 * or the RSA cryptographic provider on Windows), which is then combined with
963 * the time, the process id, and a sequence number.
964 *
965 * srand may be used to ensure repeatable sequences of pseudo-random numbers
966 * between different runs of the program. By setting the seed to a known value,
967 * programs can be made deterministic during testing.
968 *
969 * srand 1234 # => 268519324636777531569100071560086917274
970 * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
971 * [ rand(10), rand(1000) ] # => [4, 664]
972 * srand 1234 # => 1234
973 * [ rand, rand ] # => [0.1915194503788923, 0.6221087710398319]
974 */
975
976static VALUE
977rb_f_srand(int argc, VALUE *argv, VALUE obj)
978{
979 VALUE seed, old;
980 rb_random_mt_t *r = rand_mt_start(default_rand());
981
982 if (rb_check_arity(argc, 0, 1) == 0) {
983 seed = random_seed(obj);
984 }
985 else {
986 seed = rb_to_int(argv[0]);
987 }
988 old = r->base.seed;
989 rand_init(&random_mt_if, &r->base, seed);
990 r->base.seed = seed;
991
992 return old;
993}
994
995static unsigned long
996make_mask(unsigned long x)
997{
998 x = x | x >> 1;
999 x = x | x >> 2;
1000 x = x | x >> 4;
1001 x = x | x >> 8;
1002 x = x | x >> 16;
1003#if 4 < SIZEOF_LONG
1004 x = x | x >> 32;
1005#endif
1006 return x;
1007}
1008
1009static unsigned long
1010limited_rand(const rb_random_interface_t *rng, rb_random_t *rnd, unsigned long limit)
1011{
1012 /* mt must be initialized */
1013 unsigned long val, mask;
1014
1015 if (!limit) return 0;
1016 mask = make_mask(limit);
1017
1018#if 4 < SIZEOF_LONG
1019 if (0xffffffff < limit) {
1020 int i;
1021 retry:
1022 val = 0;
1023 for (i = SIZEOF_LONG/SIZEOF_INT32-1; 0 <= i; i--) {
1024 if ((mask >> (i * 32)) & 0xffffffff) {
1025 val |= (unsigned long)rng->get_int32(rnd) << (i * 32);
1026 val &= mask;
1027 if (limit < val)
1028 goto retry;
1029 }
1030 }
1031 return val;
1032 }
1033#endif
1034
1035 do {
1036 val = rng->get_int32(rnd) & mask;
1037 } while (limit < val);
1038 return val;
1039}
1040
1041static VALUE
1042limited_big_rand(const rb_random_interface_t *rng, rb_random_t *rnd, VALUE limit)
1043{
1044 /* mt must be initialized */
1045
1046 uint32_t mask;
1047 long i;
1048 int boundary;
1049
1050 size_t len;
1051 uint32_t *tmp, *lim_array, *rnd_array;
1052 VALUE vtmp;
1053 VALUE val;
1054
1055 len = rb_absint_numwords(limit, 32, NULL);
1056 tmp = ALLOCV_N(uint32_t, vtmp, len*2);
1057 lim_array = tmp;
1058 rnd_array = tmp + len;
1059 rb_integer_pack(limit, lim_array, len, sizeof(uint32_t), 0,
1061
1062 retry:
1063 mask = 0;
1064 boundary = 1;
1065 for (i = len-1; 0 <= i; i--) {
1066 uint32_t r = 0;
1067 uint32_t lim = lim_array[i];
1068 mask = mask ? 0xffffffff : (uint32_t)make_mask(lim);
1069 if (mask) {
1070 r = rng->get_int32(rnd) & mask;
1071 if (boundary) {
1072 if (lim < r)
1073 goto retry;
1074 if (r < lim)
1075 boundary = 0;
1076 }
1077 }
1078 rnd_array[i] = r;
1079 }
1080 val = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0,
1082 ALLOCV_END(vtmp);
1083
1084 return val;
1085}
1086
1087/*
1088 * Returns random unsigned long value in [0, +limit+].
1089 *
1090 * Note that +limit+ is included, and the range of the argument and the
1091 * return value depends on environments.
1092 */
1093unsigned long
1094rb_genrand_ulong_limited(unsigned long limit)
1095{
1096 rb_random_mt_t *mt = default_mt();
1097 return limited_rand(&random_mt_if, &mt->base, limit);
1098}
1099
1100static VALUE
1101obj_random_bytes(VALUE obj, void *p, long n)
1102{
1103 VALUE len = LONG2NUM(n);
1104 VALUE v = rb_funcallv_public(obj, id_bytes, 1, &len);
1105 long l;
1106 Check_Type(v, T_STRING);
1107 l = RSTRING_LEN(v);
1108 if (l < n)
1109 rb_raise(rb_eRangeError, "random data too short %ld", l);
1110 else if (l > n)
1111 rb_raise(rb_eRangeError, "random data too long %ld", l);
1112 if (p) memcpy(p, RSTRING_PTR(v), n);
1113 return v;
1114}
1115
1116static unsigned int
1117random_int32(const rb_random_interface_t *rng, rb_random_t *rnd)
1118{
1119 return rng->get_int32(rnd);
1120}
1121
1122unsigned int
1124{
1125 rb_random_t *rnd = try_get_rnd(obj);
1126 if (!rnd) {
1127 uint32_t x;
1128 obj_random_bytes(obj, &x, sizeof(x));
1129 return (unsigned int)x;
1130 }
1131 return random_int32(try_rand_if(obj, rnd), rnd);
1132}
1133
1134static double
1135random_real(VALUE obj, rb_random_t *rnd, int excl)
1136{
1137 uint32_t a, b;
1138
1139 if (!rnd) {
1140 uint32_t x[2] = {0, 0};
1141 obj_random_bytes(obj, x, sizeof(x));
1142 a = x[0];
1143 b = x[1];
1144 }
1145 else {
1146 const rb_random_interface_t *rng = try_rand_if(obj, rnd);
1147 if (rng->get_real) return rng->get_real(rnd, excl);
1148 a = random_int32(rng, rnd);
1149 b = random_int32(rng, rnd);
1150 }
1151 return rb_int_pair_to_real(a, b, excl);
1152}
1153
1154double
1155rb_int_pair_to_real(uint32_t a, uint32_t b, int excl)
1156{
1157 if (excl) {
1158 return int_pair_to_real_exclusive(a, b);
1159 }
1160 else {
1161 return int_pair_to_real_inclusive(a, b);
1162 }
1163}
1164
1165double
1167{
1168 rb_random_t *rnd = try_get_rnd(obj);
1169 if (!rnd) {
1170 VALUE v = rb_funcallv(obj, id_rand, 0, 0);
1171 double d = NUM2DBL(v);
1172 if (d < 0.0) {
1173 rb_raise(rb_eRangeError, "random number too small %g", d);
1174 }
1175 else if (d >= 1.0) {
1176 rb_raise(rb_eRangeError, "random number too big %g", d);
1177 }
1178 return d;
1179 }
1180 return random_real(obj, rnd, TRUE);
1181}
1182
1183static inline VALUE
1184ulong_to_num_plus_1(unsigned long n)
1185{
1186#if HAVE_LONG_LONG
1187 return ULL2NUM((LONG_LONG)n+1);
1188#else
1189 if (n >= ULONG_MAX) {
1190 return rb_big_plus(ULONG2NUM(n), INT2FIX(1));
1191 }
1192 return ULONG2NUM(n+1);
1193#endif
1194}
1195
1196static unsigned long
1197random_ulong_limited(VALUE obj, rb_random_t *rnd, unsigned long limit)
1198{
1199 if (!limit) return 0;
1200 if (!rnd) {
1201 const int w = sizeof(limit) * CHAR_BIT - nlz_long(limit);
1202 const int n = w > 32 ? sizeof(unsigned long) : sizeof(uint32_t);
1203 const unsigned long mask = ~(~0UL << w);
1204 const unsigned long full =
1205 (size_t)n >= sizeof(unsigned long) ? ~0UL :
1206 ~(~0UL << n * CHAR_BIT);
1207 unsigned long val, bits = 0, rest = 0;
1208 do {
1209 if (mask & ~rest) {
1210 union {uint32_t u32; unsigned long ul;} buf;
1211 obj_random_bytes(obj, &buf, n);
1212 rest = full;
1213 bits = (n == sizeof(uint32_t)) ? buf.u32 : buf.ul;
1214 }
1215 val = bits;
1216 bits >>= w;
1217 rest >>= w;
1218 val &= mask;
1219 } while (limit < val);
1220 return val;
1221 }
1222 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1223}
1224
1225unsigned long
1226rb_random_ulong_limited(VALUE obj, unsigned long limit)
1227{
1228 rb_random_t *rnd = try_get_rnd(obj);
1229 if (!rnd) {
1230 VALUE lim = ulong_to_num_plus_1(limit);
1231 VALUE v = rb_to_int(rb_funcallv_public(obj, id_rand, 1, &lim));
1232 unsigned long r = NUM2ULONG(v);
1233 if (rb_num_negative_p(v)) {
1234 rb_raise(rb_eRangeError, "random number too small %ld", r);
1235 }
1236 if (r > limit) {
1237 rb_raise(rb_eRangeError, "random number too big %ld", r);
1238 }
1239 return r;
1240 }
1241 return limited_rand(try_rand_if(obj, rnd), rnd, limit);
1242}
1243
1244static VALUE
1245random_ulong_limited_big(VALUE obj, rb_random_t *rnd, VALUE vmax)
1246{
1247 if (!rnd) {
1248 VALUE v, vtmp;
1249 size_t i, nlz, len = rb_absint_numwords(vmax, 32, &nlz);
1250 uint32_t *tmp = ALLOCV_N(uint32_t, vtmp, len * 2);
1251 uint32_t mask = (uint32_t)~0 >> nlz;
1252 uint32_t *lim_array = tmp;
1253 uint32_t *rnd_array = tmp + len;
1255 rb_integer_pack(vmax, lim_array, len, sizeof(uint32_t), 0, flag);
1256
1257 retry:
1258 obj_random_bytes(obj, rnd_array, len * sizeof(uint32_t));
1259 rnd_array[0] &= mask;
1260 for (i = 0; i < len; ++i) {
1261 if (lim_array[i] < rnd_array[i])
1262 goto retry;
1263 if (rnd_array[i] < lim_array[i])
1264 break;
1265 }
1266 v = rb_integer_unpack(rnd_array, len, sizeof(uint32_t), 0, flag);
1267 ALLOCV_END(vtmp);
1268 return v;
1269 }
1270 return limited_big_rand(try_rand_if(obj, rnd), rnd, vmax);
1271}
1272
1273static VALUE
1274rand_bytes(const rb_random_interface_t *rng, rb_random_t *rnd, long n)
1275{
1276 VALUE bytes;
1277 char *ptr;
1278
1279 bytes = rb_str_new(0, n);
1280 ptr = RSTRING_PTR(bytes);
1281 rng->get_bytes(rnd, ptr, n);
1282 return bytes;
1283}
1284
1285/*
1286 * call-seq: prng.bytes(size) -> string
1287 *
1288 * Returns a random binary string containing +size+ bytes.
1289 *
1290 * random_string = Random.new.bytes(10) # => "\xD7:R\xAB?\x83\xCE\xFAkO"
1291 * random_string.size # => 10
1292 */
1293static VALUE
1294random_bytes(VALUE obj, VALUE len)
1295{
1296 rb_random_t *rnd = try_get_rnd(obj);
1297 return rand_bytes(rb_rand_if(obj), rnd, NUM2LONG(rb_to_int(len)));
1298}
1299
1300void
1302 rb_random_t *rnd, void *p, size_t n)
1303{
1304 char *ptr = p;
1305 unsigned int r, i;
1306 for (; n >= SIZEOF_INT32; n -= SIZEOF_INT32) {
1307 r = get_int32(rnd);
1308 i = SIZEOF_INT32;
1309 do {
1310 *ptr++ = (char)r;
1311 r >>= CHAR_BIT;
1312 } while (--i);
1313 }
1314 if (n > 0) {
1315 r = get_int32(rnd);
1316 do {
1317 *ptr++ = (char)r;
1318 r >>= CHAR_BIT;
1319 } while (--n);
1320 }
1321}
1322
1323VALUE
1325{
1326 rb_random_t *rnd = try_get_rnd(obj);
1327 if (!rnd) {
1328 return obj_random_bytes(obj, NULL, n);
1329 }
1330 return rand_bytes(try_rand_if(obj, rnd), rnd, n);
1331}
1332
1333/*
1334 * call-seq: Random.bytes(size) -> string
1335 *
1336 * Returns a random binary string.
1337 * The argument +size+ specifies the length of the returned string.
1338 */
1339static VALUE
1340random_s_bytes(VALUE obj, VALUE len)
1341{
1342 rb_random_t *rnd = rand_start(default_rand());
1343 return rand_bytes(&random_mt_if, rnd, NUM2LONG(rb_to_int(len)));
1344}
1345
1346/*
1347 * call-seq: Random.seed -> integer
1348 *
1349 * Returns the seed value used to initialize the Ruby system PRNG.
1350 * This may be used to initialize another generator with the same
1351 * state at a later time, causing it to produce the same sequence of
1352 * numbers.
1353 *
1354 * Random.seed #=> 1234
1355 * prng1 = Random.new(Random.seed)
1356 * prng1.seed #=> 1234
1357 * prng1.rand(100) #=> 47
1358 * Random.seed #=> 1234
1359 * Random.rand(100) #=> 47
1360 */
1361static VALUE
1362random_s_seed(VALUE obj)
1363{
1364 rb_random_mt_t *rnd = rand_mt_start(default_rand());
1365 return rnd->base.seed;
1366}
1367
1368static VALUE
1369range_values(VALUE vmax, VALUE *begp, VALUE *endp, int *exclp)
1370{
1371 VALUE beg, end;
1372
1373 if (!rb_range_values(vmax, &beg, &end, exclp)) return Qfalse;
1374 if (begp) *begp = beg;
1375 if (NIL_P(beg)) return Qnil;
1376 if (endp) *endp = end;
1377 if (NIL_P(end)) return Qnil;
1378 return rb_check_funcall_default(end, id_minus, 1, begp, Qfalse);
1379}
1380
1381static VALUE
1382rand_int(VALUE obj, rb_random_t *rnd, VALUE vmax, int restrictive)
1383{
1384 /* mt must be initialized */
1385 unsigned long r;
1386
1387 if (FIXNUM_P(vmax)) {
1388 long max = FIX2LONG(vmax);
1389 if (!max) return Qnil;
1390 if (max < 0) {
1391 if (restrictive) return Qnil;
1392 max = -max;
1393 }
1394 r = random_ulong_limited(obj, rnd, (unsigned long)max - 1);
1395 return ULONG2NUM(r);
1396 }
1397 else {
1398 VALUE ret;
1399 if (rb_bigzero_p(vmax)) return Qnil;
1400 if (!BIGNUM_SIGN(vmax)) {
1401 if (restrictive) return Qnil;
1402 vmax = rb_big_uminus(vmax);
1403 }
1404 vmax = rb_big_minus(vmax, INT2FIX(1));
1405 if (FIXNUM_P(vmax)) {
1406 long max = FIX2LONG(vmax);
1407 if (max == -1) return Qnil;
1408 r = random_ulong_limited(obj, rnd, max);
1409 return LONG2NUM(r);
1410 }
1411 ret = random_ulong_limited_big(obj, rnd, vmax);
1412 RB_GC_GUARD(vmax);
1413 return ret;
1414 }
1415}
1416
1417static void
1418domain_error(void)
1419{
1420 VALUE error = INT2FIX(EDOM);
1421 rb_exc_raise(rb_class_new_instance(1, &error, rb_eSystemCallError));
1422}
1423
1424NORETURN(static void invalid_argument(VALUE));
1425static void
1426invalid_argument(VALUE arg0)
1427{
1428 rb_raise(rb_eArgError, "invalid argument - %"PRIsVALUE, arg0);
1429}
1430
1431static VALUE
1432check_random_number(VALUE v, const VALUE *argv)
1433{
1434 switch (v) {
1435 case Qfalse:
1436 (void)NUM2LONG(argv[0]);
1437 break;
1438 case Qnil:
1439 invalid_argument(argv[0]);
1440 }
1441 return v;
1442}
1443
1444static inline double
1445float_value(VALUE v)
1446{
1447 double x = RFLOAT_VALUE(v);
1448 if (!isfinite(x)) {
1449 domain_error();
1450 }
1451 return x;
1452}
1453
1454static inline VALUE
1455rand_range(VALUE obj, rb_random_t* rnd, VALUE range)
1456{
1457 VALUE beg = Qundef, end = Qundef, vmax, v;
1458 int excl = 0;
1459
1460 if ((v = vmax = range_values(range, &beg, &end, &excl)) == Qfalse)
1461 return Qfalse;
1462 if (NIL_P(v)) domain_error();
1463 if (!RB_FLOAT_TYPE_P(vmax) && (v = rb_check_to_int(vmax), !NIL_P(v))) {
1464 long max;
1465 vmax = v;
1466 v = Qnil;
1467 fixnum:
1468 if (FIXNUM_P(vmax)) {
1469 if ((max = FIX2LONG(vmax) - excl) >= 0) {
1470 unsigned long r = random_ulong_limited(obj, rnd, (unsigned long)max);
1471 v = ULONG2NUM(r);
1472 }
1473 }
1474 else if (BUILTIN_TYPE(vmax) == T_BIGNUM && BIGNUM_SIGN(vmax) && !rb_bigzero_p(vmax)) {
1475 vmax = excl ? rb_big_minus(vmax, INT2FIX(1)) : rb_big_norm(vmax);
1476 if (FIXNUM_P(vmax)) {
1477 excl = 0;
1478 goto fixnum;
1479 }
1480 v = random_ulong_limited_big(obj, rnd, vmax);
1481 }
1482 }
1483 else if (v = rb_check_to_float(vmax), !NIL_P(v)) {
1484 int scale = 1;
1485 double max = RFLOAT_VALUE(v), mid = 0.5, r;
1486 if (isinf(max)) {
1487 double min = float_value(rb_to_float(beg)) / 2.0;
1488 max = float_value(rb_to_float(end)) / 2.0;
1489 scale = 2;
1490 mid = max + min;
1491 max -= min;
1492 }
1493 else if (isnan(max)) {
1494 domain_error();
1495 }
1496 v = Qnil;
1497 if (max > 0.0) {
1498 r = random_real(obj, rnd, excl);
1499 if (scale > 1) {
1500 return rb_float_new(+(+(+(r - 0.5) * max) * scale) + mid);
1501 }
1502 v = rb_float_new(r * max);
1503 }
1504 else if (max == 0.0 && !excl) {
1505 v = rb_float_new(0.0);
1506 }
1507 }
1508
1509 if (FIXNUM_P(beg) && FIXNUM_P(v)) {
1510 long x = FIX2LONG(beg) + FIX2LONG(v);
1511 return LONG2NUM(x);
1512 }
1513 switch (TYPE(v)) {
1514 case T_NIL:
1515 break;
1516 case T_BIGNUM:
1517 return rb_big_plus(v, beg);
1518 case T_FLOAT: {
1519 VALUE f = rb_check_to_float(beg);
1520 if (!NIL_P(f)) {
1521 return DBL2NUM(RFLOAT_VALUE(v) + RFLOAT_VALUE(f));
1522 }
1523 }
1524 default:
1525 return rb_funcallv(beg, id_plus, 1, &v);
1526 }
1527
1528 return v;
1529}
1530
1531static VALUE rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd);
1532
1533/*
1534 * call-seq:
1535 * prng.rand -> float
1536 * prng.rand(max) -> number
1537 * prng.rand(range) -> number
1538 *
1539 * When +max+ is an Integer, +rand+ returns a random integer greater than
1540 * or equal to zero and less than +max+. Unlike Kernel.rand, when +max+
1541 * is a negative integer or zero, +rand+ raises an ArgumentError.
1542 *
1543 * prng = Random.new
1544 * prng.rand(100) # => 42
1545 *
1546 * When +max+ is a Float, +rand+ returns a random floating point number
1547 * between 0.0 and +max+, including 0.0 and excluding +max+.
1548 *
1549 * prng.rand(1.5) # => 1.4600282860034115
1550 *
1551 * When +range+ is a Range, +rand+ returns a random number where
1552 * <code>range.member?(number) == true</code>.
1553 *
1554 * prng.rand(5..9) # => one of [5, 6, 7, 8, 9]
1555 * prng.rand(5...9) # => one of [5, 6, 7, 8]
1556 * prng.rand(5.0..9.0) # => between 5.0 and 9.0, including 9.0
1557 * prng.rand(5.0...9.0) # => between 5.0 and 9.0, excluding 9.0
1558 *
1559 * Both the beginning and ending values of the range must respond to subtract
1560 * (<tt>-</tt>) and add (<tt>+</tt>)methods, or rand will raise an
1561 * ArgumentError.
1562 */
1563static VALUE
1564random_rand(int argc, VALUE *argv, VALUE obj)
1565{
1566 VALUE v = rand_random(argc, argv, obj, try_get_rnd(obj));
1567 check_random_number(v, argv);
1568 return v;
1569}
1570
1571static VALUE
1572rand_random(int argc, VALUE *argv, VALUE obj, rb_random_t *rnd)
1573{
1574 VALUE vmax, v;
1575
1576 if (rb_check_arity(argc, 0, 1) == 0) {
1577 return rb_float_new(random_real(obj, rnd, TRUE));
1578 }
1579 vmax = argv[0];
1580 if (NIL_P(vmax)) return Qnil;
1581 if (!RB_FLOAT_TYPE_P(vmax)) {
1582 v = rb_check_to_int(vmax);
1583 if (!NIL_P(v)) return rand_int(obj, rnd, v, 1);
1584 }
1585 v = rb_check_to_float(vmax);
1586 if (!NIL_P(v)) {
1587 const double max = float_value(v);
1588 if (max < 0.0) {
1589 return Qnil;
1590 }
1591 else {
1592 double r = random_real(obj, rnd, TRUE);
1593 if (max > 0.0) r *= max;
1594 return rb_float_new(r);
1595 }
1596 }
1597 return rand_range(obj, rnd, vmax);
1598}
1599
1600/*
1601 * call-seq:
1602 * prng.random_number -> float
1603 * prng.random_number(max) -> number
1604 * prng.random_number(range) -> number
1605 * prng.rand -> float
1606 * prng.rand(max) -> number
1607 * prng.rand(range) -> number
1608 *
1609 * Generates formatted random number from raw random bytes.
1610 * See Random#rand.
1611 */
1612static VALUE
1613rand_random_number(int argc, VALUE *argv, VALUE obj)
1614{
1615 rb_random_t *rnd = try_get_rnd(obj);
1616 VALUE v = rand_random(argc, argv, obj, rnd);
1617 if (NIL_P(v)) v = rand_random(0, 0, obj, rnd);
1618 else if (!v) invalid_argument(argv[0]);
1619 return v;
1620}
1621
1622/*
1623 * call-seq:
1624 * prng1 == prng2 -> true or false
1625 *
1626 * Returns true if the two generators have the same internal state, otherwise
1627 * false. Equivalent generators will return the same sequence of
1628 * pseudo-random numbers. Two generators will generally have the same state
1629 * only if they were initialized with the same seed
1630 *
1631 * Random.new == Random.new # => false
1632 * Random.new(1234) == Random.new(1234) # => true
1633 *
1634 * and have the same invocation history.
1635 *
1636 * prng1 = Random.new(1234)
1637 * prng2 = Random.new(1234)
1638 * prng1 == prng2 # => true
1639 *
1640 * prng1.rand # => 0.1915194503788923
1641 * prng1 == prng2 # => false
1642 *
1643 * prng2.rand # => 0.1915194503788923
1644 * prng1 == prng2 # => true
1645 */
1646static VALUE
1647rand_mt_equal(VALUE self, VALUE other)
1648{
1649 rb_random_mt_t *r1, *r2;
1650 if (rb_obj_class(self) != rb_obj_class(other)) return Qfalse;
1651 r1 = get_rnd_mt(self);
1652 r2 = get_rnd_mt(other);
1653 if (memcmp(r1->mt.state, r2->mt.state, sizeof(r1->mt.state))) return Qfalse;
1654 if ((r1->mt.next - r1->mt.state) != (r2->mt.next - r2->mt.state)) return Qfalse;
1655 if (r1->mt.left != r2->mt.left) return Qfalse;
1656 return rb_equal(r1->base.seed, r2->base.seed);
1657}
1658
1659/*
1660 * call-seq:
1661 * rand(max=0) -> number
1662 *
1663 * If called without an argument, or if <tt>max.to_i.abs == 0</tt>, rand
1664 * returns a pseudo-random floating point number between 0.0 and 1.0,
1665 * including 0.0 and excluding 1.0.
1666 *
1667 * rand #=> 0.2725926052826416
1668 *
1669 * When +max.abs+ is greater than or equal to 1, +rand+ returns a pseudo-random
1670 * integer greater than or equal to 0 and less than +max.to_i.abs+.
1671 *
1672 * rand(100) #=> 12
1673 *
1674 * When +max+ is a Range, +rand+ returns a random number where
1675 * <code>range.member?(number) == true</code>.
1676 *
1677 * Negative or floating point values for +max+ are allowed, but may give
1678 * surprising results.
1679 *
1680 * rand(-100) # => 87
1681 * rand(-0.5) # => 0.8130921818028143
1682 * rand(1.9) # equivalent to rand(1), which is always 0
1683 *
1684 * Kernel.srand may be used to ensure that sequences of random numbers are
1685 * reproducible between different runs of a program.
1686 *
1687 * See also Random.rand.
1688 */
1689
1690static VALUE
1691rb_f_rand(int argc, VALUE *argv, VALUE obj)
1692{
1693 VALUE vmax;
1694 rb_random_t *rnd = rand_start(default_rand());
1695
1696 if (rb_check_arity(argc, 0, 1) && !NIL_P(vmax = argv[0])) {
1697 VALUE v = rand_range(obj, rnd, vmax);
1698 if (v != Qfalse) return v;
1699 vmax = rb_to_int(vmax);
1700 if (vmax != INT2FIX(0)) {
1701 v = rand_int(obj, rnd, vmax, 0);
1702 if (!NIL_P(v)) return v;
1703 }
1704 }
1705 return DBL2NUM(random_real(obj, rnd, TRUE));
1706}
1707
1708/*
1709 * call-seq:
1710 * Random.rand -> float
1711 * Random.rand(max) -> number
1712 * Random.rand(range) -> number
1713 *
1714 * Returns a random number using the Ruby system PRNG.
1715 *
1716 * See also Random#rand.
1717 */
1718static VALUE
1719random_s_rand(int argc, VALUE *argv, VALUE obj)
1720{
1721 VALUE v = rand_random(argc, argv, Qnil, rand_start(default_rand()));
1722 check_random_number(v, argv);
1723 return v;
1724}
1725
1726#define SIP_HASH_STREAMING 0
1727#define sip_hash13 ruby_sip_hash13
1728#if !defined _WIN32 && !defined BYTE_ORDER
1729# ifdef WORDS_BIGENDIAN
1730# define BYTE_ORDER BIG_ENDIAN
1731# else
1732# define BYTE_ORDER LITTLE_ENDIAN
1733# endif
1734# ifndef LITTLE_ENDIAN
1735# define LITTLE_ENDIAN 1234
1736# endif
1737# ifndef BIG_ENDIAN
1738# define BIG_ENDIAN 4321
1739# endif
1740#endif
1741#include "siphash.c"
1742
1743typedef struct {
1744 st_index_t hash;
1745 uint8_t sip[16];
1746} hash_salt_t;
1747
1748static union {
1749 hash_salt_t key;
1750 uint32_t u32[type_roomof(hash_salt_t, uint32_t)];
1751} hash_salt;
1752
1753static void
1754init_hash_salt(struct MT *mt)
1755{
1756 int i;
1757
1758 for (i = 0; i < numberof(hash_salt.u32); ++i)
1759 hash_salt.u32[i] = genrand_int32(mt);
1760}
1761
1762NO_SANITIZE("unsigned-integer-overflow", extern st_index_t rb_hash_start(st_index_t h));
1763st_index_t
1764rb_hash_start(st_index_t h)
1765{
1766 return st_hash_start(hash_salt.key.hash + h);
1767}
1768
1769st_index_t
1770rb_memhash(const void *ptr, long len)
1771{
1772 sip_uint64_t h = sip_hash13(hash_salt.key.sip, ptr, len);
1773#ifdef HAVE_UINT64_T
1774 return (st_index_t)h;
1775#else
1776 return (st_index_t)(h.u32[0] ^ h.u32[1]);
1777#endif
1778}
1779
1780/* Initialize Ruby internal seeds. This function is called at very early stage
1781 * of Ruby startup. Thus, you can't use Ruby's object. */
1782void
1783Init_RandomSeedCore(void)
1784{
1785 if (!fill_random_bytes(&hash_salt, sizeof(hash_salt), FALSE)) return;
1786
1787 /*
1788 If failed to fill siphash's salt with random data, expand less random
1789 data with MT.
1790
1791 Don't reuse this MT for default_rand(). default_rand()::seed shouldn't
1792 provide a hint that an attacker guess siphash's seed.
1793 */
1794 struct MT mt;
1795
1796 with_random_seed(DEFAULT_SEED_CNT, 0, false) {
1797 init_by_array(&mt, seedbuf, DEFAULT_SEED_CNT);
1798 }
1799
1800 init_hash_salt(&mt);
1801 explicit_bzero(&mt, sizeof(mt));
1802}
1803
1804void
1806{
1807 rb_random_mt_t *r = default_rand();
1808 uninit_genrand(&r->mt);
1809 r->base.seed = INT2FIX(0);
1810}
1811
1812/*
1813 * Document-class: Random
1814 *
1815 * Random provides an interface to Ruby's pseudo-random number generator, or
1816 * PRNG. The PRNG produces a deterministic sequence of bits which approximate
1817 * true randomness. The sequence may be represented by integers, floats, or
1818 * binary strings.
1819 *
1820 * The generator may be initialized with either a system-generated or
1821 * user-supplied seed value by using Random.srand.
1822 *
1823 * The class method Random.rand provides the base functionality of Kernel.rand
1824 * along with better handling of floating point values. These are both
1825 * interfaces to the Ruby system PRNG.
1826 *
1827 * Random.new will create a new PRNG with a state independent of the Ruby
1828 * system PRNG, allowing multiple generators with different seed values or
1829 * sequence positions to exist simultaneously. Random objects can be
1830 * marshaled, allowing sequences to be saved and resumed.
1831 *
1832 * PRNGs are currently implemented as a modified Mersenne Twister with a period
1833 * of 2**19937-1. As this algorithm is _not_ for cryptographical use, you must
1834 * use SecureRandom for security purpose, instead of this PRNG.
1835 *
1836 * See also Random::Formatter module that adds convenience methods to generate
1837 * various forms of random data.
1838 */
1839
1840void
1841InitVM_Random(void)
1842{
1843 VALUE base;
1844 ID id_base = rb_intern_const("Base");
1845
1846 rb_define_global_function("srand", rb_f_srand, -1);
1847 rb_define_global_function("rand", rb_f_rand, -1);
1848
1849 base = rb_define_class_id(id_base, rb_cObject);
1850 rb_undef_alloc_func(base);
1851 rb_cRandom = rb_define_class("Random", base);
1852 rb_const_set(rb_cRandom, id_base, base);
1853 rb_define_alloc_func(rb_cRandom, random_alloc);
1854 rb_define_method(base, "initialize", random_init, -1);
1855 rb_define_method(base, "rand", random_rand, -1);
1856 rb_define_method(base, "bytes", random_bytes, 1);
1857 rb_define_method(base, "seed", random_get_seed, 0);
1858 rb_define_method(rb_cRandom, "initialize_copy", rand_mt_copy, 1);
1859 rb_define_private_method(rb_cRandom, "marshal_dump", rand_mt_dump, 0);
1860 rb_define_private_method(rb_cRandom, "marshal_load", rand_mt_load, 1);
1861 rb_define_private_method(rb_cRandom, "state", rand_mt_state, 0);
1862 rb_define_private_method(rb_cRandom, "left", rand_mt_left, 0);
1863 rb_define_method(rb_cRandom, "==", rand_mt_equal, 1);
1864
1865#if 0 /* for RDoc: it can't handle unnamed base class */
1866 rb_define_method(rb_cRandom, "initialize", random_init, -1);
1867 rb_define_method(rb_cRandom, "rand", random_rand, -1);
1868 rb_define_method(rb_cRandom, "bytes", random_bytes, 1);
1869 rb_define_method(rb_cRandom, "seed", random_get_seed, 0);
1870#endif
1871
1872 rb_define_singleton_method(rb_cRandom, "srand", rb_f_srand, -1);
1873 rb_define_singleton_method(rb_cRandom, "rand", random_s_rand, -1);
1874 rb_define_singleton_method(rb_cRandom, "bytes", random_s_bytes, 1);
1875 rb_define_singleton_method(rb_cRandom, "seed", random_s_seed, 0);
1876 rb_define_singleton_method(rb_cRandom, "new_seed", random_seed, 0);
1877 rb_define_singleton_method(rb_cRandom, "urandom", random_raw_seed, 1);
1878 rb_define_private_method(CLASS_OF(rb_cRandom), "state", random_s_state, 0);
1879 rb_define_private_method(CLASS_OF(rb_cRandom), "left", random_s_left, 0);
1880
1881 {
1882 /*
1883 * Generate a random number in the given range as Random does
1884 *
1885 * prng.random_number #=> 0.5816771641321361
1886 * prng.random_number(1000) #=> 485
1887 * prng.random_number(1..6) #=> 3
1888 * prng.rand #=> 0.5816771641321361
1889 * prng.rand(1000) #=> 485
1890 * prng.rand(1..6) #=> 3
1891 */
1892 VALUE m = rb_define_module_under(rb_cRandom, "Formatter");
1893 rb_include_module(base, m);
1894 rb_extend_object(base, m);
1895 rb_define_method(m, "random_number", rand_random_number, -1);
1896 rb_define_method(m, "rand", rand_random_number, -1);
1897 }
1898
1899 default_rand_key = rb_ractor_local_storage_ptr_newkey(&default_rand_key_storage_type);
1900}
1901
1902#undef rb_intern
1903void
1904Init_Random(void)
1905{
1906 id_rand = rb_intern("rand");
1907 id_bytes = rb_intern("bytes");
1908
1909 InitVM(Random);
1910}
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:1187
VALUE rb_define_class(const char *name, VALUE super)
Defines a top-level class.
Definition class.c:980
void rb_extend_object(VALUE obj, VALUE module)
Extend the object with the module.
Definition eval.c:1756
VALUE rb_define_module_under(VALUE outer, const char *name)
Defines a module under the namespace of outer.
Definition class.c:1119
VALUE rb_define_class_id(ID id, VALUE super)
This is a very badly designed API that creates an anonymous class.
Definition class.c:950
#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:203
#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
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:4197
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:3198
VALUE rb_class_new_instance(int argc, const VALUE *argv, VALUE klass)
Allocates, then initialises an instance of the given class.
Definition object.c:2138
VALUE rb_check_to_float(VALUE val)
This is complicated.
Definition object.c:3663
VALUE rb_cRandom
Random class.
Definition random.c:236
VALUE rb_obj_class(VALUE obj)
Queries the class of an object.
Definition object.c:247
VALUE rb_to_float(VALUE val)
Identical to rb_check_to_float(), except it raises on error.
Definition object.c:3653
VALUE rb_equal(VALUE lhs, VALUE rhs)
This function is an optimised version of calling #==.
Definition object.c:179
VALUE rb_to_int(VALUE val)
Identical to rb_check_to_int(), except it raises in case of conversion mismatch.
Definition object.c:3192
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:1150
#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:1094
double rb_random_real(VALUE rnd)
Identical to rb_genrand_real(), except it generates using the passed RNG.
Definition random.c:1166
unsigned int rb_random_int32(VALUE rnd)
Identical to rb_genrand_int32(), except it generates using the passed RNG.
Definition random.c:1123
void rb_reset_random_seed(void)
Resets the RNG behind rb_genrand_int32()/rb_genrand_real().
Definition random.c:1805
VALUE rb_random_bytes(VALUE rnd, long n)
Generates a String of random bytes.
Definition random.c:1324
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:1226
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:1804
st_index_t rb_memhash(const void *ptr, long len)
This is a universal hash function.
Definition random.c:1770
#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:1764
void rb_const_set(VALUE space, ID name, VALUE val)
Names a constant.
Definition variable.c:3703
void rb_undef_alloc_func(VALUE klass)
Deletes the allocator function of a class.
Definition vm_method.c:1291
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
struct rb_ractor_local_key_struct * rb_ractor_local_key_t
(Opaque) struct that holds a ractor-local storage key.
Definition ractor.h:42
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:3866
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:3878
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:3768
#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:1301
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:1155
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:449
struct rb_data_type_struct rb_data_type_t
This is the struct that holds necessary info for a struct.
Definition rtypeddata.h:197
#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:602
#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
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::@252065172107115056214132245033320006371365370334 version
Major/minor versions of this interface.
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