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