Index: base/numeric_cast.h |
=================================================================== |
--- base/numeric_cast.h (revision 0) |
+++ base/numeric_cast.h (revision 0) |
@@ -0,0 +1,58 @@ |
+// 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_ |
+#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> |
+inline bool IsNumericCastableTo(Source source) { |
+ typedef std::numeric_limits<Source> source_limits; |
+ 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 type. |
+ if (dest_limits::digits == source_limits::digits && |
+ dest_limits::is_signed == source_limits::is_signed) { |
+ return true; |
+ |
+ // Dest is wider. Check for underflow if dest is not signed. |
+ } else if (dest_limits::digits > source_limits::digits) { |
+ return dest_limits::is_signed || source >= 0; |
+ |
+ // Destination is narrower than source. |
+ } else { |
+ // Check for underflow if source is signed. |
+ if (source_limits::is_signed && |
+ source < static_cast<Source>(dest_limits::min())) |
+ return false; |
+ |
+ // Check for 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_ |