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