Skip to content

Commit

Permalink
fixed a bug where -0.5 / -epsilon triggers UB
Browse files Browse the repository at this point in the history
  • Loading branch information
MichaelSuen-thePointer committed May 10, 2024
1 parent 9810a17 commit 5f57cf4
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 2 deletions.
6 changes: 4 additions & 2 deletions include/fixmath/fixed_impl.inl
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,10 @@ constexpr fixed<policy> operator/(fixed<policy> a, fixed<policy> b) {
int64_t rem = 0;
if constexpr (sizeof(raw_t) == 8) {
// use extended int128 division
raw_t _check_bits = a.raw() >> (fixed::ALL_BITS - fixed::FRACTION_BITS - 1); // check for simple division
if (FIXMATH_LIKELY(_check_bits == 0 || _check_bits == -1)) {
raw_t _check_bits = a.raw() >> (fixed::ALL_BITS - fixed::FRACTION_BITS - 1);
raw_t _remain_bits = a.raw() & (fixed::FRACTION_MASK >> 1);
if (FIXMATH_LIKELY(_check_bits == 0 || (_check_bits == -1 && _remain_bits))) {
// check for simplified division
qlo = a.raw() * fixed::RATIO;
if constexpr (policy::rounding) {
rem = qlo % b.raw();
Expand Down
1 change: 1 addition & 0 deletions tests/unit_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ TEST(FIXMATH, DIV) {
CHECK_FIX_DIV(ABSERROR, -ABSERROR);
CHECK_FIX_DIV(-1.234, -4.321);
CHECK_FIX_DIV(-1.234, 4.321);
EXPECT_EQ(-Fix32(0.5) / -Fix32::epsilon(), Fix32::max_sat());
EXPECT_EQ(1 / Fix32::epsilon(), Fix32::max_sat());
EXPECT_EQ(1 / -Fix32::epsilon(), Fix32::min_sat());
EXPECT_EQ(Fix32::max_fix() / Fix32(0.5), Fix32::max_sat());
Expand Down

0 comments on commit 5f57cf4

Please sign in to comment.