HomePhabricator

Add templated GetRandomDuration<>

Description

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

Reviewers: #bitcoin_abc, Fabien

Reviewed By: #bitcoin_abc, Fabien

Differential Revision: https://reviews.bitcoinabc.org/D9118

Details

Provenance
MarcoFalke <falke.marco@gmail.com>Authored on Feb 1 2021, 10:44
PiRKCommitted on Feb 1 2021, 10:44
abc-botPushed on Feb 1 2021, 10:51
Reviewer
Restricted Project
Differential Revision
D9118: Add templated GetRandomDuration<>
Parents
rABCba0016fcc62e: [net processing] Only send a getheaders for one block in an INV
Branches
Unknown
Tags
Unknown