Skip to content

Commit fa4fb8d

Browse files
author
MarcoFalke
committed
random: Add FastRandomContext::rand_uniform_delay
1 parent faa5c62 commit fa4fb8d

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

src/random.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,17 @@ class FastRandomContext
223223
/** Generate a random boolean. */
224224
bool randbool() noexcept { return randbits(1); }
225225

226+
/** Return the time point advanced by a uniform random duration. */
227+
template <typename Tp>
228+
Tp rand_uniform_delay(const Tp& time, typename Tp::duration range)
229+
{
230+
using Dur = typename Tp::duration;
231+
Dur dur{range.count() > 0 ? /* interval [0..range) */ Dur{randrange(range.count())} :
232+
range.count() < 0 ? /* interval (range..0] */ -Dur{randrange(-range.count())} :
233+
/* interval [0..0] */ Dur{0}};
234+
return time + dur;
235+
}
236+
226237
// Compatibility with the C++11 UniformRandomBitGenerator concept
227238
typedef uint64_t result_type;
228239
static constexpr uint64_t min() { return 0; }

src/test/random_tests.cpp

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,16 @@ BOOST_AUTO_TEST_CASE(fastrandom_tests)
3131
BOOST_CHECK_EQUAL(GetRandMicros(std::chrono::hours{1}).count(), 2917185654);
3232
BOOST_CHECK_EQUAL(GetRandMillis(std::chrono::hours{1}).count(), 2144374);
3333
}
34+
{
35+
constexpr SteadySeconds time_point{1s};
36+
FastRandomContext ctx{true};
37+
BOOST_CHECK_EQUAL(7, ctx.rand_uniform_delay(time_point, 9s).time_since_epoch().count());
38+
BOOST_CHECK_EQUAL(-6, ctx.rand_uniform_delay(time_point, -9s).time_since_epoch().count());
39+
BOOST_CHECK_EQUAL(1, ctx.rand_uniform_delay(time_point, 0s).time_since_epoch().count());
40+
BOOST_CHECK_EQUAL(1467825113502396065, ctx.rand_uniform_delay(time_point, 9223372036854775807s).time_since_epoch().count());
41+
BOOST_CHECK_EQUAL(-970181367944767837, ctx.rand_uniform_delay(time_point, -9223372036854775807s).time_since_epoch().count());
42+
BOOST_CHECK_EQUAL(24761, ctx.rand_uniform_delay(time_point, 9h).time_since_epoch().count());
43+
}
3444
BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());
3545
BOOST_CHECK_EQUAL(ctx1.rand32(), ctx2.rand32());
3646
BOOST_CHECK_EQUAL(ctx1.rand64(), ctx2.rand64());

0 commit comments

Comments
 (0)