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