Merge bitcoin/bitcoin#24925: refactor: make GetRand a template, remove GetRandInt

ab1ea29ba1 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 ab1ea29ba1

Tree-SHA512: db5082a0e21783389f1be898ae73e097b31ab48cab1a2c0e29348a4adeb545d4098193aa72a547c6baa6e8205699aafec38d6a27b3d65522fb3246f91b4daae9
This commit is contained in:
MacroFake
2022-05-12 08:57:12 +02:00
12 changed files with 34 additions and 31 deletions

View File

@@ -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;
/**