summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
Diffstat (limited to 'src/core/index.c')
-rw-r--r--src/core/index.c61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/core/index.c b/src/core/index.c
new file mode 100644
index 0000000..375e0ad
--- /dev/null
+++ b/src/core/index.c
@@ -0,0 +1,61 @@
+#include <limits.h>
+#include <stdlib.h>
+
+#include "index.h"
+
+#if (RAND_MAX < UCHAR_MAX)
+ #error "RAND_MAX < UCHAR_MAX, unable to generate random numbers."
+#endif
+
+#if (RAND_MAX == 0)
+ #error "RAND_MAX is included in [0, 0]. What are you even doing?"
+#endif
+
+/*
+ * Returns a random unsigned char.
+ */
+static unsigned char random_uchar (void)
+{
+ return
+ (unsigned char)
+ (
+ /* FIXME: Do floats allow enough precision for this? */
+ (
+ ((float) rand())
+ / ((float) RAND_MAX)
+ )
+ * ((float) UCHAR_MAX)
+ );
+}
+
+/* See: "index.h" */
+ZoO_index ZoO_index_random (void)
+{
+ ZoO_index i;
+ ZoO_index result;
+ unsigned char * result_bytes;
+
+ result_bytes = (unsigned char *) &result;
+
+ for (i = 0; i < sizeof(ZoO_index); ++i)
+ {
+ result_bytes[i] = random_uchar();
+ }
+
+ return result;
+}
+
+/* See: "index.h" */
+ZoO_index ZoO_index_random_up_to (const ZoO_index max)
+{
+ return
+ (ZoO_index)
+ (
+ /* FIXME: Do floats allow enough precision for this? */
+ (
+ ((float) ZoO_index_random())
+ / ((float) ZoO_INDEX_MAX)
+ )
+ * ((float) max)
+ );
+}