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