aboutsummaryrefslogtreecommitdiff
path: root/src/stdlib/random.h
diff options
context:
space:
mode:
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));
+}