Chromium Code Reviews| Index: base/rand_util.cc |
| diff --git a/base/rand_util.cc b/base/rand_util.cc |
| index 4140e9a539867026e856f50e670118378f2512ea..fe49f524412bad915f48d94ed6e59a706bd6c22b 100644 |
| --- a/base/rand_util.cc |
| +++ b/base/rand_util.cc |
| @@ -45,7 +45,20 @@ double BitsToOpenEndedUnitInterval(uint64 bits) { |
| uint64 RandGenerator(uint64 max) { |
| DCHECK_GT(max, 0ULL); |
| - return base::RandUint64() % max; |
| + |
| + // We must discard random results above this number, as they would |
| + // make the random generator non-uniform (consider e.g. if |
| + // MAX_UINT64 was 4 and max was 3, then a result of 1 would be twice |
| + // as likely as a result of 0 or 2). |
| + uint64 max_acceptable_value = |
| + (std::numeric_limits<uint64>::max() / max) * max; |
| + |
| + uint64 value; |
| + do { |
| + value = base::RandUint64(); |
| + } while (value > max_acceptable_value); |
|
jar (doing other things)
2011/05/27 20:25:14
Very cute.... but I think there is a typo, and thi
Jói
2011/05/27 23:18:01
You're right, thanks for catching that. Fixed and
jar (doing other things)
2011/05/28 17:26:40
OK... With that change I'm convinced it is "right,
|
| + |
| + return value % max; |
| } |
| void RandBytes(void* output, size_t output_length) { |