mirror of
https://github.com/MaSzyna-EU07/maszyna.git
synced 2026-12-02 00:22:42 +01:00
72 lines
2.3 KiB
C++
72 lines
2.3 KiB
C++
#include "stdafx.h"
|
|
|
|
#include "doctest.h"
|
|
|
|
#include "utilities/utilities.h"
|
|
#include "utilities/lazyrandom.h"
|
|
|
|
#include <random>
|
|
#include <vector>
|
|
|
|
namespace
|
|
{
|
|
// what Random() draws in the calling thread with the engine set before, n times
|
|
std::vector<double> draws(int const Count)
|
|
{
|
|
std::vector<double> result;
|
|
for (int i = 0; i < Count; ++i)
|
|
result.push_back(Random(0.0, 1.0));
|
|
return result;
|
|
}
|
|
} // namespace
|
|
|
|
TEST_CASE("random engine: the lazily seeded engine draws as one seeded up front from the same numbers")
|
|
{
|
|
std::pair<std::uint32_t, std::uint32_t> const seeds[]{{0u, 0u}, {12345u, 7u}, {0xFFFFFFFFu, 4096u}};
|
|
for (auto const &seed : seeds)
|
|
{
|
|
CAPTURE(seed.first);
|
|
CAPTURE(seed.second);
|
|
std::seed_seq eagerseed{seed.first, seed.second};
|
|
std::mt19937 eager{eagerseed}; // NOSONAR: randomness of the simulation, not of anything security-relevant
|
|
set_thread_random_engine(&eager);
|
|
auto const expected{draws(100)};
|
|
set_thread_random_engine(nullptr);
|
|
|
|
lazy_random_engine lazy;
|
|
lazy.seed[0] = seed.first;
|
|
lazy.seed[1] = seed.second;
|
|
set_thread_lazy_random_engine(&lazy);
|
|
auto const actual{draws(100)};
|
|
set_thread_lazy_random_engine(nullptr);
|
|
|
|
CHECK(actual == expected);
|
|
}
|
|
}
|
|
|
|
TEST_CASE("random engine: the lazy engine is seeded at the first draw only, and stands ahead of the thread's engine")
|
|
{
|
|
std::mt19937 threadengine{1u}; // NOSONAR: randomness of the simulation, not of anything security-relevant
|
|
auto const untouched{threadengine}; // NOSONAR: randomness of the simulation, not of anything security-relevant
|
|
set_thread_random_engine(&threadengine);
|
|
|
|
lazy_random_engine lazy;
|
|
lazy.seed[0] = 3u;
|
|
lazy.seed[1] = 5u;
|
|
set_thread_lazy_random_engine(&lazy);
|
|
CHECK(thread_lazy_random_engine() == &lazy);
|
|
// a group that draws nothing never seeds it
|
|
CHECK_FALSE(lazy.engine.has_value());
|
|
static_cast<void>(Random(0.0, 1.0));
|
|
CHECK(lazy.engine.has_value());
|
|
// the draw came from the lazy engine, the one of the thread is left as it was
|
|
CHECK(threadengine == untouched);
|
|
|
|
set_thread_lazy_random_engine(nullptr);
|
|
CHECK(thread_lazy_random_engine() == nullptr);
|
|
// without the lazy engine the draws come from the thread's engine again
|
|
static_cast<void>(Random(0.0, 1.0));
|
|
CHECK_FALSE(threadengine == untouched);
|
|
set_thread_random_engine(nullptr);
|
|
}
|