summaryrefslogtreecommitdiffhomepage
path: root/src/random.cpp
blob: 7888dbaa77dd5749679880f617b50240ef803de5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "random.hpp"
#include <random>
#include <limits>

namespace floormat {

static thread_local auto g = std::independent_bits_engine<decltype(std::ranlux48{}), 32, std::uint32_t>{std::ranlux48{}};

random_engine::~random_engine() = default;

struct random_engine_impl final : random_engine {
    std::size_t operator()() override;
    float operator()(float min, float max) override;
};

std::size_t random_engine_impl::operator()()
{
    if constexpr(sizeof(std::size_t) > sizeof(std::uint32_t))
    {
        constexpr auto N = (sizeof(std::size_t) + sizeof(std::uint32_t)-1) / sizeof(std::uint32_t);
        static_assert(N >= 1);
        union {
            std::size_t x;
            std::uint32_t a[N];
        } ret;
        for (auto i = 0_uz; i < N; i++)
            ret.a[i] = g();
        return ret.x;
    }
    else
        return (std::size_t)g();
}

float random_engine_impl::operator()(float min, float max)
{
    std::uniform_real_distribution<float> dist{min, max};
    return dist(g);
}

static random_engine& make_random_impl() {
    static random_engine_impl ret;
    return ret;
}
random_engine& random = make_random_impl();

} // namespace floormat