xref: /aosp_15_r20/external/cronet/base/rand_util.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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(&number, sizeof(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   DCHECK_GT(length, 0u);
115   std::string result(length, '\0');
116   RandBytes(result.data(), length);
117   return result;
118 }
119 
RandBytesAsVector(size_t length)120 std::vector<uint8_t> RandBytesAsVector(size_t length) {
121   std::vector<uint8_t> result(length);
122   if (result.size()) {
123     RandBytes(result);
124   }
125   return result;
126 }
127 
InsecureRandomGenerator()128 InsecureRandomGenerator::InsecureRandomGenerator() {
129   a_ = base::RandUint64();
130   b_ = base::RandUint64();
131 }
132 
ReseedForTesting(uint64_t seed)133 void InsecureRandomGenerator::ReseedForTesting(uint64_t seed) {
134   a_ = seed;
135   b_ = seed;
136 }
137 
RandUint64()138 uint64_t InsecureRandomGenerator::RandUint64() {
139   // Using XorShift128+, which is simple and widely used. See
140   // https://en.wikipedia.org/wiki/Xorshift#xorshift+ for details.
141   uint64_t t = a_;
142   const uint64_t s = b_;
143 
144   a_ = s;
145   t ^= t << 23;
146   t ^= t >> 17;
147   t ^= s ^ (s >> 26);
148   b_ = t;
149 
150   return t + s;
151 }
152 
RandUint32()153 uint32_t InsecureRandomGenerator::RandUint32() {
154   // The generator usually returns an uint64_t, truncate it.
155   //
156   // It is noted in this paper (https://arxiv.org/abs/1810.05313) that the
157   // lowest 32 bits fail some statistical tests from the Big Crush
158   // suite. Use the higher ones instead.
159   return this->RandUint64() >> 32;
160 }
161 
RandDouble()162 double InsecureRandomGenerator::RandDouble() {
163   uint64_t x = RandUint64();
164   // From https://vigna.di.unimi.it/xorshift/.
165   // 53 bits of mantissa, hence the "hexadecimal exponent" 1p-53.
166   return (x >> 11) * 0x1.0p-53;
167 }
168 
169 MetricsSubSampler::MetricsSubSampler() = default;
ShouldSample(double probability)170 bool MetricsSubSampler::ShouldSample(double probability) {
171   if (g_subsampling_always_sample.load(std::memory_order_relaxed)) {
172     return true;
173   }
174   if (g_subsampling_never_sample.load(std::memory_order_relaxed)) {
175     return false;
176   }
177 
178   return generator_.RandDouble() < probability;
179 }
180 
181 MetricsSubSampler::ScopedAlwaysSampleForTesting::
ScopedAlwaysSampleForTesting()182     ScopedAlwaysSampleForTesting() {
183   DCHECK(!g_subsampling_always_sample.load(std::memory_order_relaxed));
184   DCHECK(!g_subsampling_never_sample.load(std::memory_order_relaxed));
185   g_subsampling_always_sample.store(true, std::memory_order_relaxed);
186 }
187 
188 MetricsSubSampler::ScopedAlwaysSampleForTesting::
~ScopedAlwaysSampleForTesting()189     ~ScopedAlwaysSampleForTesting() {
190   DCHECK(g_subsampling_always_sample.load(std::memory_order_relaxed));
191   DCHECK(!g_subsampling_never_sample.load(std::memory_order_relaxed));
192   g_subsampling_always_sample.store(false, std::memory_order_relaxed);
193 }
194 
ScopedNeverSampleForTesting()195 MetricsSubSampler::ScopedNeverSampleForTesting::ScopedNeverSampleForTesting() {
196   DCHECK(!g_subsampling_always_sample.load(std::memory_order_relaxed));
197   DCHECK(!g_subsampling_never_sample.load(std::memory_order_relaxed));
198   g_subsampling_never_sample.store(true, std::memory_order_relaxed);
199 }
200 
~ScopedNeverSampleForTesting()201 MetricsSubSampler::ScopedNeverSampleForTesting::~ScopedNeverSampleForTesting() {
202   DCHECK(!g_subsampling_always_sample);
203   DCHECK(g_subsampling_never_sample);
204   g_subsampling_never_sample.store(false, std::memory_order_relaxed);
205 }
206 
207 }  // namespace base
208