OLD | NEW |
(Empty) | |
| 1 // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #ifndef BASE_NUMERIC_CAST_H_ |
| 6 #define BASE_NUMERIC_CAST_H_ |
| 7 |
| 8 #include <limits> |
| 9 |
| 10 #include "base/logging.h" |
| 11 |
| 12 namespace base { |
| 13 |
| 14 // numeric_cast<> is analogous to static_cast<> for numeric types, except that |
| 15 // it CHECKs that the specified numeric conversion will not overflow or |
| 16 // underflow. Floating point arguments are not currently allowed (this is |
| 17 // COMPILE_ASSERTd), though this could be supported if necessary. |
| 18 |
| 19 // The main test for whether the conversion will under or overflow. |
| 20 template <class Dest, class Source> |
| 21 inline bool IsNumericCastableTo(Source source) { |
| 22 typedef std::numeric_limits<Source> source_limits; |
| 23 typedef std::numeric_limits<Dest> dest_limits; |
| 24 COMPILE_ASSERT(source_limits::is_specialized, argument_must_be_numeric); |
| 25 COMPILE_ASSERT(source_limits::is_integer, argument_must_be_integral); |
| 26 COMPILE_ASSERT(dest_limits::is_specialized, result_must_be_numeric); |
| 27 COMPILE_ASSERT(dest_limits::is_integer, result_must_be_integral); |
| 28 |
| 29 // Source and Dest are the same type. |
| 30 if (dest_limits::digits == source_limits::digits && |
| 31 dest_limits::is_signed == source_limits::is_signed) { |
| 32 return true; |
| 33 |
| 34 // Dest is wider. Check for underflow if dest is not signed. |
| 35 } else if (dest_limits::digits > source_limits::digits) { |
| 36 return dest_limits::is_signed || source >= 0; |
| 37 |
| 38 // Destination is narrower than source. |
| 39 } else { |
| 40 // Check for underflow if source is signed. |
| 41 if (source_limits::is_signed && |
| 42 source < static_cast<Source>(dest_limits::min())) |
| 43 return false; |
| 44 |
| 45 // Check for overflow. |
| 46 return source <= static_cast<Source>(dest_limits::max()); |
| 47 } |
| 48 } |
| 49 |
| 50 template <class Dest, class Source> |
| 51 inline Dest numeric_cast(Source source) { |
| 52 CHECK(IsNumericCastableTo<Dest>(source)); |
| 53 return static_cast<Dest>(source); |
| 54 } |
| 55 |
| 56 } // namespace base |
| 57 |
| 58 #endif // BASE_NUMERIC_CAST_H_ |
OLD | NEW |