rand: cleanup rand_between() and helpers
[fio.git] / lib / rand.h
index a95bd28b49041991abb8a1713ad80c9ef086742a..4f10fb3c57afe6946e931b0f95233db3f68d6aaf 100644 (file)
@@ -2,7 +2,8 @@
 #define FIO_RAND_H
 
 #include <inttypes.h>
-#include "../arch/arch.h"
+#include <assert.h>
+#include "types.h"
 
 #define FRAND32_MAX    (-1U)
 #define FRAND64_MAX    (-1ULL)
@@ -23,10 +24,6 @@ struct frand_state {
        };
 };
 
-struct frand64_state {
-       uint64_t s1, s2, s3, s4, s5;
-};
-
 static inline uint64_t rand_max(struct frand_state *state)
 {
        if (state->use64)
@@ -117,8 +114,40 @@ static inline double __rand_0_1(struct frand_state *state)
        }
 }
 
-extern void init_rand(struct frand_state *, int);
-extern void init_rand_seed(struct frand_state *, unsigned int seed, int);
+/*
+ * Generate a random value between 'start' and 'end', both inclusive
+ */
+static inline uint32_t rand32_upto(struct frand_state *state, uint32_t end)
+{
+       uint32_t r;
+
+       assert(!state->use64);
+
+       r = __rand32(&state->state32);
+       return (int) ((double)end * (r / (FRAND32_MAX + 1.0)));
+}
+
+static inline uint64_t rand64_upto(struct frand_state *state, uint64_t end)
+{
+       uint64_t r;
+
+       assert(state->use64);
+
+       r = __rand64(&state->state64);
+       return (uint64_t) ((double)end * (r / (FRAND64_MAX + 1.0)));
+}
+
+static inline uint64_t rand_between(struct frand_state *state, uint64_t start,
+                                   uint64_t end)
+{
+       if (state->use64)
+               return start + rand64_upto(state, end - start);
+       else
+               return start + rand32_upto(state, end - start);
+}
+
+extern void init_rand(struct frand_state *, bool);
+extern void init_rand_seed(struct frand_state *, unsigned int seed, bool);
 extern void __fill_random_buf(void *buf, unsigned int len, unsigned long seed);
 extern unsigned long fill_random_buf(struct frand_state *, void *buf, unsigned int len);
 extern void __fill_random_buf_percentage(unsigned long, void *, unsigned int, unsigned int, unsigned int, char *, unsigned int);