#include "test/fuzzers/random_generator.h"
#include <algorithm>
#include <array>
#include <cassert>
namespace spvtools {
namespace fuzzers {
namespace {
template <typename I>
I RandomUInt(std::mt19937_64* engine, I lower, I upper) {
assert(lower < upper && "|lower| must be stictly less than |upper|");
return std::uniform_int_distribution<I>(lower, upper - 1)(*engine);
}
template <int SIZE_OF_SIZE_T>
struct HashCombineOffset {};
template <>
struct HashCombineOffset<4> {
static constexpr inline uint32_t value() {
return 0x9e3779b9;
}
};
template <>
struct HashCombineOffset<8> {
static constexpr inline uint64_t value() {
return 0x9e3779b97f4a7c16;
}
};
template <typename T>
void HashCombine(size_t* hash, const T& value) {
constexpr size_t offset = HashCombineOffset<sizeof(size_t)>::value();
*hash ^= std::hash<T>()(value) + offset + (*hash << 6) + (*hash >> 2);
}
size_t HashBuffer(const uint8_t* data, const size_t size) {
size_t hash =
static_cast<size_t>(0xCA8945571519E991);
HashCombine(&hash, size);
for (size_t i = 0; i < size; i++) {
HashCombine(&hash, data[i]);
}
return hash;
}
}
RandomGenerator::RandomGenerator(uint64_t seed) : engine_(seed) {}
RandomGenerator::RandomGenerator(const uint8_t* data, size_t size) {
RandomGenerator(RandomGenerator::CalculateSeed(data, size));
}
spv_target_env RandomGenerator::GetTargetEnv() {
spv_target_env result;
do {
result = static_cast<spv_target_env>(
RandomUInt(&engine_, 0u, static_cast<unsigned int>(SPV_ENV_MAX)));
} while (!spvIsValidEnv(result));
return result;
}
uint32_t RandomGenerator::GetUInt32(uint32_t lower, uint32_t upper) {
return RandomUInt(&engine_, lower, upper);
}
uint32_t RandomGenerator::GetUInt32(uint32_t bound) {
assert(bound > 0 && "|bound| must be greater than 0");
return RandomUInt(&engine_, 0u, bound);
}
uint64_t RandomGenerator::CalculateSeed(const uint8_t* data, size_t size) {
assert(data != nullptr && "|data| must be !nullptr");
static const int64_t kHashDesiredLeadingSkipBytes = 5;
static const int64_t kHashDesiredMinBytes = 4;
static const int64_t kHashDesiredMaxBytes = 32;
int64_t size_i64 = static_cast<int64_t>(size);
int64_t hash_begin_i64 =
std::min(kHashDesiredLeadingSkipBytes,
std::max<int64_t>(size_i64 - kHashDesiredMinBytes, 0));
int64_t hash_end_i64 =
std::min(hash_begin_i64 + kHashDesiredMaxBytes, size_i64);
size_t hash_begin = static_cast<size_t>(hash_begin_i64);
size_t hash_size = static_cast<size_t>(hash_end_i64) - hash_begin;
return HashBuffer(data + hash_begin, hash_size);
}
}
}