diff options
author | Nick Mathewson <nickm@torproject.org> | 2006-10-01 21:59:05 +0000 |
---|---|---|
committer | Nick Mathewson <nickm@torproject.org> | 2006-10-01 21:59:05 +0000 |
commit | 219ad6395cea5403857c3adf1b938741dba79c4f (patch) | |
tree | e754d3a9a6caf6dce643492a2c48bca20a0e230e /src/common/crypto.c | |
parent | f6e165ea0146550f1882611e4395d92251f71ee7 (diff) | |
download | tor-219ad6395cea5403857c3adf1b938741dba79c4f.tar.gz tor-219ad6395cea5403857c3adf1b938741dba79c4f.zip |
r8825@totoro: nickm | 2006-10-01 17:41:27 -0400
Add function to return a random uint64_t.
svn:r8570
Diffstat (limited to 'src/common/crypto.c')
-rw-r--r-- | src/common/crypto.c | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/src/common/crypto.c b/src/common/crypto.c index 6cb0031fb7..a8caed47ba 100644 --- a/src/common/crypto.c +++ b/src/common/crypto.c @@ -1645,6 +1645,28 @@ crypto_rand_int(unsigned int max) } } +/** Return a pseudorandom integer, chosen uniformly from the values + * between 0 and max-1. */ +uint64_t +crypto_rand_uint64(uint64_t max) +{ + uint64_t val; + uint64_t cutoff; + tor_assert(max < UINT64_MAX); + tor_assert(max > 0); /* don't div by 0 */ + + /* We ignore any values that are >= 'cutoff,' to avoid biasing the + * distribution with clipping at the upper end of unsigned int's + * range. + */ + cutoff = UINT64_MAX - (UINT64_MAX%max); + while (1) { + crypto_rand((char*)&val, sizeof(val)); + if (val < cutoff) + return val % max; + } +} + /** Return a randomly chosen element of sl; or NULL if sl is empty. */ void * |