Chromium Code Reviews| Index: base/safe_numerics.h |
| diff --git a/base/safe_numerics.h b/base/safe_numerics.h |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..0392e270f976b262cd06973bf25738eb6e6a6605 |
| --- /dev/null |
| +++ b/base/safe_numerics.h |
| @@ -0,0 +1,59 @@ |
| +// 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_SAFE_NUMERICS_H_ |
| +#define BASE_SAFE_NUMERICS_H_ |
| + |
| +#include <limits> |
| + |
| +#include "base/logging.h" |
| + |
| +namespace base { |
| +namespace internal { |
| + |
| +// The main test for whether the conversion will under or overflow. |
| +template <class Dest, class Source> |
| +inline bool IsValidNumericCast(Source source) { |
| + typedef std::numeric_limits<Source> SourceLimits; |
| + typedef std::numeric_limits<Dest> DestLimits; |
| + COMPILE_ASSERT(SourceLimits::is_specialized, argument_must_be_numeric); |
| + COMPILE_ASSERT(SourceLimits::is_integer, argument_must_be_integral); |
| + COMPILE_ASSERT(DestLimits::is_specialized, result_must_be_numeric); |
| + COMPILE_ASSERT(DestLimits::is_integer, result_must_be_integral); |
| + |
| + // Source and Dest are the same. |
| + if (DestLimits::digits == SourceLimits::digits && |
| + DestLimits::is_signed == SourceLimits::is_signed) |
| + return true; |
| + |
| + // Dest is wider, check for loss of sign if Dest is not signed. |
| + if (DestLimits::digits > SourceLimits::digits) |
| + return DestLimits::is_signed || source >= 0; |
| + |
| + // Otherwise, Dest is narrower than Source. |
| + |
| + // Check for underflow. |
| + if (SourceLimits::is_signed && // Don't need to check if source is unsigned. |
| + source < static_cast<Source>(DestLimits::min())) |
| + return false; |
| + |
| + // Or overflow. |
| + return source <= static_cast<Source>(DestLimits::max()); |
| +} |
| + |
| +} // namespace internal |
| + |
| +// 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. |
| +template <class Dest, class Source> |
| +inline Dest numeric_cast(Source source) { |
| + CHECK(internal::IsValidNumericCast<Dest>(source)); |
| + return static_cast<Dest>(source); |
| +} |
| + |
| +} // namespace base |
|
brettw
2013/01/15 21:09:50
We've done some extern templates in some cases whi
jschuh
2013/01/15 21:13:27
fwiw, I was planning on just adding a saturating_c
|
| + |
| +#endif // BASE_SAFE_NUMERICS_H_ |