diff options
author | MarcoFalke <falke.marco@gmail.com> | 2020-04-27 09:25:05 -0400 |
---|---|---|
committer | MarcoFalke <falke.marco@gmail.com> | 2020-04-30 09:19:14 -0400 |
commit | fa0e5b89cf742df56c6c8f49fe9b3c54d2970a66 (patch) | |
tree | 510c91dbf42bb275803df45311ed19f5e04d861a /src/random.h | |
parent | af2ec6b03745cf408f169cfbd74e3380a69975e0 (diff) |
Add templated GetRandomDuration<>
Diffstat (limited to 'src/random.h')
-rw-r--r-- | src/random.h | 16 |
1 files changed, 14 insertions, 2 deletions
diff --git a/src/random.h b/src/random.h index 690125079b..0c6dc24983 100644 --- a/src/random.h +++ b/src/random.h @@ -67,9 +67,21 @@ * Thread-safe. */ void GetRandBytes(unsigned char* buf, int num) noexcept; +/** Generate a uniform random integer in the range [0..range). Precondition: range > 0 */ uint64_t GetRand(uint64_t nMax) noexcept; -std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept; -std::chrono::milliseconds GetRandMillis(std::chrono::milliseconds duration_max) noexcept; +/** Generate a uniform random duration in the range [0..max). Precondition: max.count() > 0 */ +template <typename D> +D GetRandomDuration(typename std::common_type<D>::type max) noexcept +// Having the compiler infer the template argument from the function argument +// is dangerous, because the desired return value generally has a different +// type than the function argument. So std::common_type is used to force the +// call site to specify the type of the return value. +{ + assert(max.count() > 0); + return D{GetRand(max.count())}; +}; +constexpr auto GetRandMicros = GetRandomDuration<std::chrono::microseconds>; +constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>; int GetRandInt(int nMax) noexcept; uint256 GetRandHash() noexcept; |