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 <atomic>
13 #include <limits>
14
15 #include "base/check_op.h"
16 #include "base/time/time.h"
17
18 namespace base {
19
20 namespace {
21
22 // A MetricSubsampler instance is not thread-safe. However, the global
23 // sampling state may be read concurrently with writing it via testing
24 // scopers, hence the need to use atomics. All operations use
25 // memory_order_relaxed because there are no dependent memory accesses.
26 std::atomic<bool> g_subsampling_always_sample = false;
27 std::atomic<bool> g_subsampling_never_sample = false;
28
29 } // namespace
30
RandUint64()31 uint64_t RandUint64() {
32 uint64_t number;
33 RandBytes(base::byte_span_from_ref(number));
34 return number;
35 }
36
RandInt(int min,int max)37 int RandInt(int min, int max) {
38 DCHECK_LE(min, max);
39
40 uint64_t range = static_cast<uint64_t>(max) - static_cast<uint64_t>(min) + 1;
41 // |range| is at most UINT_MAX + 1, so the result of RandGenerator(range)
42 // is at most UINT_MAX. Hence it's safe to cast it from uint64_t to int64_t.
43 int result =
44 static_cast<int>(min + static_cast<int64_t>(base::RandGenerator(range)));
45 DCHECK_GE(result, min);
46 DCHECK_LE(result, max);
47 return result;
48 }
49
RandDouble()50 double RandDouble() {
51 return BitsToOpenEndedUnitInterval(base::RandUint64());
52 }
53
RandFloat()54 float RandFloat() {
55 return BitsToOpenEndedUnitIntervalF(base::RandUint64());
56 }
57
RandTimeDelta(TimeDelta start,TimeDelta limit)58 TimeDelta RandTimeDelta(TimeDelta start, TimeDelta limit) {
59 // We must have a finite, non-empty, non-reversed interval.
60 CHECK_LT(start, limit);
61 CHECK(!start.is_min());
62 CHECK(!limit.is_max());
63
64 const int64_t range = (limit - start).InMicroseconds();
65 // Because of the `CHECK_LT()` above, range > 0, so this cast is safe.
66 const uint64_t delta_us = base::RandGenerator(static_cast<uint64_t>(range));
67 // ...and because `range` fit in an `int64_t`, so will `delta_us`.
68 return start + Microseconds(static_cast<int64_t>(delta_us));
69 }
70
RandTimeDeltaUpTo(TimeDelta limit)71 TimeDelta RandTimeDeltaUpTo(TimeDelta limit) {
72 return RandTimeDelta(TimeDelta(), limit);
73 }
74
BitsToOpenEndedUnitInterval(uint64_t bits)75 double BitsToOpenEndedUnitInterval(uint64_t bits) {
76 // We try to get maximum precision by masking out as many bits as will fit
77 // in the target type's mantissa, and raising it to an appropriate power to
78 // produce output in the range [0, 1). For IEEE 754 doubles, the mantissa
79 // is expected to accommodate 53 bits (including the implied bit).
80 static_assert(std::numeric_limits<double>::radix == 2,
81 "otherwise use scalbn");
82 constexpr int kBits = std::numeric_limits<double>::digits;
83 return ldexp(bits & ((UINT64_C(1) << kBits) - 1u), -kBits);
84 }
85
BitsToOpenEndedUnitIntervalF(uint64_t bits)86 float BitsToOpenEndedUnitIntervalF(uint64_t bits) {
87 // We try to get maximum precision by masking out as many bits as will fit
88 // in the target type's mantissa, and raising it to an appropriate power to
89 // produce output in the range [0, 1). For IEEE 754 floats, the mantissa is
90 // expected to accommodate 12 bits (including the implied bit).
91 static_assert(std::numeric_limits<float>::radix == 2, "otherwise use scalbn");
92 constexpr int kBits = std::numeric_limits<float>::digits;
93 return ldexpf(bits & ((UINT64_C(1) << kBits) - 1u), -kBits);
94 }
95
RandGenerator(uint64_t range)96 uint64_t RandGenerator(uint64_t range) {
97 DCHECK_GT(range, 0u);
98 // We must discard random results above this number, as they would
99 // make the random generator non-uniform (consider e.g. if
100 // MAX_UINT64 was 7 and |range| was 5, then a result of 1 would be twice
101 // as likely as a result of 3 or 4).
102 uint64_t max_acceptable_value =
103 (std::numeric_limits<uint64_t>::max() / range) * range - 1;
104
105 uint64_t value;
106 do {
107 value = base::RandUint64();
108 } while (value > max_acceptable_value);
109
110 return value % range;
111 }
112
RandBytesAsString(size_t length)113 std::string RandBytesAsString(size_t length) {
114 std::string result(length, '\0');
115 RandBytes(as_writable_byte_span(result));
116 return result;
117 }
118
RandBytesAsVector(size_t length)119 std::vector<uint8_t> RandBytesAsVector(size_t length) {
120 std::vector<uint8_t> result(length);
121 RandBytes(result);
122 return result;
123 }
124
InsecureRandomGenerator()125 InsecureRandomGenerator::InsecureRandomGenerator() {
126 a_ = base::RandUint64();
127 b_ = base::RandUint64();
128 }
129
ReseedForTesting(uint64_t seed)130 void InsecureRandomGenerator::ReseedForTesting(uint64_t seed) {
131 a_ = seed;
132 b_ = seed;
133 }
134
RandUint64()135 uint64_t InsecureRandomGenerator::RandUint64() {
136 // Using XorShift128+, which is simple and widely used. See
137 // https://en.wikipedia.org/wiki/Xorshift#xorshift+ for details.
138 uint64_t t = a_;
139 const uint64_t s = b_;
140
141 a_ = s;
142 t ^= t << 23;
143 t ^= t >> 17;
144 t ^= s ^ (s >> 26);
145 b_ = t;
146
147 return t + s;
148 }
149
RandUint32()150 uint32_t InsecureRandomGenerator::RandUint32() {
151 // The generator usually returns an uint64_t, truncate it.
152 //
153 // It is noted in this paper (https://arxiv.org/abs/1810.05313) that the
154 // lowest 32 bits fail some statistical tests from the Big Crush
155 // suite. Use the higher ones instead.
156 return this->RandUint64() >> 32;
157 }
158
RandDouble()159 double InsecureRandomGenerator::RandDouble() {
160 uint64_t x = RandUint64();
161 // From https://vigna.di.unimi.it/xorshift/.
162 // 53 bits of mantissa, hence the "hexadecimal exponent" 1p-53.
163 return (x >> 11) * 0x1.0p-53;
164 }
165
166 MetricsSubSampler::MetricsSubSampler() = default;
ShouldSample(double probability)167 bool MetricsSubSampler::ShouldSample(double probability) {
168 if (g_subsampling_always_sample.load(std::memory_order_relaxed)) {
169 return true;
170 }
171 if (g_subsampling_never_sample.load(std::memory_order_relaxed)) {
172 return false;
173 }
174
175 return generator_.RandDouble() < probability;
176 }
177
178 MetricsSubSampler::ScopedAlwaysSampleForTesting::
ScopedAlwaysSampleForTesting()179 ScopedAlwaysSampleForTesting() {
180 DCHECK(!g_subsampling_always_sample.load(std::memory_order_relaxed));
181 DCHECK(!g_subsampling_never_sample.load(std::memory_order_relaxed));
182 g_subsampling_always_sample.store(true, std::memory_order_relaxed);
183 }
184
185 MetricsSubSampler::ScopedAlwaysSampleForTesting::
~ScopedAlwaysSampleForTesting()186 ~ScopedAlwaysSampleForTesting() {
187 DCHECK(g_subsampling_always_sample.load(std::memory_order_relaxed));
188 DCHECK(!g_subsampling_never_sample.load(std::memory_order_relaxed));
189 g_subsampling_always_sample.store(false, std::memory_order_relaxed);
190 }
191
ScopedNeverSampleForTesting()192 MetricsSubSampler::ScopedNeverSampleForTesting::ScopedNeverSampleForTesting() {
193 DCHECK(!g_subsampling_always_sample.load(std::memory_order_relaxed));
194 DCHECK(!g_subsampling_never_sample.load(std::memory_order_relaxed));
195 g_subsampling_never_sample.store(true, std::memory_order_relaxed);
196 }
197
~ScopedNeverSampleForTesting()198 MetricsSubSampler::ScopedNeverSampleForTesting::~ScopedNeverSampleForTesting() {
199 DCHECK(!g_subsampling_always_sample);
200 DCHECK(g_subsampling_never_sample);
201 g_subsampling_never_sample.store(false, std::memory_order_relaxed);
202 }
203
204 } // namespace base
205