diff options
author | MacroFake <falke.marco@gmail.com> | 2022-05-12 08:57:12 +0200 |
---|---|---|
committer | MacroFake <falke.marco@gmail.com> | 2022-05-12 08:57:22 +0200 |
commit | a2a8e919ee07506083f45426874cd2edf82d9f9f (patch) | |
tree | fb1f82ca4b8660b3366bf80c16d0321ec4f4f07c /src/random.h | |
parent | 51527ec1ec4264f7e24ef548bb049db07a89fc7f (diff) | |
parent | ab1ea29ba1b8379a21fabd3dc859552c470a6421 (diff) | |
download | bitcoin-a2a8e919ee07506083f45426874cd2edf82d9f9f.tar.xz |
Merge bitcoin/bitcoin#24925: refactor: make GetRand a template, remove GetRandInt
ab1ea29ba1b8379a21fabd3dc859552c470a6421 refactor: make GetRand a template, remove GetRandInt (pasta)
Pull request description:
makes GetRand a template for which any integral type can be used, where the default behavior is to return a random integral up to the max of the integral unless a max is provided.
This simplifies a lot of code from GetRand(std::numeric_limits<uint64_t>::max() -> GetRand<uint64_t>()
ACKs for top commit:
laanwj:
Code review ACK ab1ea29ba1b8379a21fabd3dc859552c470a6421
Tree-SHA512: db5082a0e21783389f1be898ae73e097b31ab48cab1a2c0e29348a4adeb545d4098193aa72a547c6baa6e8205699aafec38d6a27b3d65522fb3246f91b4daae9
Diffstat (limited to 'src/random.h')
-rw-r--r-- | src/random.h | 13 |
1 files changed, 11 insertions, 2 deletions
diff --git a/src/random.h b/src/random.h index 4679a2b40c..b92c29f0be 100644 --- a/src/random.h +++ b/src/random.h @@ -69,7 +69,17 @@ */ void GetRandBytes(Span<unsigned char> bytes) noexcept; /** Generate a uniform random integer in the range [0..range). Precondition: range > 0 */ -uint64_t GetRand(uint64_t nMax) noexcept; +uint64_t GetRandInternal(uint64_t nMax) noexcept; +/** Generate a uniform random integer of type T in the range [0..nMax) + * nMax defaults to std::numeric_limits<T>::max() + * Precondition: nMax > 0, T is an integral type, no larger than uint64_t + */ +template<typename T> +T GetRand(T nMax=std::numeric_limits<T>::max()) noexcept { + static_assert(std::is_integral<T>(), "T must be integral"); + static_assert(std::numeric_limits<T>::max() <= std::numeric_limits<uint64_t>::max(), "GetRand only supports up to uint64_t"); + return T(GetRandInternal(nMax)); +} /** 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 @@ -95,7 +105,6 @@ constexpr auto GetRandMillis = GetRandomDuration<std::chrono::milliseconds>; * */ std::chrono::microseconds GetExponentialRand(std::chrono::microseconds now, std::chrono::seconds average_interval); -int GetRandInt(int nMax) noexcept; uint256 GetRandHash() noexcept; /** |