From 70611c0faaf436eaa01f6a6fd87d0637f74a2e4a Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Thu, 1 May 2025 15:30:14 -0400 Subject: Add missing file --- src/stdlib/random.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/stdlib/random.h (limited to 'src/stdlib/random.h') diff --git a/src/stdlib/random.h b/src/stdlib/random.h new file mode 100644 index 00000000..861fab56 --- /dev/null +++ b/src/stdlib/random.h @@ -0,0 +1,23 @@ +#if defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__) +#include +static ssize_t getrandom(void *buf, size_t buflen, unsigned int flags) { + (void)flags; + arc4random_buf(buf, buflen); + return buflen; +} +#elif defined(__linux__) +// Use getrandom() +# include +#else + #error "Unsupported platform for secure random number generation" +#endif + +static int64_t random_range(int64_t low, int64_t high) { + uint64_t range = (uint64_t)high - (uint64_t)low + 1; + uint64_t min_r = -range % range; + uint64_t r; + do { + getrandom(&r, sizeof(r), 0); + } while (r < min_r); + return (int64_t)((uint64_t)low + (r % range)); +} -- cgit v1.2.3