Index: base/safe_numerics.h |
diff --git a/base/safe_numerics.h b/base/safe_numerics.h |
new file mode 100644 |
index 0000000000000000000000000000000000000000..f2a099a60e6eabd6c64e1fa32d4cf2d698d5016d |
--- /dev/null |
+++ b/base/safe_numerics.h |
@@ -0,0 +1,57 @@ |
+// Copyright 2013 The Chromium Authors. All rights reserved. |
+// Use of this source code is governed by a BSD-style license that can be |
+// found in the LICENSE file. |
+ |
+#ifndef BASE_NUMERIC_CAST_H_ |
darin (slow to review)
2013/01/15 18:53:29
nit: fix include guard. or maybe the file name nu
jschuh
2013/01/15 19:07:32
This was my request. I want to put the safe_numeri
scottmg
2013/01/15 19:30:17
Justin wanted it called safe_numerics with the int
|
+#define BASE_NUMERIC_CAST_H_ |
+ |
+#include <limits> |
+ |
+#include "base/logging.h" |
+ |
+namespace base { |
+ |
+// numeric_cast<> is analogous to static_cast<> for numeric types, except that |
+// it CHECKs that the specified numeric conversion will not overflow or |
+// underflow. Floating point arguments are not currently allowed (this is |
+// COMPILE_ASSERTd), though this could be supported if necessary. |
+ |
+// The main test for whether the conversion will under or overflow. |
+template <class Dest, class Source> |
darin (slow to review)
2013/01/15 18:53:29
this feels like implementation detail. perhaps it
scottmg
2013/01/15 19:30:17
Done.
|
+inline bool IsNumericCastableTo(Source source) { |
darin (slow to review)
2013/01/15 18:53:29
nit: IsValidNumericCast?
scottmg
2013/01/15 19:30:17
Done.
|
+ typedef std::numeric_limits<Source> source_limits; |
darin (slow to review)
2013/01/15 18:53:29
nit: typedefs are usually MixedCase... SourceLimit
scottmg
2013/01/15 19:30:17
Done.
|
+ typedef std::numeric_limits<Dest> dest_limits; |
+ COMPILE_ASSERT(source_limits::is_specialized, argument_must_be_numeric); |
+ COMPILE_ASSERT(source_limits::is_integer, argument_must_be_integral); |
+ COMPILE_ASSERT(dest_limits::is_specialized, result_must_be_numeric); |
+ COMPILE_ASSERT(dest_limits::is_integer, result_must_be_integral); |
+ |
+ // Source and Dest are the same. |
+ if (dest_limits::digits == source_limits::digits && |
+ dest_limits::is_signed == source_limits::is_signed) |
+ return true; |
+ |
+ // Dest is wider, check for loss of sign if Dest is not signed. |
+ if (dest_limits::digits > source_limits::digits) |
+ return dest_limits::is_signed || source >= 0; |
+ |
+ // Otherwise, Dest is narrower than Source. |
+ |
+ // Check for underflow. |
+ if (source_limits::is_signed && // Don't need to check if source is unsigned. |
+ source < static_cast<Source>(dest_limits::min())) |
+ return false; |
+ |
+ // Or overflow. |
+ return source <= static_cast<Source>(dest_limits::max()); |
+} |
+ |
+template <class Dest, class Source> |
+inline Dest numeric_cast(Source source) { |
+ CHECK(IsNumericCastableTo<Dest>(source)); |
+ return static_cast<Dest>(source); |
+} |
+ |
+} // namespace base |
+ |
+#endif // BASE_NUMERIC_CAST_H_ |