Skip to content

Commit fa0e5b8

Browse files
author
MarcoFalke
committed
Add templated GetRandomDuration<>
1 parent af2ec6b commit fa0e5b8

File tree

2 files changed

+16
-16
lines changed

2 files changed

+16
-16
lines changed

src/random.cpp

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,14 @@
1414
#include <wincrypt.h>
1515
#endif
1616
#include <logging.h> // for LogPrintf()
17+
#include <randomenv.h>
18+
#include <support/allocators/secure.h>
1719
#include <sync.h> // for Mutex
1820
#include <util/time.h> // for GetTimeMicros()
1921

2022
#include <stdlib.h>
2123
#include <thread>
2224

23-
#include <randomenv.h>
24-
25-
#include <support/allocators/secure.h>
26-
2725
#ifndef WIN32
2826
#include <fcntl.h>
2927
#include <sys/time.h>
@@ -587,16 +585,6 @@ uint64_t GetRand(uint64_t nMax) noexcept
587585
return FastRandomContext(g_mock_deterministic_tests).randrange(nMax);
588586
}
589587

590-
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept
591-
{
592-
return std::chrono::microseconds{GetRand(duration_max.count())};
593-
}
594-
595-
std::chrono::milliseconds GetRandMillis(std::chrono::milliseconds duration_max) noexcept
596-
{
597-
return std::chrono::milliseconds{GetRand(duration_max.count())};
598-
}
599-
600588
int GetRandInt(int nMax) noexcept
601589
{
602590
return GetRand(nMax);

src/random.h

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,21 @@
6767
* Thread-safe.
6868
*/
6969
void GetRandBytes(unsigned char* buf, int num) noexcept;
70+
/** Generate a uniform random integer in the range [0..range). Precondition: range > 0 */
7071
uint64_t GetRand(uint64_t nMax) noexcept;
71-
std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept;
72-
std::chrono::milliseconds GetRandMillis(std::chrono::milliseconds duration_max) noexcept;
72+
/** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */
73+
template <typename D>
74+
D GetRandomDuration(typename std::common_type<D>::type max) noexcept
75+
// Having the compiler infer the template argument from the function argument
76+
// is dangerous, because the desired return value generally has a different
77+
// type than the function argument. So std::common_type is used to force the
78+
// call site to specify the type of the return value.
79+
{
80+
assert(max.count() > 0);
81+
return D{GetRand(max.count())};
82+
};
83+
constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>;
84+
constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>;
7385
int GetRandInt(int nMax) noexcept;
7486
uint256 GetRandHash() noexcept;
7587

0 commit comments

Comments
 (0)