Skip to content

Commit

Permalink
Be more careful with as_int
Browse files Browse the repository at this point in the history
The old version worked fine, but it felt a little sketchy the way we
were handling implicit conversion from a wrapped-around unsigned to a
smaller signed type.  (Note that if the signed type had been bigger, we
would silently get the wrong answer!)
  • Loading branch information
chiphogg committed Nov 12, 2024
1 parent 5fb92d2 commit 2467986
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 1 deletion.
4 changes: 3 additions & 1 deletion au/code/au/utility/probable_primes.hh
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,9 @@ struct LucasDParameter {
uint64_t mag = 5u;
bool is_neg = false;

friend constexpr int as_int(const LucasDParameter &D) { return D.is_neg ? -D.mag : D.mag; }
friend constexpr int as_int(const LucasDParameter &D) {
return bool_sign(!D.is_neg) * static_cast<int>(D.mag);
}
friend constexpr void increment(LucasDParameter &D) {
D.mag += 2u;
D.is_neg = !D.is_neg;
Expand Down
5 changes: 5 additions & 0 deletions au/code/au/utility/test/probable_primes_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,11 @@ std::vector<uint64_t> strong_lucas_pseudoprimes() {
231703u, 243629u, 253259u, 268349u, 288919u, 313499u, 324899u};
}

TEST(LucasDParameter, CanConvertToInt) {
EXPECT_EQ(as_int(LucasDParameter{5u, false}), 5);
EXPECT_EQ(as_int(LucasDParameter{7u, true}), -7);
}

TEST(StrongLucas, AllPrimeNumbersAreProbablyPrime) {
const auto primes = first_n_primes<3'000u>();
for (const auto &p : primes) {
Expand Down

0 comments on commit 2467986

Please sign in to comment.