From a0b45a51de4d59a390c626cfe9e662a829196f98 Mon Sep 17 00:00:00 2001 From: apio Date: Tue, 2 May 2023 21:20:24 +0200 Subject: [PATCH] libc: Add rand() + srand() Very basic random number generator, but that's what rand() is. If you want secure numbers then use arc4random() or something idk --- libc/include/stdlib.h | 7 ++++++- libc/src/stdlib.cpp | 13 +++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/libc/include/stdlib.h b/libc/include/stdlib.h index b7ed9819..df6cf274 100644 --- a/libc/include/stdlib.h +++ b/libc/include/stdlib.h @@ -29,6 +29,8 @@ typedef struct #define MB_CUR_MAX 4 +#define RAND_MAX 32767 + #ifdef __cplusplus extern "C" { @@ -91,8 +93,11 @@ extern "C" * endptr if nonnull. */ unsigned long strtoul(const char* str, char** endptr, int base); + /* Return the next pseudorandom number. */ int rand(); - void srand(int); + + /* Set the pseudorandom number generator's seed, which will determine the sequence of numbers returned by rand(). */ + void srand(unsigned int seed); /* Exit the program normally, performing any registered cleanup actions. */ __noreturn void exit(int status); diff --git a/libc/src/stdlib.cpp b/libc/src/stdlib.cpp index 59c6bd43..4271aeeb 100644 --- a/libc/src/stdlib.cpp +++ b/libc/src/stdlib.cpp @@ -205,4 +205,17 @@ extern "C" { c_quicksort(base, nmemb, size, compar); } + + static unsigned next = 42; + + int rand() + { + next = next * 1103515245 + 12345; + return (int)((unsigned)(next / 65536) % 32768); + } + + void srand(unsigned int seed) + { + next = seed; + } }