blob: 7c731b23d8d81c8a075c43385304afb6fcd747b7 [file] [log] [blame]
Avi Drissmane4622aa2022-09-08 20:36:061// Copyright 2011 The Chromium Authors
[email protected]05f9b682008-09-29 22:18:012// 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
avi9b6f42932015-12-26 22:15:147#include <stddef.h>
8#include <stdint.h>
9
[email protected]0173b962011-08-24 19:58:3610#include <algorithm>
Benoit Lize73de21b2021-07-02 08:17:5611#include <cmath>
[email protected]05f9b682008-09-29 22:18:0112#include <limits>
dcheng093de9b2016-04-04 21:25:5113#include <memory>
Benoit Lize73de21b2021-07-02 08:17:5614#include <vector>
[email protected]05f9b682008-09-29 22:18:0115
Austin Sullivana41f7f62024-01-09 20:11:5016#include "base/containers/span.h"
[email protected]c910c5a2014-01-23 02:14:2817#include "base/logging.h"
[email protected]c910c5a2014-01-23 02:14:2818#include "base/time/time.h"
[email protected]05f9b682008-09-29 22:18:0119#include "testing/gtest/include/gtest/gtest.h"
20
Benoit Lize73de21b2021-07-02 08:17:5621namespace base {
22
[email protected]05f9b682008-09-29 22:18:0123namespace {
24
25const int kIntMin = std::numeric_limits<int>::min();
26const int kIntMax = std::numeric_limits<int>::max();
27
28} // namespace
29
Nico Weber0a3852a72015-10-29 20:42:5830TEST(RandUtilTest, RandInt) {
[email protected]05f9b682008-09-29 22:18:0131 EXPECT_EQ(base::RandInt(0, 0), 0);
32 EXPECT_EQ(base::RandInt(kIntMin, kIntMin), kIntMin);
33 EXPECT_EQ(base::RandInt(kIntMax, kIntMax), kIntMax);
Nico Weber0a3852a72015-10-29 20:42:5834
35 // Check that the DCHECKS in RandInt() don't fire due to internal overflow.
36 // There was a 50% chance of that happening, so calling it 40 times means
37 // the chances of this passing by accident are tiny (9e-13).
38 for (int i = 0; i < 40; ++i)
39 base::RandInt(kIntMin, kIntMax);
[email protected]05f9b682008-09-29 22:18:0140}
[email protected]94a0f312008-09-30 14:26:3341
42TEST(RandUtilTest, RandDouble) {
[email protected]29548d82011-04-29 21:03:5443 // Force 64-bit precision, making sure we're not in a 80-bit FPU register.
44 volatile double number = base::RandDouble();
45 EXPECT_GT(1.0, number);
46 EXPECT_LE(0.0, number);
47}
48
Avery Musbacheff342b2022-10-06 18:36:0749TEST(RandUtilTest, RandFloat) {
50 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
51 volatile float number = base::RandFloat();
52 EXPECT_GT(1.f, number);
53 EXPECT_LE(0.f, number);
54}
55
Peter Kastingf18c8ca2023-10-04 16:31:5156TEST(RandUtilTest, RandTimeDelta) {
57 {
58 const auto delta =
59 base::RandTimeDelta(-base::Seconds(2), -base::Seconds(1));
60 EXPECT_GE(delta, -base::Seconds(2));
61 EXPECT_LT(delta, -base::Seconds(1));
62 }
63
64 {
65 const auto delta = base::RandTimeDelta(-base::Seconds(2), base::Seconds(2));
66 EXPECT_GE(delta, -base::Seconds(2));
67 EXPECT_LT(delta, base::Seconds(2));
68 }
69
70 {
71 const auto delta = base::RandTimeDelta(base::Seconds(1), base::Seconds(2));
72 EXPECT_GE(delta, base::Seconds(1));
73 EXPECT_LT(delta, base::Seconds(2));
74 }
75}
76
77TEST(RandUtilTest, RandTimeDeltaUpTo) {
78 const auto delta = base::RandTimeDeltaUpTo(base::Seconds(2));
79 EXPECT_FALSE(delta.is_negative());
80 EXPECT_LT(delta, base::Seconds(2));
81}
82
Avery Musbach92a30e382022-09-08 23:30:4183TEST(RandUtilTest, BitsToOpenEndedUnitInterval) {
84 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
85 volatile double all_zeros = BitsToOpenEndedUnitInterval(0x0);
86 EXPECT_EQ(0.0, all_zeros);
87
88 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
89 volatile double smallest_nonzero = BitsToOpenEndedUnitInterval(0x1);
90 EXPECT_LT(0.0, smallest_nonzero);
91
92 for (uint64_t i = 0x2; i < 0x10; ++i) {
93 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
94 volatile double number = BitsToOpenEndedUnitInterval(i);
95 EXPECT_EQ(i * smallest_nonzero, number);
96 }
97
98 // Force 64-bit precision, making sure we're not in an 80-bit FPU register.
99 volatile double all_ones = BitsToOpenEndedUnitInterval(UINT64_MAX);
100 EXPECT_GT(1.0, all_ones);
101}
102
Avery Musbacheff342b2022-10-06 18:36:07103TEST(RandUtilTest, BitsToOpenEndedUnitIntervalF) {
104 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
105 volatile float all_zeros = BitsToOpenEndedUnitIntervalF(0x0);
106 EXPECT_EQ(0.f, all_zeros);
107
108 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
109 volatile float smallest_nonzero = BitsToOpenEndedUnitIntervalF(0x1);
110 EXPECT_LT(0.f, smallest_nonzero);
111
112 for (uint64_t i = 0x2; i < 0x10; ++i) {
113 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
114 volatile float number = BitsToOpenEndedUnitIntervalF(i);
115 EXPECT_EQ(i * smallest_nonzero, number);
116 }
117
118 // Force 32-bit precision, making sure we're not in an 80-bit FPU register.
119 volatile float all_ones = BitsToOpenEndedUnitIntervalF(UINT64_MAX);
120 EXPECT_GT(1.f, all_ones);
121}
122
[email protected]51a01812011-05-05 08:46:11123TEST(RandUtilTest, RandBytes) {
[email protected]0173b962011-08-24 19:58:36124 const size_t buffer_size = 50;
Austin Sullivana41f7f62024-01-09 20:11:50125 uint8_t buffer[buffer_size];
[email protected]51a01812011-05-05 08:46:11126 memset(buffer, 0, buffer_size);
Austin Sullivana41f7f62024-01-09 20:11:50127 base::RandBytes(buffer);
[email protected]0173b962011-08-24 19:58:36128 std::sort(buffer, buffer + buffer_size);
129 // Probability of occurrence of less than 25 unique bytes in 50 random bytes
130 // is below 10^-25.
131 EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25);
[email protected]51a01812011-05-05 08:46:11132}
133
Sergey Ulanovfdc62f8e2017-08-01 19:51:00134// Verify that calling base::RandBytes with an empty buffer doesn't fail.
135TEST(RandUtilTest, RandBytes0) {
Austin Sullivana41f7f62024-01-09 20:11:50136 base::RandBytes(span<uint8_t>());
Sergey Ulanovfdc62f8e2017-08-01 19:51:00137 base::RandBytes(nullptr, 0);
138}
139
Tom Sepez230a75c62023-11-13 23:27:16140TEST(RandUtilTest, RandBytesAsVector) {
141 std::vector<uint8_t> random_vec = base::RandBytesAsVector(0);
142 EXPECT_TRUE(random_vec.empty());
143 random_vec = base::RandBytesAsVector(1);
144 EXPECT_EQ(1U, random_vec.size());
145 random_vec = base::RandBytesAsVector(145);
146 EXPECT_EQ(145U, random_vec.size());
147 char accumulator = 0;
148 for (auto i : random_vec) {
149 accumulator |= i;
150 }
151 // In theory this test can fail, but it won't before the universe dies of
152 // heat death.
153 EXPECT_NE(0, accumulator);
154}
155
[email protected]29548d82011-04-29 21:03:54156TEST(RandUtilTest, RandBytesAsString) {
[email protected]fdce4782011-11-29 20:06:18157 std::string random_string = base::RandBytesAsString(1);
158 EXPECT_EQ(1U, random_string.size());
[email protected]29548d82011-04-29 21:03:54159 random_string = base::RandBytesAsString(145);
160 EXPECT_EQ(145U, random_string.size());
161 char accumulator = 0;
jdoerrie6c6229352018-10-22 15:55:43162 for (auto i : random_string)
163 accumulator |= i;
[email protected]29548d82011-04-29 21:03:54164 // In theory this test can fail, but it won't before the universe dies of
165 // heat death.
166 EXPECT_NE(0, accumulator);
[email protected]94a0f312008-09-30 14:26:33167}
[email protected]a74dcae2010-08-30 21:07:05168
169// Make sure that it is still appropriate to use RandGenerator in conjunction
170// with std::random_shuffle().
171TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
172 EXPECT_EQ(base::RandGenerator(1), 0U);
173 EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
avi9b6f42932015-12-26 22:15:14174 std::numeric_limits<int64_t>::max());
[email protected]a74dcae2010-08-30 21:07:05175}
[email protected]af2e192b2011-05-30 17:39:09176
177TEST(RandUtilTest, RandGeneratorIsUniform) {
178 // Verify that RandGenerator has a uniform distribution. This is a
179 // regression test that consistently failed when RandGenerator was
180 // implemented this way:
181 //
182 // return base::RandUint64() % max;
183 //
184 // A degenerate case for such an implementation is e.g. a top of
185 // range that is 2/3rds of the way to MAX_UINT64, in which case the
186 // bottom half of the range would be twice as likely to occur as the
187 // top half. A bit of calculus care of jar@ shows that the largest
188 // measurable delta is when the top of the range is 3/4ths of the
189 // way, so that's what we use in the test.
Peter Kastingfbb9e562021-06-27 02:57:37190 constexpr uint64_t kTopOfRange =
avi9b6f42932015-12-26 22:15:14191 (std::numeric_limits<uint64_t>::max() / 4ULL) * 3ULL;
Peter Kastingfbb9e562021-06-27 02:57:37192 constexpr double kExpectedAverage = static_cast<double>(kTopOfRange / 2);
193 constexpr double kAllowedVariance = kExpectedAverage / 50.0; // +/- 2%
194 constexpr int kMinAttempts = 1000;
195 constexpr int kMaxAttempts = 1000000;
[email protected]af2e192b2011-05-30 17:39:09196
197 double cumulative_average = 0.0;
198 int count = 0;
199 while (count < kMaxAttempts) {
avi9b6f42932015-12-26 22:15:14200 uint64_t value = base::RandGenerator(kTopOfRange);
[email protected]af2e192b2011-05-30 17:39:09201 cumulative_average = (count * cumulative_average + value) / (count + 1);
202
203 // Don't quit too quickly for things to start converging, or we may have
204 // a false positive.
205 if (count > kMinAttempts &&
206 kExpectedAverage - kAllowedVariance < cumulative_average &&
207 cumulative_average < kExpectedAverage + kAllowedVariance) {
208 break;
209 }
210
211 ++count;
212 }
213
Benoit Lize73de21b2021-07-02 08:17:56214 ASSERT_LT(count, kMaxAttempts) << "Expected average was " << kExpectedAverage
215 << ", average ended at " << cumulative_average;
[email protected]af2e192b2011-05-30 17:39:09216}
217
218TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
219 // This tests to see that our underlying random generator is good
220 // enough, for some value of good enough.
avi9b6f42932015-12-26 22:15:14221 uint64_t kAllZeros = 0ULL;
222 uint64_t kAllOnes = ~kAllZeros;
223 uint64_t found_ones = kAllZeros;
224 uint64_t found_zeros = kAllOnes;
[email protected]af2e192b2011-05-30 17:39:09225
226 for (size_t i = 0; i < 1000; ++i) {
avi9b6f42932015-12-26 22:15:14227 uint64_t value = base::RandUint64();
[email protected]af2e192b2011-05-30 17:39:09228 found_ones |= value;
229 found_zeros &= value;
230
231 if (found_zeros == kAllZeros && found_ones == kAllOnes)
232 return;
233 }
234
235 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
236}
[email protected]c910c5a2014-01-23 02:14:28237
Scott Graham4ffd63b52017-06-01 18:03:33238TEST(RandUtilTest, RandBytesLonger) {
239 // Fuchsia can only retrieve 256 bytes of entropy at a time, so make sure we
240 // handle longer requests than that.
241 std::string random_string0 = base::RandBytesAsString(255);
242 EXPECT_EQ(255u, random_string0.size());
243 std::string random_string1 = base::RandBytesAsString(1023);
244 EXPECT_EQ(1023u, random_string1.size());
245 std::string random_string2 = base::RandBytesAsString(4097);
246 EXPECT_EQ(4097u, random_string2.size());
247}
248
[email protected]c910c5a2014-01-23 02:14:28249// Benchmark test for RandBytes(). Disabled since it's intentionally slow and
250// does not test anything that isn't already tested by the existing RandBytes()
251// tests.
252TEST(RandUtilTest, DISABLED_RandBytesPerf) {
253 // Benchmark the performance of |kTestIterations| of RandBytes() using a
254 // buffer size of |kTestBufferSize|.
255 const int kTestIterations = 10;
256 const size_t kTestBufferSize = 1 * 1024 * 1024;
257
dcheng093de9b2016-04-04 21:25:51258 std::unique_ptr<uint8_t[]> buffer(new uint8_t[kTestBufferSize]);
charliea3be839702015-01-26 17:35:41259 const base::TimeTicks now = base::TimeTicks::Now();
[email protected]c910c5a2014-01-23 02:14:28260 for (int i = 0; i < kTestIterations; ++i)
Austin Sullivana41f7f62024-01-09 20:11:50261 base::RandBytes(make_span(buffer.get(), kTestBufferSize));
charliea3be839702015-01-26 17:35:41262 const base::TimeTicks end = base::TimeTicks::Now();
[email protected]c910c5a2014-01-23 02:14:28263
Benoit Lize73de21b2021-07-02 08:17:56264 LOG(INFO) << "RandBytes(" << kTestBufferSize
265 << ") took: " << (end - now).InMicroseconds() << "µs";
[email protected]c910c5a2014-01-23 02:14:28266}
Benoit Lize73de21b2021-07-02 08:17:56267
268TEST(RandUtilTest, InsecureRandomGeneratorProducesBothValuesOfAllBits) {
269 // This tests to see that our underlying random generator is good
270 // enough, for some value of good enough.
271 uint64_t kAllZeros = 0ULL;
272 uint64_t kAllOnes = ~kAllZeros;
273 uint64_t found_ones = kAllZeros;
274 uint64_t found_zeros = kAllOnes;
275
276 InsecureRandomGenerator generator;
Benoit Lize73de21b2021-07-02 08:17:56277
278 for (size_t i = 0; i < 1000; ++i) {
279 uint64_t value = generator.RandUint64();
280 found_ones |= value;
281 found_zeros &= value;
282
283 if (found_zeros == kAllZeros && found_ones == kAllOnes)
284 return;
285 }
286
287 FAIL() << "Didn't achieve all bit values in maximum number of tries.";
288}
289
290namespace {
291
292constexpr double kXp1Percent = -2.33;
293constexpr double kXp99Percent = 2.33;
294
295double ChiSquaredCriticalValue(double nu, double x_p) {
296 // From "The Art Of Computer Programming" (TAOCP), Volume 2, Section 3.3.1,
297 // Table 1. This is the asymptotic value for nu > 30, up to O(1 / sqrt(nu)).
298 return nu + sqrt(2. * nu) * x_p + 2. / 3. * (x_p * x_p) - 2. / 3.;
299}
300
301int ExtractBits(uint64_t value, int from_bit, int num_bits) {
302 return (value >> from_bit) & ((1 << num_bits) - 1);
303}
304
305// Performs a Chi-Squared test on a subset of |num_bits| extracted starting from
306// |from_bit| in the generated value.
307//
308// See TAOCP, Volume 2, Section 3.3.1, and
309// https://en.wikipedia.org/wiki/Pearson%27s_chi-squared_test for details.
310//
311// This is only one of the many, many random number generator test we could do,
312// but they are cumbersome, as they are typically very slow, and expected to
313// fail from time to time, due to their probabilistic nature.
314//
315// The generator we use has however been vetted with the BigCrush test suite
316// from Marsaglia, so this should suffice as a smoke test that our
317// implementation is wrong.
318bool ChiSquaredTest(InsecureRandomGenerator& gen,
319 size_t n,
320 int from_bit,
321 int num_bits) {
322 const int range = 1 << num_bits;
323 CHECK_EQ(static_cast<int>(n % range), 0) << "Makes computations simpler";
324 std::vector<size_t> samples(range, 0);
325
326 // Count how many samples pf each value are found. All buckets should be
327 // almost equal if the generator is suitably uniformly random.
328 for (size_t i = 0; i < n; i++) {
329 int sample = ExtractBits(gen.RandUint64(), from_bit, num_bits);
330 samples[sample] += 1;
331 }
332
333 // Compute the Chi-Squared statistic, which is:
334 // \Sum_{k=0}^{range-1} \frac{(count - expected)^2}{expected}
335 double chi_squared = 0.;
336 double expected_count = n / range;
337 for (size_t sample_count : samples) {
338 double deviation = sample_count - expected_count;
339 chi_squared += (deviation * deviation) / expected_count;
340 }
341
342 // The generator should produce numbers that are not too far of (chi_squared
343 // lower than a given quantile), but not too close to the ideal distribution
344 // either (chi_squared is too low).
345 //
346 // See The Art Of Computer Programming, Volume 2, Section 3.3.1 for details.
347 return chi_squared > ChiSquaredCriticalValue(range - 1, kXp1Percent) &&
348 chi_squared < ChiSquaredCriticalValue(range - 1, kXp99Percent);
349}
350
351} // namespace
352
353TEST(RandUtilTest, InsecureRandomGeneratorChiSquared) {
354 constexpr int kIterations = 50;
355
356 // Specifically test the low bits, which are usually weaker in random number
357 // generators. We don't use them for the 32 bit number generation, but let's
358 // make sure they are still suitable.
359 for (int start_bit : {1, 2, 3, 8, 12, 20, 32, 48, 54}) {
360 int pass_count = 0;
361 for (int i = 0; i < kIterations; i++) {
362 size_t samples = 1 << 16;
363 InsecureRandomGenerator gen;
364 // Fix the seed to make the test non-flaky.
Benoit Lize7532d4af2021-08-24 11:34:04365 gen.ReseedForTesting(kIterations + 1);
Benoit Lize73de21b2021-07-02 08:17:56366 bool pass = ChiSquaredTest(gen, samples, start_bit, 8);
367 pass_count += pass;
368 }
369
370 // We exclude 1% on each side, so we expect 98% of tests to pass, meaning 98
371 // * kIterations / 100. However this is asymptotic, so add a bit of leeway.
372 int expected_pass_count = (kIterations * 98) / 100;
373 EXPECT_GE(pass_count, expected_pass_count - ((kIterations * 2) / 100))
374 << "For start_bit = " << start_bit;
375 }
376}
377
Benoit Lized6377142021-07-05 10:17:16378TEST(RandUtilTest, InsecureRandomGeneratorRandDouble) {
379 InsecureRandomGenerator gen;
Benoit Lized6377142021-07-05 10:17:16380
381 for (int i = 0; i < 1000; i++) {
382 volatile double x = gen.RandDouble();
383 EXPECT_GE(x, 0.);
384 EXPECT_LT(x, 1.);
385 }
386}
Benoit Lize73de21b2021-07-02 08:17:56387} // namespace base