diff --git a/rand.c b/rand.c index 7251826c89..4b921cabb3 100644 --- a/rand.c +++ b/rand.c @@ -35,10 +35,9 @@ void init_rand(void) int finalize_rand(void) { - int err = fclose(f); - f = NULL; - - return err; + int err = fclose(f); + f = NULL; + return err; } uint32_t random32(void) @@ -50,8 +49,27 @@ uint32_t random32(void) return r; } +uint32_t random_uniform(uint32_t n) +{ + uint32_t x, max = 0xFFFFFFFF - (0xFFFFFFFF % n); + while ((x = random32()) >= max); + return x / (max / n); +} + void random_buffer(uint8_t *buf, size_t len) { size_t len_read = fread(buf, 1, len, f); assert(len_read == len); } + +void random_permute(char *str, size_t len) +{ + int i, j; + char t; + for (i = len - 1; i >= 1; i--) { + j = random_uniform(i + 1); + t = str[j]; + str[j] = str[i]; + str[i] = t; + } +} diff --git a/rand.h b/rand.h index 2c78939630..8d81608872 100644 --- a/rand.h +++ b/rand.h @@ -24,12 +24,14 @@ #ifndef __RAND_H__ #define __RAND_H__ -#include #include +#include void init_rand(void); int finalize_rand(void); uint32_t random32(void); +uint32_t random_uniform(uint32_t n); void random_buffer(uint8_t *buf, size_t len); +void random_permute(char *buf, size_t len); #endif