1 #define _ALL_SOURCE
2 #include <stdlib.h>
3 
4 #include <limits.h>
5 #include <stdint.h>
6 #include <threads.h>
7 
8 // TODO(kulakowski) Implement a real and secure prng
9 
10 static mtx_t counter_lock = MTX_INIT;
11 static uint64_t counter;
12 
random(void)13 long random(void) {
14     mtx_lock(&counter_lock);
15     uint64_t value = ++counter;
16     if (counter > RAND_MAX || counter > LONG_MAX)
17         counter = 0;
18     mtx_unlock(&counter_lock);
19 
20     return value;
21 }
22 
srandom(unsigned seed)23 void srandom(unsigned seed) {
24     mtx_lock(&counter_lock);
25     counter = seed;
26     mtx_unlock(&counter_lock);
27 }
28 
initstate(unsigned seed,char * state,size_t n)29 char* initstate(unsigned seed, char* state, size_t n) {
30     srandom(seed);
31     return (char*)&counter;
32 }
33 
setstate(char * state)34 char* setstate(char* state) {
35     return (char*)&counter;
36 }
37