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