Skip to content

Commit

Permalink
STYLE: Remove casts from MersenneTwisterRandomVariateGenerator::hash
Browse files Browse the repository at this point in the history
Moved duplicate code into a lambda, replacing two unsafe C-style
pointer casts by a reinterpret_cast, and removing two unnecessary
`static_cast<unsigned int>` casts.
  • Loading branch information
N-Dekker authored and dzenanz committed Apr 13, 2022
1 parent 2e481c4 commit 59b001f
Showing 1 changed file with 13 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,31 +89,27 @@ MersenneTwisterRandomVariateGenerator::MersenneTwisterRandomVariateGenerator()
MersenneTwisterRandomVariateGenerator::~MersenneTwisterRandomVariateGenerator() = default;

MersenneTwisterRandomVariateGenerator::IntegerType
MersenneTwisterRandomVariateGenerator ::hash(time_t t, clock_t c)
MersenneTwisterRandomVariateGenerator::hash(const time_t t, const clock_t c)
{
itkInitGlobalsMacro(PimplGlobals);
// Get an IntegerType from t and c
// Better than IntegerType(x) in case x is floating point in [0,1]
// Based on code by Lawrence Kirby: fred at genesis dot demon dot co dot uk

IntegerType h1 = 0;
auto * p = (unsigned char *)&t;
const auto convert = [](const auto arg) {
IntegerType h{ 0 };
const auto * const p = reinterpret_cast<const unsigned char *>(&arg);

const auto sizeOfT = static_cast<unsigned int>(sizeof(t));
for (unsigned int i = 0; i < sizeOfT; ++i)
{
h1 *= UCHAR_MAX + 2U;
h1 += p[i];
}
IntegerType h2 = 0;
p = (unsigned char *)&c;
for (size_t i = 0; i < sizeof(arg); ++i)
{
h *= UCHAR_MAX + 2U;
h += p[i];
}
return h;
};

const auto sizeOfC = static_cast<unsigned int>(sizeof(c));
for (unsigned int j = 0; j < sizeOfC; ++j)
{
h2 *= UCHAR_MAX + 2U;
h2 += p[j];
}
const IntegerType h1 = convert(t);
const IntegerType h2 = convert(c);
return (h1 + m_PimplGlobals->m_StaticDiffer++) ^ h2;
}

Expand Down

0 comments on commit 59b001f

Please sign in to comment.