aboutsummaryrefslogtreecommitdiff
path: root/src/stdlib/random.h
diff options
context:
space:
mode:
authorBruce Hill <bruce@bruce-hill.com>2025-05-01 15:30:14 -0400
committerBruce Hill <bruce@bruce-hill.com>2025-05-01 15:30:14 -0400
commit70611c0faaf436eaa01f6a6fd87d0637f74a2e4a (patch)
treedcbf76fc572b9b6f0fb8a0fd63061b43e938c292 /src/stdlib/random.h
parentc814131f2e5e09fe514746aa546d8baf90270ece (diff)
Add missing file
Diffstat (limited to 'src/stdlib/random.h')
-rw-r--r--src/stdlib/random.h23
1 files changed, 23 insertions, 0 deletions
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 <stdlib.h>
+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 <sys/random.h>
+#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));
+}