|
@@ -21,6 +21,9 @@
|
|
|
|
|
|
#include "common.hpp"
|
|
|
|
|
|
+#include <climits>
|
|
|
+#include <limits>
|
|
|
+#include <random>
|
|
|
#include <vector>
|
|
|
|
|
|
namespace rtc::impl::utils {
|
|
@@ -36,6 +39,36 @@ string url_decode(const string &str);
|
|
|
// See https://www.rfc-editor.org/rfc/rfc4648.html#section-4
|
|
|
string base64_encode(const binary &data);
|
|
|
|
|
|
-} // namespace rtc::impl
|
|
|
+// Return a random seed sequence
|
|
|
+std::seed_seq random_seed();
|
|
|
+
|
|
|
+template <typename Generator, typename Result = typename Generator::result_type>
|
|
|
+struct random_engine_wrapper {
|
|
|
+ Generator &engine;
|
|
|
+ using result_type = Result;
|
|
|
+ static constexpr result_type min() { return static_cast<Result>(Generator::min()); }
|
|
|
+ static constexpr result_type max() { return static_cast<Result>(Generator::max()); }
|
|
|
+ inline result_type operator()() { return static_cast<Result>(engine()); }
|
|
|
+ inline void discard(unsigned long long z) { engine.discard(z); }
|
|
|
+};
|
|
|
+
|
|
|
+// Return a wrapped thread-local seeded random number generator
|
|
|
+template <typename Generator = std::mt19937, typename Result = typename Generator::result_type>
|
|
|
+auto random_engine() {
|
|
|
+ static thread_local std::seed_seq seed = random_seed();
|
|
|
+ static thread_local Generator engine{seed};
|
|
|
+ return random_engine_wrapper<Generator, Result>{engine};
|
|
|
+}
|
|
|
+
|
|
|
+// Return a wrapped thread-local seeded random bytes generator
|
|
|
+template <typename Generator = std::mt19937> auto random_bytes_engine() {
|
|
|
+ using char_independent_bits_engine =
|
|
|
+ std::independent_bits_engine<Generator, CHAR_BIT, unsigned short>;
|
|
|
+ static_assert(char_independent_bits_engine::min() == std::numeric_limits<uint8_t>::min());
|
|
|
+ static_assert(char_independent_bits_engine::max() == std::numeric_limits<uint8_t>::max());
|
|
|
+ return random_engine<char_independent_bits_engine, uint8_t>();
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace rtc::impl::utils
|
|
|
|
|
|
#endif
|