#include "base/rand_util.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <memory>
#include <vector>
#include "base/logging.h"
#include "base/time/time.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
const int kIntMin = std::numeric_limits<int>::min();
const int kIntMax = std::numeric_limits<int>::max();
}
TEST(RandUtilTest, RandInt) {
EXPECT_EQ(base::RandInt(0, 0), 0);
EXPECT_EQ(base::RandInt(kIntMin, kIntMin), kIntMin);
EXPECT_EQ(base::RandInt(kIntMax, kIntMax), kIntMax);
for (int i = 0; i < 40; ++i)
base::RandInt(kIntMin, kIntMax);
}
TEST(RandUtilTest, RandDouble) {
volatile double number = base::RandDouble();
EXPECT_GT(1.0, number);
EXPECT_LE(0.0, number);
}
TEST(RandUtilTest, RandFloat) {
volatile float number = base::RandFloat();
EXPECT_GT(1.f, number);
EXPECT_LE(0.f, number);
}
TEST(RandUtilTest, BitsToOpenEndedUnitInterval) {
volatile double all_zeros = BitsToOpenEndedUnitInterval(0x0);
EXPECT_EQ(0.0, all_zeros);
volatile double smallest_nonzero = BitsToOpenEndedUnitInterval(0x1);
EXPECT_LT(0.0, smallest_nonzero);
for (uint64_t i = 0x2; i < 0x10; ++i) {
volatile double number = BitsToOpenEndedUnitInterval(i);
EXPECT_EQ(i * smallest_nonzero, number);
}
volatile double all_ones = BitsToOpenEndedUnitInterval(UINT64_MAX);
EXPECT_GT(1.0, all_ones);
}
TEST(RandUtilTest, BitsToOpenEndedUnitIntervalF) {
volatile float all_zeros = BitsToOpenEndedUnitIntervalF(0x0);
EXPECT_EQ(0.f, all_zeros);
volatile float smallest_nonzero = BitsToOpenEndedUnitIntervalF(0x1);
EXPECT_LT(0.f, smallest_nonzero);
for (uint64_t i = 0x2; i < 0x10; ++i) {
volatile float number = BitsToOpenEndedUnitIntervalF(i);
EXPECT_EQ(i * smallest_nonzero, number);
}
volatile float all_ones = BitsToOpenEndedUnitIntervalF(UINT64_MAX);
EXPECT_GT(1.f, all_ones);
}
TEST(RandUtilTest, RandBytes) {
const size_t buffer_size = 50;
char buffer[buffer_size];
memset(buffer, 0, buffer_size);
base::RandBytes(buffer, buffer_size);
std::sort(buffer, buffer + buffer_size);
EXPECT_GT(std::unique(buffer, buffer + buffer_size) - buffer, 25);
}
TEST(RandUtilTest, RandBytes0) {
base::RandBytes(nullptr, 0);
}
TEST(RandUtilTest, RandBytesAsString) {
std::string random_string = base::RandBytesAsString(1);
EXPECT_EQ(1U, random_string.size());
random_string = base::RandBytesAsString(145);
EXPECT_EQ(145U, random_string.size());
char accumulator = 0;
for (auto i : random_string)
accumulator |= i;
EXPECT_NE(0, accumulator);
}
TEST(RandUtilTest, RandGeneratorForRandomShuffle) {
EXPECT_EQ(base::RandGenerator(1), 0U);
EXPECT_LE(std::numeric_limits<ptrdiff_t>::max(),
std::numeric_limits<int64_t>::max());
}
TEST(RandUtilTest, RandGeneratorIsUniform) {
constexpr uint64_t kTopOfRange =
(std::numeric_limits<uint64_t>::max() / 4ULL) * 3ULL;
constexpr double kExpectedAverage = static_cast<double>(kTopOfRange / 2);
constexpr double kAllowedVariance = kExpectedAverage / 50.0;
constexpr int kMinAttempts = 1000;
constexpr int kMaxAttempts = 1000000;
double cumulative_average = 0.0;
int count = 0;
while (count < kMaxAttempts) {
uint64_t value = base::RandGenerator(kTopOfRange);
cumulative_average = (count * cumulative_average + value) / (count + 1);
if (count > kMinAttempts &&
kExpectedAverage - kAllowedVariance < cumulative_average &&
cumulative_average < kExpectedAverage + kAllowedVariance) {
break;
}
++count;
}
ASSERT_LT(count, kMaxAttempts) << "Expected average was " << kExpectedAverage
<< ", average ended at " << cumulative_average;
}
TEST(RandUtilTest, RandUint64ProducesBothValuesOfAllBits) {
uint64_t kAllZeros = 0ULL;
uint64_t kAllOnes = ~kAllZeros;
uint64_t found_ones = kAllZeros;
uint64_t found_zeros = kAllOnes;
for (size_t i = 0; i < 1000; ++i) {
uint64_t value = base::RandUint64();
found_ones |= value;
found_zeros &= value;
if (found_zeros == kAllZeros && found_ones == kAllOnes)
return;
}
FAIL() << "Didn't achieve all bit values in maximum number of tries.";
}
TEST(RandUtilTest, RandBytesLonger) {
std::string random_string0 = base::RandBytesAsString(255);
EXPECT_EQ(255u, random_string0.size());
std::string random_string1 = base::RandBytesAsString(1023);
EXPECT_EQ(1023u, random_string1.size());
std::string random_string2 = base::RandBytesAsString(4097);
EXPECT_EQ(4097u, random_string2.size());
}
TEST(RandUtilTest, DISABLED_RandBytesPerf) {
const int kTestIterations = 10;
const size_t kTestBufferSize = 1 * 1024 * 1024;
std::unique_ptr<uint8_t[]> buffer(new uint8_t[kTestBufferSize]);
const base::TimeTicks now = base::TimeTicks::Now();
for (int i = 0; i < kTestIterations; ++i)
base::RandBytes(buffer.get(), kTestBufferSize);
const base::TimeTicks end = base::TimeTicks::Now();
LOG(INFO) << "RandBytes(" << kTestBufferSize
<< ") took: " << (end - now).InMicroseconds() << "µs";
}
TEST(RandUtilTest, InsecureRandomGeneratorProducesBothValuesOfAllBits) {
uint64_t kAllZeros = 0ULL;
uint64_t kAllOnes = ~kAllZeros;
uint64_t found_ones = kAllZeros;
uint64_t found_zeros = kAllOnes;
InsecureRandomGenerator generator;
for (size_t i = 0; i < 1000; ++i) {
uint64_t value = generator.RandUint64();
found_ones |= value;
found_zeros &= value;
if (found_zeros == kAllZeros && found_ones == kAllOnes)
return;
}
FAIL() << "Didn't achieve all bit values in maximum number of tries.";
}
namespace {
constexpr double kXp1Percent = -2.33;
constexpr double kXp99Percent = 2.33;
double ChiSquaredCriticalValue(double nu, double x_p) {
return nu + sqrt(2. * nu) * x_p + 2. / 3. * (x_p * x_p) - 2. / 3.;
}
int ExtractBits(uint64_t value, int from_bit, int num_bits) {
return (value >> from_bit) & ((1 << num_bits) - 1);
}
bool ChiSquaredTest(InsecureRandomGenerator& gen,
size_t n,
int from_bit,
int num_bits) {
const int range = 1 << num_bits;
CHECK_EQ(static_cast<int>(n % range), 0) << "Makes computations simpler";
std::vector<size_t> samples(range, 0);
for (size_t i = 0; i < n; i++) {
int sample = ExtractBits(gen.RandUint64(), from_bit, num_bits);
samples[sample] += 1;
}
double chi_squared = 0.;
double expected_count = n / range;
for (size_t sample_count : samples) {
double deviation = sample_count - expected_count;
chi_squared += (deviation * deviation) / expected_count;
}
return chi_squared > ChiSquaredCriticalValue(range - 1, kXp1Percent) &&
chi_squared < ChiSquaredCriticalValue(range - 1, kXp99Percent);
}
}
TEST(RandUtilTest, InsecureRandomGeneratorChiSquared) {
constexpr int kIterations = 50;
for (int start_bit : {1, 2, 3, 8, 12, 20, 32, 48, 54}) {
int pass_count = 0;
for (int i = 0; i < kIterations; i++) {
size_t samples = 1 << 16;
InsecureRandomGenerator gen;
gen.ReseedForTesting(kIterations + 1);
bool pass = ChiSquaredTest(gen, samples, start_bit, 8);
pass_count += pass;
}
int expected_pass_count = (kIterations * 98) / 100;
EXPECT_GE(pass_count, expected_pass_count - ((kIterations * 2) / 100))
<< "For start_bit = " << start_bit;
}
}
TEST(RandUtilTest, InsecureRandomGeneratorRandDouble) {
InsecureRandomGenerator gen;
for (int i = 0; i < 1000; i++) {
volatile double x = gen.RandDouble();
EXPECT_GE(x, 0.);
EXPECT_LT(x, 1.);
}
}
}