From 74e3f8b2531ee873c3555060d5b02791a325553a Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Fri, 27 Jan 2023 19:26:19 +0100 Subject: [PATCH] Add random util Add a user-friendly tool to generate random numbers. --- app/meson.build | 1 + app/src/util/rand.c | 24 ++++++++++++++++++++++++ app/src/util/rand.h | 16 ++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 app/src/util/rand.c create mode 100644 app/src/util/rand.h diff --git a/app/meson.build b/app/meson.build index cc465564..3ddd5a5d 100644 --- a/app/meson.build +++ b/app/meson.build @@ -37,6 +37,7 @@ src = [ 'src/util/net_intr.c', 'src/util/process.c', 'src/util/process_intr.c', + 'src/util/rand.c', 'src/util/strbuf.c', 'src/util/str.c', 'src/util/term.c', diff --git a/app/src/util/rand.c b/app/src/util/rand.c new file mode 100644 index 00000000..590e4ca4 --- /dev/null +++ b/app/src/util/rand.c @@ -0,0 +1,24 @@ +#include "rand.h" + +#include + +#include "tick.h" + +void sc_rand_init(struct sc_rand *rand) { + sc_tick seed = sc_tick_now(); // microsecond precision + rand->xsubi[0] = (seed >> 32) & 0xFFFF; + rand->xsubi[1] = (seed >> 16) & 0xFFFF; + rand->xsubi[2] = seed & 0xFFFF; +} + +uint32_t sc_rand_u32(struct sc_rand *rand) { + // jrand returns a value in range [-2^31, 2^31] + // conversion from signed to unsigned is well-defined to wrap-around + return jrand48(rand->xsubi); +} + +uint64_t sc_rand_u64(struct sc_rand *rand) { + uint32_t msb = sc_rand_u32(rand); + uint32_t lsb = sc_rand_u32(rand); + return ((uint64_t) msb << 32) | lsb; +} diff --git a/app/src/util/rand.h b/app/src/util/rand.h new file mode 100644 index 00000000..262b0b9b --- /dev/null +++ b/app/src/util/rand.h @@ -0,0 +1,16 @@ +#ifndef SC_RAND_H +#define SC_RAND_H + +#include "common.h" + +#include + +struct sc_rand { + unsigned short xsubi[3]; +}; + +void sc_rand_init(struct sc_rand *rand); +uint32_t sc_rand_u32(struct sc_rand *rand); +uint64_t sc_rand_u64(struct sc_rand *rand); + +#endif