12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- #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);
- memcpy(p, &s, sizeof(s));
- p += sizeof(s);
- }
- if ((n = size % sizeof(s))) {
-
- xs_rnd_int32_d(&s);
- memcpy(p, &s, n);
- }
- }
- #endif
- return buf;
- }
- #endif
- #endif
|