diff --git a/include/mcl/fp.hpp b/include/mcl/fp.hpp index 706d9fa..f41d4f8 100644 --- a/include/mcl/fp.hpp +++ b/include/mcl/fp.hpp @@ -227,7 +227,7 @@ public: } else { clear(); if (x) { - int64_t y = x < 0 ? -x : x; + uint64_t y = fp::abs_(x); if (sizeof(Unit) == 8) { v_[0] = y; } else { diff --git a/include/mcl/util.hpp b/include/mcl/util.hpp index 8915c88..b35801e 100644 --- a/include/mcl/util.hpp +++ b/include/mcl/util.hpp @@ -17,8 +17,21 @@ namespace mcl { namespace fp { // some environments do not have utility -template -T abs_(T x) { return x < 0 ? -x : x; } +inline uint32_t abs_(int32_t x) +{ + if (x >= 0) return uint32_t(x); + // avoid undefined behavior + if (x == -2147483647 - 1) return 2147483648u; + return uint32_t(-x); +} + +inline uint64_t abs_(int64_t x) +{ + if (x >= 0) return uint64_t(x); + // avoid undefined behavior + if (x == -9223372036854775807ll - 1) return 9223372036854775808ull; + return uint64_t(-x); +} template T min_(T x, T y) { return x < y ? x : y; }