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