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