Page MenuHomePhabricator

Add templated GetRandomDuration<>
ClosedPublic

Authored by PiRK on Feb 1 2021, 09:11.

Details

Reviewers
Fabien
Group Reviewers
Restricted Project
Commits
rABC6731f60abe1a: Add templated GetRandomDuration<>
Summary

instead of implementing the function for each duration type by hand, replace it with a templated version that is safe to use.

A naive implementation of this template is dangerous, because the call site might accidentally omit the template parameter:

template <typename D>
D GetRandDur(const D& duration_max)
{
    return D{GetRand(duration_max.count())};
}

BOOST_AUTO_TEST_CASE(util_time_GetRandTime)
{
   std::chrono::seconds rand_hour = GetRandDur(std::chrono::hours{1});
   // Want seconds to be in range [0..1hour), but always get zero :((((
   BOOST_CHECK_EQUAL(rand_hour.count(), 0);
}

This is a backport of Core PR18781

Test Plan

ninja all check-all