userver: userver/utils/rand.hpp Source File
Loading...
Searching...
No Matches
rand.hpp
Go to the documentation of this file.
1#pragma once
2
6
7#include <algorithm>
8#include <cstdint>
9#include <limits>
10#include <random>
11#include <utility>
12
15
16USERVER_NAMESPACE_BEGIN
17
18namespace utils {
19
23public:
24 using result_type = uint32_t;
25
26 virtual ~RandomBase() = default;
27
28 virtual result_type operator()() = 0;
29
30 static constexpr result_type min() { return std::mt19937::min(); }
31 static constexpr result_type max() { return std::mt19937::max(); }
32};
33
34namespace impl {
35
36std::seed_seq MakeSeedSeq();
37
38class RandomImpl final : public RandomBase {
39public:
40 RandomImpl();
41
42 result_type operator()() override { return gen_(); }
43
44private:
45 std::mt19937 gen_;
46};
47
48compiler::ThreadLocalScope<RandomImpl> UseLocalRandomImpl();
49
50} // namespace impl
51
76template <typename Func>
77decltype(auto) WithDefaultRandom(Func&& func) {
78 auto random = impl::UseLocalRandomImpl();
79 return std::forward<Func>(func)(static_cast<RandomBase&>(*random));
80}
81
85template <typename T>
86T RandRange(T from_inclusive, T to_exclusive) {
87 UINVARIANT(from_inclusive < to_exclusive, "attempt to get a random value in an incorrect range");
88 if constexpr (std::is_floating_point_v<T>) {
89 return utils::WithDefaultRandom(std::uniform_real_distribution<T>{from_inclusive, to_exclusive});
90 } else {
91 // 8-bit types are not allowed in uniform_int_distribution, so increase the
92 // T size.
93 return utils::WithDefaultRandom(std::uniform_int_distribution<std::common_type_t<T, unsigned short>>{
94 from_inclusive,
95 to_exclusive - 1
96 });
97 }
98}
99
102template <typename T>
103T RandRange(T to_exclusive) {
104 return utils::RandRange(T{0}, to_exclusive);
105}
106
110template <typename Container>
111void Shuffle(Container& container) {
112 utils::WithDefaultRandom([&container](RandomBase& rng) { std::ranges::shuffle(container, rng); });
113}
114
118std::uint32_t Rand();
119
120} // namespace utils
121
122USERVER_NAMESPACE_END