My Project 3.7.1
C++ Distributed Hash Table
Loading...
Searching...
No Matches
rng.h
1// Copyright (c) 2014-2026 Savoir-faire Linux Inc.
2// SPDX-License-Identifier: MIT
3#pragma once
4
5#include <random>
6#include <algorithm>
7#include <functional>
8#include <thread>
9#include <stdexcept>
10
11namespace dht {
12namespace crypto {
13
17template<class T = std::mt19937, std::size_t N = T::state_size + 1>
18auto
19getSeededRandomEngine() -> typename std::enable_if<!!N, T>::type
20{
21 std::array<typename T::result_type, N> random_data;
22 constexpr auto gen = [](std::random_device& source) -> typename T::result_type {
23 for (unsigned j = 0; j < 64; j++) {
24 try {
25 return source();
26 } catch (...) {
27 std::this_thread::sleep_for(std::chrono::microseconds(500));
28 }
29 }
30 throw std::runtime_error("Can't generate random number");
31 };
32 for (unsigned i = 0; i < 8; i++) {
33 try {
34 std::random_device source;
35 for (auto& r : random_data)
36 r = gen(source);
37 std::seed_seq seed((std::seed_seq::result_type*) random_data.data(),
38 (std::seed_seq::result_type*) (random_data.data() + random_data.size()));
39 return T(seed);
40 } catch (...) {
41 std::this_thread::sleep_for(std::chrono::microseconds(500));
42 }
43 }
44 throw std::runtime_error("Can't seed random seed");
45}
46
50template<class T = std::mt19937, std::size_t N = T::state_size + 1>
51auto
52getDerivedRandomEngine(T& source) -> typename std::enable_if<!!N, T>::type
53{
54 std::array<typename T::result_type, N> random_data;
55 std::generate(random_data.begin(), random_data.end(), std::ref(source));
56 std::seed_seq seed((std::seed_seq::result_type*) random_data.data(),
57 (std::seed_seq::result_type*) (random_data.data() + random_data.size()));
58 return T(seed);
59}
60
61} // namespace crypto
62} // namespace dht
auto getDerivedRandomEngine(T &source) -> typename std::enable_if<!!N, T >::type
Definition rng.h:52
auto getSeededRandomEngine() -> typename std::enable_if<!!N, T >::type
Definition rng.h:19