From: Kefu Chai Date: Sat, 11 Jan 2020 14:41:59 +0000 (+0800) Subject: common/strtol.cc: refactor strict_si_cast() to silence warnings X-Git-Tag: v15.1.0~234^2 X-Git-Url: http://git-server-git.apps.pok.os.sepia.ceph.com/?a=commitdiff_plain;h=refs%2Fpull%2F32605%2Fhead;p=ceph.git common/strtol.cc: refactor strict_si_cast() to silence warnings to silence warnings like ../src/common/strtol.cc:286:7: warning: implicit conversion from 'promoted_t' (aka 'long long') to 'double' changes value from 9223372036854775807 to 9223372036854775808 [-Wimplicit-int-float-conversion] static_cast(std::numeric_limits::max()) / pow (10, m)) { ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~ ../src/common/strtol.cc:294:15: note: in instantiation of function template specialization 'strict_si_cast' requested here template long strict_si_cast(std::string_view str, std::string *err); ^ Signed-off-by: Kefu Chai --- diff --git a/src/common/strtol.cc b/src/common/strtol.cc index 9b437596941f..c39363c88c5f 100644 --- a/src/common/strtol.cc +++ b/src/common/strtol.cc @@ -14,6 +14,7 @@ #include "strtol.h" +#include #include #include #include @@ -277,17 +278,17 @@ T strict_si_cast(std::string_view str, std::string *err) return 0; } using promoted_t = typename std::common_type::type; - if (static_cast(ll) < - static_cast(std::numeric_limits::min()) / pow (10, m)) { - *err = "strict_sistrtoll: value seems to be too small"; - return 0; - } - if (static_cast(ll) > - static_cast(std::numeric_limits::max()) / pow (10, m)) { - *err = "strict_sistrtoll: value seems to be too large"; + auto v = static_cast(ll); + auto coefficient = static_cast(powl(10, m)); + if (v != std::clamp(v, + (static_cast(std::numeric_limits::min()) / + coefficient), + (static_cast(std::numeric_limits::max()) / + coefficient))) { + *err = "strict_sistrtoll: value out of range"; return 0; } - return (ll * pow (10, m)); + return v * coefficient; } template int strict_si_cast(std::string_view str, std::string *err);