1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/rand_util.h"
14 #include "base/logging.h"
15 #include "base/strings/string_util.h"
19 uint64_t RandUint64() {
21 RandBytes(&number, sizeof(number));
25 int RandInt(int min, int max) {
28 uint64_t range = static_cast<uint64_t>(max) - min + 1;
29 // |range| is at most UINT_MAX + 1, so the result of RandGenerator(range)
30 // is at most UINT_MAX. Hence it's safe to cast it from uint64_t to int64_t.
32 static_cast<int>(min + static_cast<int64_t>(base::RandGenerator(range)));
33 DCHECK_GE(result, min);
34 DCHECK_LE(result, max);
39 return BitsToOpenEndedUnitInterval(base::RandUint64());
42 double BitsToOpenEndedUnitInterval(uint64_t bits) {
43 // We try to get maximum precision by masking out as many bits as will fit
44 // in the target type's mantissa, and raising it to an appropriate power to
45 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa
46 // is expected to accommodate 53 bits.
48 static_assert(std::numeric_limits<double>::radix == 2,
49 "otherwise use scalbn");
50 static const int kBits = std::numeric_limits<double>::digits;
51 uint64_t random_bits = bits & ((UINT64_C(1) << kBits) - 1);
52 double result = ldexp(static_cast<double>(random_bits), -1 * kBits);
53 DCHECK_GE(result, 0.0);
54 DCHECK_LT(result, 1.0);
58 uint64_t RandGenerator(uint64_t range) {
60 // We must discard random results above this number, as they would
61 // make the random generator non-uniform (consider e.g. if
62 // MAX_UINT64 was 7 and |range| was 5, then a result of 1 would be twice
63 // as likely as a result of 3 or 4).
64 uint64_t max_acceptable_value =
65 (std::numeric_limits<uint64_t>::max() / range) * range - 1;
69 value = base::RandUint64();
70 } while (value > max_acceptable_value);
75 std::string RandBytesAsString(size_t length) {
76 DCHECK_GT(length, 0u);
78 RandBytes(WriteInto(&result, length + 1), length);