Clio develop
The XRP Ledger API server.
Loading...
Searching...
No Matches
Random.hpp
1//------------------------------------------------------------------------------
2/*
3 This file is part of clio: https://github.com/XRPLF/clio
4 Copyright (c) 2023, the clio developers.
5
6 Permission to use, copy, modify, and distribute this software for any
7 purpose with or without fee is hereby granted, provided that the above
8 copyright notice and this permission notice appear in all copies.
9
10 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17*/
18//==============================================================================
19#pragma once
20
21#include "util/Assert.hpp"
22
23#include <cstddef>
24#include <random>
25
26namespace util {
27
32public:
33 virtual ~RandomGeneratorInterface() = default;
34
35 using SeedType = typename std::mt19937_64::result_type;
36
44 [[nodiscard]]
45 virtual size_t
46 uniform(size_t min, size_t max) = 0;
47
53 virtual void
54 setSeed(SeedType seed) = 0;
55};
56
61public:
63
71 [[nodiscard]]
72 size_t
73 uniform(size_t min, size_t max) override;
74
83 template <typename T>
84 [[nodiscard]]
85 T
86 uniformImpl(T min, T max)
87 {
88 ASSERT(min <= max, "Min cannot be greater than max. min: {}, max: {}", min, max);
89 if constexpr (std::is_floating_point_v<T>) {
90 std::uniform_real_distribution<T> distribution(min, max);
91 return distribution(generator_);
92 }
93 std::uniform_int_distribution<T> distribution(min, max);
94 return distribution(generator_);
95 }
96
102 void
103 setSeed(SeedType seed) override;
104
105private:
106 std::mt19937_64 generator_;
107};
108
109} // namespace util
Mersenne Twister random number generator.
Definition Random.hpp:60
T uniformImpl(T min, T max)
Generate a random number between min and max.
Definition Random.hpp:86
void setSeed(SeedType seed) override
Set the seed for the random number generator.
Definition Random.cpp:39
size_t uniform(size_t min, size_t max) override
Generate a random number between min and max.
Definition Random.cpp:33
Random number generator interface.
Definition Random.hpp:31
virtual size_t uniform(size_t min, size_t max)=0
Generate a random number between min and max.
virtual void setSeed(SeedType seed)=0
Set the seed for the random number generator.
This namespace contains various utilities.
Definition AccountUtils.hpp:30