MCPcopy Create free account
hub / github.com/eggert/tz / get_rand_u64

Function get_rand_u64

zic.c:1485–1542  ·  view source on GitHub ↗

Return a random uint_fast64_t. */

Source from the content-addressed store, hash-verified

1483}
1484
1485/* Return a random uint_fast64_t. */
1486static uint_fast64_t
1487get_rand_u64(void)
1488{
1489#if HAVE_GETRANDOM
1490 static uint_fast64_t entropy_buffer[max(1, 256 / sizeof(uint_fast64_t))];
1491 static int nwords;
1492 if (!nwords) {
1493 ssize_t s;
1494 for (;; check_for_signal()) {
1495 s = getrandom(entropy_buffer, sizeof entropy_buffer, 0);
1496 if (! (s < 0 && errno == EINTR))
1497 break;
1498 }
1499
1500 nwords = s < 0 ? -1 : s / sizeof *entropy_buffer;
1501 }
1502 if (0 < nwords)
1503 return entropy_buffer[--nwords];
1504#endif
1505
1506 /* getrandom didn't work, so fall back on portable code that is
1507 not the best because the seed isn't cryptographically random and
1508 'rand' might not be cryptographically secure. */
1509 {
1510 static bool initialized;
1511 if (!initialized) {
1512 srand(time(NULL));
1513 initialized = true;
1514 }
1515 }
1516
1517 /* Return a random number if rand() yields a random number and in
1518 the typical case where RAND_MAX is one less than a power of two.
1519 In other cases this code yields a sort-of-random number. */
1520 {
1521 uint_fast64_t rand_max = RAND_MAX,
1522 nrand = rand_max < UINT_FAST64_MAX ? rand_max + 1 : 0,
1523 rmod = INT_MAX < UINT_FAST64_MAX ? 0 : UINT_FAST64_MAX / nrand + 1,
1524 r = 0, rmax = 0;
1525
1526 for (;; check_for_signal()) {
1527 uint_fast64_t rmax1 = rmax;
1528 if (rmod) {
1529 /* Avoid signed integer overflow on theoretical platforms
1530 where uint_fast64_t promotes to int. */
1531 rmax1 %= rmod;
1532 r %= rmod;
1533 }
1534 rmax1 = nrand * rmax1 + rand_max;
1535 r = nrand * r + rand();
1536 rmax = rmax < rmax1 ? rmax1 : UINT_FAST64_MAX;
1537 if (UINT_FAST64_MAX <= rmax)
1538 break;
1539 }
1540
1541 return r;
1542 }

Callers 1

random_direntFunction · 0.85

Calls 2

check_for_signalFunction · 0.85
timeFunction · 0.85

Tested by

no test coverage detected