Skip to content

Commit fc43b3c

Browse files
committed
Add SafeAbs to avoid UB when casting INT_MIN.
1 parent 4a4380b commit fc43b3c

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/s2/util/math/exactfloat/exactfloat.cc

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,15 +64,17 @@ ExactFloat::ExactFloat(double v) {
6464
}
6565
}
6666

67+
// Calculates abs(v) without UB. SafeAbs(INT_MIN) == INT_MIN.
68+
// Generates the same code as std::abs().
69+
// https://godbolt.org/z/eT6KW1zGb
70+
int SafeAbs(int v) {
71+
return v < 0 ? -static_cast<unsigned>(v) : v;
72+
}
73+
6774
ExactFloat::ExactFloat(int v) {
6875
sign_ = (v >= 0) ? 1 : -1;
6976
bn_exp_ = 0;
70-
71-
if (v == std::numeric_limits<int>::min()) {
72-
bn_ = Bignum(static_cast<unsigned>(v));
73-
} else {
74-
bn_ = Bignum(abs(v));
75-
}
77+
bn_ = Bignum(static_cast<unsigned>(SafeAbs(v)));
7678
Canonicalize();
7779
}
7880

0 commit comments

Comments
 (0)