From a92649f9185dad6565a4c09a4def41d7843f8896 Mon Sep 17 00:00:00 2001 From: Norbert Manthey Date: Tue, 29 Sep 2020 14:38:46 +0200 Subject: [PATCH] rand: add prng This commit adds the ability to use random numbers with a seed, via the known methods rand() and srand(). As generator, a simple linear congruential generator is used, with the same parameters as used in musl or newlib. Signed-off-by: Norbert Manthey --- include/lib.h | 4 ++++ lib/lib.c | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/include/lib.h b/include/lib.h index 75503feb..b243a809 100644 --- a/include/lib.h +++ b/include/lib.h @@ -385,4 +385,8 @@ static inline unsigned int next_power_of_two(unsigned int n) { extern void halt(void); +extern void srand(unsigned s); + +extern int rand(void); + #endif /* KTF_LIB_H */ diff --git a/lib/lib.c b/lib/lib.c index 07f220c2..053e638d 100644 --- a/lib/lib.c +++ b/lib/lib.c @@ -33,3 +33,12 @@ void __noreturn halt(void) { pause(); } } + +static uint64_t seed; + +void srand(unsigned s) { seed = s - 1; } + +int rand(void) { + seed = 6364136223846793005ULL * seed + 1; + return seed >> 33; +}