X-Git-Url: https://pintos-os.org/cgi-bin/gitweb.cgi?a=blobdiff_plain;f=src%2Flib%2Frandom.c;h=c22414e9b779cd79123fe4390d3d0945b2d02d6c;hb=b13a0f40a52b47d3ceea92887adc9543c1d94aed;hp=3fcf62ddca797a1d9514a624d6aed59304d20d0a;hpb=5fbedf1d20c2b2f2dbc8c7ebd64cc7b4812a44bf;p=pintos-anon diff --git a/src/lib/random.c b/src/lib/random.c index 3fcf62d..c22414e 100644 --- a/src/lib/random.c +++ b/src/lib/random.c @@ -3,11 +3,24 @@ #include #include "debug.h" -/* RC4-based pseudo-random state. */ -static uint8_t s[256]; -static uint8_t s_i, s_j; -static bool inited; +/* RC4-based pseudo-random number generator (PRNG). + RC4 is a stream cipher. We're not using it here for its + cryptographic properties, but because it is easy to implement + and its output is plenty random for non-cryptographic + purposes. + + See http://en.wikipedia.org/wiki/RC4_(cipher) for information + on RC4.*/ + +/* RC4 state. */ +static uint8_t s[256]; /* S[]. */ +static uint8_t s_i, s_j; /* i, j. */ + +/* Already initialized? */ +static bool inited; + +/* Swaps the bytes pointed to by A and B. */ static inline void swap_byte (uint8_t *a, uint8_t *b) { @@ -16,6 +29,8 @@ swap_byte (uint8_t *a, uint8_t *b) *b = t; } +/* Initializes the PRNG with the given SEED. + Does nothing if the PRNG has already been initialized. */ void random_init (unsigned seed) { @@ -38,6 +53,7 @@ random_init (unsigned seed) inited = true; } +/* Writes SIZE random bytes into BUF. */ void random_bytes (void *buf_, size_t size) { @@ -57,7 +73,9 @@ random_bytes (void *buf_, size_t size) } } -/* Returns a pseudo-random unsigned long. */ +/* Returns a pseudo-random unsigned long. + Use random_ulong() % n to obtain a random number in the range + 0...n (exclusive). */ unsigned long random_ulong (void) {