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/check_op.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);
82 void InsecureRandomGenerator::Seed() {
83 a_ = base::RandUint64();
84 b_ = base::RandUint64();
88 void InsecureRandomGenerator::SeedForTesting(uint64_t seed) {
94 uint64_t InsecureRandomGenerator::RandUint64() {
97 // Using XorShift128+, which is simple and widely used. See
98 // https://en.wikipedia.org/wiki/Xorshift#xorshift+ for details.
100 const uint64_t s = b_;
111 uint32_t InsecureRandomGenerator::RandUint32() {
112 // The generator usually returns an uint64_t, truncate it.
114 // It is noted in this paper (https://arxiv.org/abs/1810.05313) that the
115 // lowest 32 bits fail some statistical tests from the Big Crush
116 // suite. Use the higher ones instead.
117 return this->RandUint64() >> 32;
120 double InsecureRandomGenerator::RandDouble() {
121 uint64_t x = RandUint64();
122 // From https://vigna.di.unimi.it/xorshift/.
123 // 53 bits of mantissa, hence the "hexadecimal exponent" 1p-53.
124 return (x >> 11) * 0x1.0p-53;