1// Copyright (c) 2011 The Chromium Authors. All rights reserved.
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 <algorithm>
8#include <limits>
9
10#include "base/logging.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/time/time.h"
13#include "testing/gtest/include/gtest/gtest.h"
14
15namespace {
16
17const int kIntMin = std::numeric_limits<int>::min();
18const int kIntMax = std::numeric_limits<int>::max();
19
20}  // namespace
21
22TEST(RandUtilTest, SameMinAndMax) {
23  EXPECT_EQ(base::RandInt(0, 0), 0);
24  EXPECT_EQ(base::RandInt(kIntMin, kIntMin), kIntMin);
25  EXPECT_EQ(base::RandInt(kIntMax, kIntMax), kIntMax);
26}
27
28TEST(RandUtilTest, RandDouble) {
29  // Force 64-bit precision, making sure we're not in a 80-bit FPU register.
30  volatile double number = base::RandDouble();
31  EXPECT_GT(1.0, number);
32  EXPECT_LE(0.0, number);
33}
34
35TEST(RandUtilTest, RandBytes) {
36  const size_t buffer_size = 50;
37  char buffer[buffer_size];
38  memset(buffer, 0, buffer_size);
39  base::RandBytes(buffer, buffer_size);
40  std::sort(buffer, buffer + buffer_size);
41  // Probability of occurrence of less than 25 unique bytes in 50 random bytes
42  // is below 10^-25.
43  EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25);
44}
45
46TEST(RandUtilTest, RandBytesAsString) {
47  std::string random_string = base::RandBytesAsString(1);
48  EXPECT_EQ(1U, random_string.size());
49  random_string = base::RandBytesAsString(145);
50  EXPECT_EQ(145U, random_string.size());
51  char accumulator = 0;
52  for (size_t i = 0; i < random_string.size(); ++i)
53    accumulator |= random_string[i];
54  // In theory this test can fail, but it won't before the universe dies of
55  // heat death.
56  EXPECT_NE(0, accumulator);
57}
58
59// Make sure that it is still appropriate to use RandGenerator in conjunction
60// with std::random_shuffle().
61TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
62  EXPECT_EQ(base::RandGenerator(1), 0U);
63  EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
64            std::numeric_limits<int64>::max());
65}
66
67TEST(RandUtilTest, RandGeneratorIsUniform) {
68  // Verify that RandGenerator has a uniform distribution. This is a
69  // regression test that consistently failed when RandGenerator was
70  // implemented this way:
71  //
72  //   return base::RandUint64() % max;
73  //
74  // A degenerate case for such an implementation is e.g. a top of
75  // range that is 2/3rds of the way to MAX_UINT64, in which case the
76  // bottom half of the range would be twice as likely to occur as the
77  // top half. A bit of calculus care of jar@ shows that the largest
78  // measurable delta is when the top of the range is 3/4ths of the
79  // way, so that's what we use in the test.
80  const uint64 kTopOfRange = (std::numeric_limits<uint64>::max() / 4ULL) * 3ULL;
81  const uint64 kExpectedAverage = kTopOfRange / 2ULL;
82  const uint64 kAllowedVariance = kExpectedAverage / 50ULL;  // +/- 2%
83  const int kMinAttempts = 1000;
84  const int kMaxAttempts = 1000000;
85
86  double cumulative_average = 0.0;
87  int count = 0;
88  while (count < kMaxAttempts) {
89    uint64 value = base::RandGenerator(kTopOfRange);
90    cumulative_average = (count * cumulative_average + value) / (count + 1);
91
92    // Don't quit too quickly for things to start converging, or we may have
93    // a false positive.
94    if (count > kMinAttempts &&
95        kExpectedAverage - kAllowedVariance < cumulative_average &&
96        cumulative_average < kExpectedAverage + kAllowedVariance) {
97      break;
98    }
99
100    ++count;
101  }
102
103  ASSERT_LT(count, kMaxAttempts) << "Expected average was " <<
104      kExpectedAverage << ", average ended at " << cumulative_average;
105}
106
107TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
108  // This tests to see that our underlying random generator is good
109  // enough, for some value of good enough.
110  uint64 kAllZeros = 0ULL;
111  uint64 kAllOnes = ~kAllZeros;
112  uint64 found_ones = kAllZeros;
113  uint64 found_zeros = kAllOnes;
114
115  for (size_t i = 0; i < 1000; ++i) {
116    uint64 value = base::RandUint64();
117    found_ones |= value;
118    found_zeros &= value;
119
120    if (found_zeros == kAllZeros && found_ones == kAllOnes)
121      return;
122  }
123
124  FAIL() << "Didn't achieve all bit values in maximum number of tries.";
125}
126
127// Benchmark test for RandBytes().  Disabled since it's intentionally slow and
128// does not test anything that isn't already tested by the existing RandBytes()
129// tests.
130TEST(RandUtilTest, DISABLED_RandBytesPerf) {
131  // Benchmark the performance of |kTestIterations| of RandBytes() using a
132  // buffer size of |kTestBufferSize|.
133  const int kTestIterations = 10;
134  const size_t kTestBufferSize = 1 * 1024 * 1024;
135
136  scoped_ptr<uint8[]> buffer(new uint8[kTestBufferSize]);
137  const base::TimeTicks now = base::TimeTicks::HighResNow();
138  for (int i = 0; i < kTestIterations; ++i)
139    base::RandBytes(buffer.get(), kTestBufferSize);
140  const base::TimeTicks end = base::TimeTicks::HighResNow();
141
142  LOG(INFO) << "RandBytes(" << kTestBufferSize << ") took: "
143            << (end - now).InMicroseconds() << "µs";
144}
145