]> git.draconx.ca Git - cdecl99.git/blobdiff - t/rng.c
tests: Improve RNG compatibility with old compilers.
[cdecl99.git] / t / rng.c
diff --git a/t/rng.c b/t/rng.c
index fec991ce1259b718bf10f6a4743bf7283ad50e2b..e442d994fe5cbcd2fef22930e7ed133d3727e76a 100644 (file)
--- a/t/rng.c
+++ b/t/rng.c
@@ -1,6 +1,6 @@
 /*
  * Simple random number generator for testing.
- * Copyright © 2022-2023 Nick Bowler
+ * Copyright © 2022-2024 Nick Bowler
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
 #include <errno.h>
 #include <limits.h>
 
-#include "test.h"
+#if !TEST_RNG_NO_EXTERNAL_API
+#  include "test.h"
+#endif
 
-#define B64(x) ((x) & 0xffffffffffffffff)
+#define B64(x) ((x) & 0xffffffffffffffffull)
 
 struct test_rng {
        unsigned long long state[4];
@@ -63,42 +65,28 @@ static unsigned long long splitmix64(unsigned long long *state)
 {
        unsigned long long z;
 
-       z = B64(*state += 0x9e3779b97f4a7c15);
-       z = B64((z ^ (z >> 30)) * 0xbf58476d1ce4e5b9);
-       z = B64((z ^ (z >> 27)) * 0x94d049bb133111eb);
+       z = B64(*state += 0x9e3779b97f4a7c15ull);
+       z = B64((z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull);
+       z = B64((z ^ (z >> 27)) * 0x94d049bb133111ebull);
 
        return z ^ (z >> 31);
 }
 
-#if HAVE_STRTOULL
-#  define STRTOULL strtoull
-#elif HAVE___STRTOULL
-/* HP-UX 11 has __strtoull in <inttypes.h> */
-#  define STRTOULL __strtoull
-#else
-/*
- * Just fall back to strtoul -- in the worst case we just lose the ability
- * to set all 64 bits of the seed.
- */
-#  define STRTOULL strtoul
-#endif
-
+#if !TEST_RNG_NO_EXTERNAL_API
 struct test_rng *test_rng_alloc(const char *seed_str)
 {
        unsigned long long seed;
+       uintmax_t limit, seed_val;
        struct test_rng *rng;
-       char *end;
 
-       errno = 0;
-       seed = STRTOULL(seed_str, &end, 0);
-       if (*end != 0) {
-               fprintf(stderr, "%s: invalid seed\n", seed_str);
-               return NULL;
-       } else if (errno != 0) {
-               fprintf(stderr, "%s: invalid seed: %s\n",
-                               seed_str, strerror(errno));
+       limit  = (uintmax_t)0xffffffff;
+       limit |= (limit << 16 << 16);
+
+       if (!test_strtoumax(&seed_val, seed_str, limit)) {
+               print_error("%s: invalid seed", seed_str);
                return NULL;
        }
+       seed = seed_val;
 
        rng = malloc_nofail(sizeof *rng);
        rng->state[0] = splitmix64(&seed);
@@ -139,3 +127,4 @@ unsigned test_rng_uniform_int(struct test_rng *rng, unsigned max)
 
        return val;
 }
+#endif