+// To preserve the uniform random distribution between min and max,
+// and allow all numbers to be represented, we generate a uniform
+// random number to the nearest power of two greater than max. If
+// this number doesn't fall between 0 and max, we try again. Anything
+// else would skew the distribution.
+uint32_t
+Random::genrand(uint32_t max)
+{
+ int log = ceilLog2(max);
+ int shift = (sizeof(uint32_t) * 8 - log);
+ uint32_t random;
+
+ do {
+ random = genrand() >> shift;
+ } while (random > max);
+
+ return random;