Skip to content

Commit

Permalink
Add templated GetRandomDuration<>
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoFalke committed Apr 30, 2020
1 parent af2ec6b commit fa0e5b8
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 16 deletions.
16 changes: 2 additions & 14 deletions src/random.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,14 @@
#include <wincrypt.h>
#endif
#include <logging.h> // for LogPrintf()
#include <randomenv.h>
#include <support/allocators/secure.h>
#include <sync.h> // for Mutex
#include <util/time.h> // for GetTimeMicros()

#include <stdlib.h>
#include <thread>

#include <randomenv.h>

#include <support/allocators/secure.h>

#ifndef WIN32
#include <fcntl.h>
#include <sys/time.h>
Expand Down Expand Up @@ -587,16 +585,6 @@ uint64_t GetRand(uint64_t nMax) noexcept
return FastRandomContext(g_mock_deterministic_tests).randrange(nMax);
}

std::chrono::microseconds GetRandMicros(std::chrono::microseconds duration_max) noexcept
{
return std::chrono::microseconds{GetRand(duration_max.count())};
}

std::chrono::milliseconds GetRandMillis(std::chrono::milliseconds duration_max) noexcept
{
return std::chrono::milliseconds{GetRand(duration_max.count())};
}

int GetRandInt(int nMax) noexcept
{
return GetRand(nMax);
Expand Down
16 changes: 14 additions & 2 deletions src/random.h
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down

0 comments on commit fa0e5b8

Please sign in to comment.