1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/rand_util.h"
6
7 #include <limits.h>
8 #include <math.h>
9 #include <stdint.h>
10
11 #include <algorithm>
12 #include <limits>
13
14 #include "base/check_op.h"
15 #include "base/strings/string_util.h"
16
17 namespace base {
18
RandUint64()19 uint64_t RandUint64() {
20 uint64_t number;
21 RandBytes(&number, sizeof(number));
22 return number;
23 }
24
RandInt(int min,int max)25 int RandInt(int min, int max) {
26 DCHECK_LE(min, max);
27
28 uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(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.
31 int result =
32 static_cast<int>(min + static_cast<int64_t>(base::RandGenerator(range)));
33 DCHECK_GE(result, min);
34 DCHECK_LE(result, max);
35 return result;
36 }
37
RandDouble()38 double RandDouble() {
39 return BitsToOpenEndedUnitInterval(base::RandUint64());
40 }
41
RandFloat()42 float RandFloat() {
43 return BitsToOpenEndedUnitIntervalF(base::RandUint64());
44 }
45
BitsToOpenEndedUnitInterval(uint64_t bits)46 double BitsToOpenEndedUnitInterval(uint64_t bits) {
47 // We try to get maximum precision by masking out as many bits as will fit
48 // in the target type's mantissa, and raising it to an appropriate power to
49 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa
50 // is expected to accommodate 53 bits (including the implied bit).
51 static_assert(std::numeric_limits<double>::radix == 2,
52 "otherwise use scalbn");
53 constexpr int kBits = std::numeric_limits<double>::digits;
54 return ldexp(bits & ((UINT64_C(1) << kBits) - 1u), -kBits);
55 }
56
BitsToOpenEndedUnitIntervalF(uint64_t bits)57 float BitsToOpenEndedUnitIntervalF(uint64_t bits) {
58 // We try to get maximum precision by masking out as many bits as will fit
59 // in the target type's mantissa, and raising it to an appropriate power to
60 // produce output in the range [0, 1). For IEEE 754 floats, the mantissa is
61 // expected to accommodate 12 bits (including the implied bit).
62 static_assert(std::numeric_limits<float>::radix == 2, "otherwise use scalbn");
63 constexpr int kBits = std::numeric_limits<float>::digits;
64 return ldexpf(bits & ((UINT64_C(1) << kBits) - 1u), -kBits);
65 }
66
RandGenerator(uint64_t range)67 uint64_t RandGenerator(uint64_t range) {
68 DCHECK_GT(range, 0u);
69 // We must discard random results above this number, as they would
70 // make the random generator non-uniform (consider e.g. if
71 // MAX_UINT64 was 7 and |range| was 5, then a result of 1 would be twice
72 // as likely as a result of 3 or 4).
73 uint64_t max_acceptable_value =
74 (std::numeric_limits<uint64_t>::max() / range) * range - 1;
75
76 uint64_t value;
77 do {
78 value = base::RandUint64();
79 } while (value > max_acceptable_value);
80
81 return value % range;
82 }
83
RandBytesAsString(size_t length)84 std::string RandBytesAsString(size_t length) {
85 DCHECK_GT(length, 0u);
86 std::string result;
87 RandBytes(WriteInto(&result, length + 1), length);
88 return result;
89 }
90
InsecureRandomGenerator()91 InsecureRandomGenerator::InsecureRandomGenerator() {
92 a_ = base::RandUint64();
93 b_ = base::RandUint64();
94 }
95
ReseedForTesting(uint64_t seed)96 void InsecureRandomGenerator::ReseedForTesting(uint64_t seed) {
97 a_ = seed;
98 b_ = seed;
99 }
100
RandUint64()101 uint64_t InsecureRandomGenerator::RandUint64() {
102 // Using XorShift128+, which is simple and widely used. See
103 // https://en.wikipedia.org/wiki/Xorshift#xorshift+ for details.
104 uint64_t t = a_;
105 const uint64_t s = b_;
106
107 a_ = s;
108 t ^= t << 23;
109 t ^= t >> 17;
110 t ^= s ^ (s >> 26);
111 b_ = t;
112
113 return t + s;
114 }
115
RandUint32()116 uint32_t InsecureRandomGenerator::RandUint32() {
117 // The generator usually returns an uint64_t, truncate it.
118 //
119 // It is noted in this paper (https://arxiv.org/abs/1810.05313) that the
120 // lowest 32 bits fail some statistical tests from the Big Crush
121 // suite. Use the higher ones instead.
122 return this->RandUint64() >> 32;
123 }
124
RandDouble()125 double InsecureRandomGenerator::RandDouble() {
126 uint64_t x = RandUint64();
127 // From https://vigna.di.unimi.it/xorshift/.
128 // 53 bits of mantissa, hence the "hexadecimal exponent" 1p-53.
129 return (x >> 11) * 0x1.0p-53;
130 }
131
132 MetricsSubSampler::MetricsSubSampler() = default;
ShouldSample(double probability)133 bool MetricsSubSampler::ShouldSample(double probability) {
134 return generator_.RandDouble() < probability;
135 }
136
137 } // namespace base
138