123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- #ifndef _XS_RANDOM_H
- #define _XS_RANDOM_H
- unsigned int xs_rnd_int32_d(unsigned int *seed);
- void *xs_rnd_buf(void *buf, int size);
- #ifdef XS_IMPLEMENTATION
- #include <stdio.h>
- #include <sys/time.h>
- #include <unistd.h>
- #include <stdlib.h>
- unsigned int xs_rnd_int32_d(unsigned int *seed)
- {
- static unsigned int s = 0;
- if (seed == NULL)
- seed = &s;
- if (*seed == 0) {
- struct timeval tv;
- gettimeofday(&tv, NULL);
- *seed = tv.tv_sec ^ tv.tv_usec ^ getpid();
- }
-
- *seed = (*seed * 1664525) + 1013904223;
- return *seed;
- }
- void *xs_rnd_buf(void *buf, int size)
- {
- #ifdef __OpenBSD__
-
- arc4random_buf(buf, size);
- #else
- FILE *f;
- int done = 0;
- if ((f = fopen("/dev/urandom", "r")) != NULL) {
-
- if (fread(buf, size, 1, f) == 1)
- done = 1;
- fclose(f);
- }
- if (!done) {
-
- unsigned int s = 0;
- unsigned char *p = (unsigned char *)buf;
- int n = size / sizeof(s);
-
- while (n--) {
- xs_rnd_int32_d(&s);
- p = memcpy(p, &s, sizeof(s)) + sizeof(s);
- }
- if ((n = size % sizeof(s))) {
-
- xs_rnd_int32_d(&s);
- memcpy(p, &s, n);
- }
- }
- #endif
- return buf;
- }
- #endif
- #endif
|