[or-cvs] r8570: Add function to return a random uint64_t. (in tor/trunk: . src/common)

nickm at seul.org nickm at seul.org
Sun Oct 1 21:59:05 UTC 2006


Author: nickm
Date: 2006-10-01 17:59:05 -0400 (Sun, 01 Oct 2006)
New Revision: 8570

Modified:
   tor/trunk/
   tor/trunk/src/common/crypto.c
   tor/trunk/src/common/crypto.h
Log:
 r8825 at totoro:  nickm | 2006-10-01 17:41:27 -0400
 Add function to return a random uint64_t.



Property changes on: tor/trunk
___________________________________________________________________
 svk:merge ticket from /tor/trunk [r8825] on 96637b51-b116-0410-a10e-9941ebb49b64

Modified: tor/trunk/src/common/crypto.c
===================================================================
--- tor/trunk/src/common/crypto.c	2006-10-01 21:59:00 UTC (rev 8569)
+++ tor/trunk/src/common/crypto.c	2006-10-01 21:59:05 UTC (rev 8570)
@@ -1645,6 +1645,28 @@
   }
 }
 
+/** 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 *

Modified: tor/trunk/src/common/crypto.h
===================================================================
--- tor/trunk/src/common/crypto.h	2006-10-01 21:59:00 UTC (rev 8569)
+++ tor/trunk/src/common/crypto.h	2006-10-01 21:59:05 UTC (rev 8570)
@@ -15,6 +15,7 @@
 #define CRYPTO_H_ID "$Id$"
 
 #include <stdio.h>
+#include "torint.h"
 
 /** Length of the output of our message digest. */
 #define DIGEST_LEN 20
@@ -152,6 +153,7 @@
 int crypto_seed_rng(void);
 int crypto_rand(char *to, size_t n);
 int crypto_rand_int(unsigned int max);
+uint64_t crypto_rand_uint64(uint64_t max);
 
 struct smartlist_t;
 void *smartlist_choose(const struct smartlist_t *sl);



More information about the tor-commits mailing list