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.
5 #include "base/rand_util.h"
14 #include "base/check_op.h"
15 #include "base/strings/string_util.h"
16 #include "base/time/time.h"
22 bool g_subsampling_enabled = true;
26 uint64_t RandUint64() {
28 RandBytes(&number, sizeof(number));
32 int RandInt(int min, int max) {
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.
39 static_cast<int>(min + static_cast<int64_t>(base::RandGenerator(range)));
40 DCHECK_GE(result, min);
41 DCHECK_LE(result, max);
46 return BitsToOpenEndedUnitInterval(base::RandUint64());
50 return BitsToOpenEndedUnitIntervalF(base::RandUint64());
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());
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));
66 TimeDelta RandTimeDeltaUpTo(TimeDelta limit) {
67 return RandTimeDelta(TimeDelta(), limit);
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);
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);
91 uint64_t RandGenerator(uint64_t range) {
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;
102 value = base::RandUint64();
103 } while (value > max_acceptable_value);
105 return value % range;
108 std::string RandBytesAsString(size_t length) {
109 DCHECK_GT(length, 0u);
111 RandBytes(WriteInto(&result, length + 1), length);
115 InsecureRandomGenerator::InsecureRandomGenerator() {
116 a_ = base::RandUint64();
117 b_ = base::RandUint64();
120 void InsecureRandomGenerator::ReseedForTesting(uint64_t seed) {
125 uint64_t InsecureRandomGenerator::RandUint64() {
126 // Using XorShift128+, which is simple and widely used. See
127 // https://en.wikipedia.org/wiki/Xorshift#xorshift+ for details.
129 const uint64_t s = b_;
140 uint32_t InsecureRandomGenerator::RandUint32() {
141 // The generator usually returns an uint64_t, truncate it.
143 // It is noted in this paper (https://arxiv.org/abs/1810.05313) that the
144 // lowest 32 bits fail some statistical tests from the Big Crush
145 // suite. Use the higher ones instead.
146 return this->RandUint64() >> 32;
149 double InsecureRandomGenerator::RandDouble() {
150 uint64_t x = RandUint64();
151 // From https://vigna.di.unimi.it/xorshift/.
152 // 53 bits of mantissa, hence the "hexadecimal exponent" 1p-53.
153 return (x >> 11) * 0x1.0p-53;
156 MetricsSubSampler::MetricsSubSampler() = default;
157 bool MetricsSubSampler::ShouldSample(double probability) {
158 return !g_subsampling_enabled || generator_.RandDouble() < probability;
161 MetricsSubSampler::ScopedDisableForTesting::ScopedDisableForTesting() {
162 DCHECK(g_subsampling_enabled);
163 g_subsampling_enabled = false;
166 MetricsSubSampler::ScopedDisableForTesting::~ScopedDisableForTesting() {
167 DCHECK(!g_subsampling_enabled);
168 g_subsampling_enabled = true;