Skip to content

Commit

Permalink
Avoid producing invalid iterators in division loops
Browse files Browse the repository at this point in the history
This decouples loop end expression from the iterator decrement.
Previously, the `it--` produced invalid iterator to `u[-1]`
in the last iteration. It might have not been a big deal for execution
because the loop terminated and the iterator was unused,
but this was theoretical undefined behavior and constexpr context
didn't like it either.
  • Loading branch information
chfast committed Aug 6, 2024
1 parent 68a9dfa commit 5510a01
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions include/intx/intx.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1605,10 +1605,13 @@ inline uint64_t udivrem_by1(uint64_t u[], int len, uint64_t d) noexcept
u[len - 1] = 0; // Reset the word being a part of the result quotient.

auto it = &u[len - 2];
do
while (true)
{
std::tie(*it, rem) = udivrem_2by1({*it, rem}, d, reciprocal);
} while (it-- != &u[0]);
if (it == &u[0])
break;
--it;
}

return rem;
}
Expand All @@ -1629,10 +1632,13 @@ inline uint128 udivrem_by2(uint64_t u[], int len, uint128 d) noexcept
u[len - 1] = u[len - 2] = 0; // Reset these words being a part of the result quotient.

auto it = &u[len - 3];
do
while (true)
{
std::tie(*it, rem) = udivrem_3by2(rem[1], rem[0], *it, d, reciprocal);
} while (it-- != &u[0]);
if (it == &u[0])
break;
--it;
}

return rem;
}
Expand Down

0 comments on commit 5510a01

Please sign in to comment.