tictactoe

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

commit e87c3093770a76d8d3410bff487b6639c4ecfc1c
parent 6129d4dee09b1b24b41630d2068b56082010368c
Author: Wilson Gheen <wilson@wilsonrgheen.com>
Date:   Fri, 23 Dec 2022 15:51:03 -0600

Use /dev/urandom if available for better randomness. Temporarily omitted for unit testing because it is slow for some reason

Diffstat:
Mtictactoe.h | 22++++++++++++++++++----
1 file changed, 18 insertions(+), 4 deletions(-)

diff --git a/tictactoe.h b/tictactoe.h @@ -22,12 +22,26 @@ static _Bool srand_seeded = 0; struct move { int move_ind; char winner; }; static int get_rand(int max_excl) { +#ifndef UNIT_TEST + FILE *urandom = fopen("/dev/urandom", "r"); + if(urandom) { + int rnd = 0; + size_t z = fread(&rnd, sizeof(int), 1, urandom); + fclose(urandom); + if(z) { + if(rnd < 0) rnd *= -1; + return rnd % max_excl; + } + } +#endif + /* fallback if somehow we can't open urandom or read 4 bytes from it */ if (!srand_seeded) { time_t seed = time(NULL); - FILE *f = fopen("seed", "w"); - if(f) { - fprintf(f, "%ld\n", seed); - fclose(f); + /* save seed for later in case of bugs, so they're reproducible */ + FILE *seed_file = fopen("seed", "w"); + if(seed_file) { + fprintf(seed_file, "%ld\n", seed); + fclose(seed_file); } srand(seed); srand_seeded = 1;