]> git-server-git.apps.pok.os.sepia.ceph.com Git - ceph.git/commitdiff
common/strtol.cc: refactor strict_si_cast() to silence warnings 32605/head
authorKefu Chai <kchai@redhat.com>
Sat, 11 Jan 2020 14:41:59 +0000 (22:41 +0800)
committerKefu Chai <kchai@redhat.com>
Sat, 11 Jan 2020 17:23:08 +0000 (01:23 +0800)
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<promoted_t>(std::numeric_limits<T>::max()) / pow (10, m)) {
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~
../src/common/strtol.cc:294:15: note: in instantiation of function template specialization 'strict_si_cast<long>' requested here
template long strict_si_cast<long>(std::string_view str, std::string *err);
              ^

Signed-off-by: Kefu Chai <kchai@redhat.com>
src/common/strtol.cc

index 9b437596941fb6b3ed5d93fd9b178a83ee2a8c87..c39363c88c5f7652cc70108d0b8d7ab4d1246711 100644 (file)
@@ -14,6 +14,7 @@
 
 #include "strtol.h"
 
+#include <algorithm>
 #include <climits>
 #include <limits>
 #include <cmath>
@@ -277,17 +278,17 @@ T strict_si_cast(std::string_view str, std::string *err)
     return 0;
   }
   using promoted_t = typename std::common_type<decltype(ll), T>::type;
-  if (static_cast<promoted_t>(ll) <
-      static_cast<promoted_t>(std::numeric_limits<T>::min()) / pow (10, m)) {
-    *err = "strict_sistrtoll: value seems to be too small";
-    return 0;
-  }
-  if (static_cast<promoted_t>(ll) >
-      static_cast<promoted_t>(std::numeric_limits<T>::max()) / pow (10, m)) {
-    *err = "strict_sistrtoll: value seems to be too large";
+  auto v = static_cast<promoted_t>(ll);
+  auto coefficient = static_cast<promoted_t>(powl(10, m));
+  if (v != std::clamp(v,
+                     (static_cast<promoted_t>(std::numeric_limits<T>::min()) /
+                      coefficient),
+                     (static_cast<promoted_t>(std::numeric_limits<T>::max()) /
+                      coefficient))) {
+    *err = "strict_sistrtoll: value out of range";
     return 0;
   }
-  return (ll * pow (10,  m));
+  return v * coefficient;
 }
 
 template int strict_si_cast<int>(std::string_view str, std::string *err);