Expand support in safe_numeric.h
* Refactor code in preparation for safe math operations.
* Support float type for numeric casts.
* Expose IsValueInRangeForNumericType as part of the API.
* Add saturated_cast.
BUG=332611
R=akalin@chromium.org, willchan@chromium.org
Review URL: https://codereview.chromium.org/131063002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@245183 0039d316-1c4b-4281-b951-d872f2087c98
diff --git a/base/base.gyp b/base/base.gyp
index 14220f9..63306cd 100644
--- a/base/base.gyp
+++ b/base/base.gyp
@@ -575,7 +575,6 @@
'profiler/tracked_time_unittest.cc',
'rand_util_unittest.cc',
'safe_numerics_unittest.cc',
- 'safe_numerics_unittest.nc',
'scoped_clear_errno_unittest.cc',
'scoped_native_library_unittest.cc',
'scoped_observer.h',
diff --git a/base/base.gypi b/base/base.gypi
index c41c387..1abf416 100644
--- a/base/base.gypi
+++ b/base/base.gypi
@@ -489,6 +489,7 @@
'run_loop.cc',
'run_loop.h',
'safe_numerics.h',
+ 'safe_numerics_impl.h',
'safe_strerror_posix.cc',
'safe_strerror_posix.h',
'scoped_native_library.cc',
diff --git a/base/safe_numerics.h b/base/safe_numerics.h
index ce5c72fc..6fbd5bf 100644
--- a/base/safe_numerics.h
+++ b/base/safe_numerics.h
@@ -1,4 +1,4 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
+// Copyright 2014 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.
@@ -8,126 +8,53 @@
#include <limits>
#include "base/logging.h"
+#include "base/safe_numerics_impl.h"
namespace base {
-namespace internal {
-template <bool SameSize, bool DestLarger,
- bool DestIsSigned, bool SourceIsSigned>
-struct IsValidNumericCastImpl;
-
-#define BASE_NUMERIC_CAST_CASE_SPECIALIZATION(A, B, C, D, Code) \
-template <> struct IsValidNumericCastImpl<A, B, C, D> { \
- template <class Source, class DestBounds> static inline bool Test( \
- Source source, DestBounds min, DestBounds max) { \
- return Code; \
- } \
+// Convenience function that returns true if the supplied value is in range
+// for the destination type.
+template <typename Dst, typename Src>
+inline bool IsValueInRangeForNumericType(Src value) {
+ return internal::RangeCheck<Dst>(value) == internal::TYPE_VALID;
}
-#define BASE_NUMERIC_CAST_CASE_SAME_SIZE(DestSigned, SourceSigned, Code) \
- BASE_NUMERIC_CAST_CASE_SPECIALIZATION( \
- true, true, DestSigned, SourceSigned, Code); \
- BASE_NUMERIC_CAST_CASE_SPECIALIZATION( \
- true, false, DestSigned, SourceSigned, Code)
-
-#define BASE_NUMERIC_CAST_CASE_SOURCE_LARGER(DestSigned, SourceSigned, Code) \
- BASE_NUMERIC_CAST_CASE_SPECIALIZATION( \
- false, false, DestSigned, SourceSigned, Code); \
-
-#define BASE_NUMERIC_CAST_CASE_DEST_LARGER(DestSigned, SourceSigned, Code) \
- BASE_NUMERIC_CAST_CASE_SPECIALIZATION( \
- false, true, DestSigned, SourceSigned, Code); \
-
-// The three top level cases are:
-// - Same size
-// - Source larger
-// - Dest larger
-// And for each of those three cases, we handle the 4 different possibilities
-// of signed and unsigned. This gives 12 cases to handle, which we enumerate
-// below.
-//
-// The last argument in each of the macros is the actual comparison code. It
-// has three arguments available, source (the value), and min/max which are
-// the ranges of the destination.
-
-
-// These are the cases where both types have the same size.
-
-// Both signed.
-BASE_NUMERIC_CAST_CASE_SAME_SIZE(true, true, true);
-// Both unsigned.
-BASE_NUMERIC_CAST_CASE_SAME_SIZE(false, false, true);
-// Dest unsigned, Source signed.
-BASE_NUMERIC_CAST_CASE_SAME_SIZE(false, true, source >= 0);
-// Dest signed, Source unsigned.
-// This cast is OK because Dest's max must be less than Source's.
-BASE_NUMERIC_CAST_CASE_SAME_SIZE(true, false,
- source <= static_cast<Source>(max));
-
-
-// These are the cases where Source is larger.
-
-// Both unsigned.
-BASE_NUMERIC_CAST_CASE_SOURCE_LARGER(false, false, source <= max);
-// Both signed.
-BASE_NUMERIC_CAST_CASE_SOURCE_LARGER(true, true,
- source >= min && source <= max);
-// Dest is unsigned, Source is signed.
-BASE_NUMERIC_CAST_CASE_SOURCE_LARGER(false, true,
- source >= 0 && source <= max);
-// Dest is signed, Source is unsigned.
-// This cast is OK because Dest's max must be less than Source's.
-BASE_NUMERIC_CAST_CASE_SOURCE_LARGER(true, false,
- source <= static_cast<Source>(max));
-
-
-// These are the cases where Dest is larger.
-
-// Both unsigned.
-BASE_NUMERIC_CAST_CASE_DEST_LARGER(false, false, true);
-// Both signed.
-BASE_NUMERIC_CAST_CASE_DEST_LARGER(true, true, true);
-// Dest is unsigned, Source is signed.
-BASE_NUMERIC_CAST_CASE_DEST_LARGER(false, true, source >= 0);
-// Dest is signed, Source is unsigned.
-BASE_NUMERIC_CAST_CASE_DEST_LARGER(true, false, true);
-
-#undef BASE_NUMERIC_CAST_CASE_SPECIALIZATION
-#undef BASE_NUMERIC_CAST_CASE_SAME_SIZE
-#undef BASE_NUMERIC_CAST_CASE_SOURCE_LARGER
-#undef BASE_NUMERIC_CAST_CASE_DEST_LARGER
-
-
-// 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);
-
- return IsValidNumericCastImpl<
- sizeof(Dest) == sizeof(Source),
- (sizeof(Dest) > sizeof(Source)),
- DestLimits::is_signed,
- SourceLimits::is_signed>::Test(
- source,
- DestLimits::min(),
- DestLimits::max());
-}
-
-} // namespace internal
-
// checked_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 checked_numeric_cast(Source source) {
- CHECK(internal::IsValidNumericCast<Dest>(source));
- return static_cast<Dest>(source);
+// overflow or underflow. NaN source will always trigger a CHECK.
+template <typename Dst, typename Src>
+inline Dst checked_numeric_cast(Src value) {
+ CHECK(IsValueInRangeForNumericType<Dst>(value));
+ return static_cast<Dst>(value);
+}
+
+// saturated_cast<> is analogous to static_cast<> for numeric types, except
+// that the specified numeric conversion will saturate rather than overflow or
+// underflow. NaN assignment to an integral will trigger a CHECK condition.
+template <typename Dst, typename Src>
+inline Dst saturated_cast(Src value) {
+ // Optimization for floating point values, which already saturate.
+ if (std::numeric_limits<Dst>::is_iec559)
+ return static_cast<Dst>(value);
+
+ switch (internal::RangeCheck<Dst>(value)) {
+ case internal::TYPE_VALID:
+ return static_cast<Dst>(value);
+
+ case internal::TYPE_UNDERFLOW:
+ return std::numeric_limits<Dst>::min();
+
+ case internal::TYPE_OVERFLOW:
+ return std::numeric_limits<Dst>::max();
+
+ // Should fail only on attempting to assign NaN to a saturated integer.
+ case internal::TYPE_INVALID:
+ CHECK(false);
+ return std::numeric_limits<Dst>::max();
+ }
+
+ NOTREACHED();
+ return static_cast<Dst>(value);
}
} // namespace base
diff --git a/base/safe_numerics_impl.h b/base/safe_numerics_impl.h
new file mode 100644
index 0000000..6ca1e2bc
--- /dev/null
+++ b/base/safe_numerics_impl.h
@@ -0,0 +1,183 @@
+// Copyright 2014 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_IMPL_H_
+#define BASE_SAFE_NUMERICS_IMPL_H_
+
+#include <limits>
+
+#include "base/macros.h"
+
+namespace base {
+namespace internal {
+
+enum DstSign {
+ DST_UNSIGNED,
+ DST_SIGNED
+};
+
+enum SrcSign {
+ SRC_UNSIGNED,
+ SRC_SIGNED
+};
+
+enum DstRange {
+ OVERLAPS_RANGE,
+ CONTAINS_RANGE
+};
+
+// Helper templates to statically determine if our destination type can contain
+// all values represented by the source type.
+
+template <typename Dst, typename Src,
+ DstSign IsDstSigned = std::numeric_limits<Dst>::is_signed ?
+ DST_SIGNED : DST_UNSIGNED,
+ SrcSign IsSrcSigned = std::numeric_limits<Src>::is_signed ?
+ SRC_SIGNED : SRC_UNSIGNED>
+struct StaticRangeCheck {};
+
+template <typename Dst, typename Src>
+struct StaticRangeCheck<Dst, Src, DST_SIGNED, SRC_SIGNED> {
+ typedef std::numeric_limits<Dst> DstLimits;
+ typedef std::numeric_limits<Src> SrcLimits;
+ // Compare based on max_exponent, which we must compute for integrals.
+ static const size_t kDstMaxExponent = DstLimits::is_iec559 ?
+ DstLimits::max_exponent :
+ (sizeof(Dst) * 8 - 1);
+ static const size_t kSrcMaxExponent = SrcLimits::is_iec559 ?
+ SrcLimits::max_exponent :
+ (sizeof(Src) * 8 - 1);
+ static const DstRange value = kDstMaxExponent >= kSrcMaxExponent ?
+ CONTAINS_RANGE : OVERLAPS_RANGE;
+};
+
+template <typename Dst, typename Src>
+struct StaticRangeCheck<Dst, Src, DST_UNSIGNED, SRC_UNSIGNED> {
+ static const DstRange value = sizeof(Dst) >= sizeof(Src) ?
+ CONTAINS_RANGE : OVERLAPS_RANGE;
+};
+
+template <typename Dst, typename Src>
+struct StaticRangeCheck<Dst, Src, DST_SIGNED, SRC_UNSIGNED> {
+ typedef std::numeric_limits<Dst> DstLimits;
+ typedef std::numeric_limits<Src> SrcLimits;
+ // Compare based on max_exponent, which we must compute for integrals.
+ static const size_t kDstMaxExponent = DstLimits::is_iec559 ?
+ DstLimits::max_exponent :
+ (sizeof(Dst) * 8 - 1);
+ static const size_t kSrcMaxExponent = sizeof(Src) * 8;
+ static const DstRange value = kDstMaxExponent >= kSrcMaxExponent ?
+ CONTAINS_RANGE : OVERLAPS_RANGE;
+};
+
+template <typename Dst, typename Src>
+struct StaticRangeCheck<Dst, Src, DST_UNSIGNED, SRC_SIGNED> {
+ static const DstRange value = OVERLAPS_RANGE;
+};
+
+
+enum RangeCheckResult {
+ TYPE_VALID = 0, // Value can be represented by the destination type.
+ TYPE_UNDERFLOW = 1, // Value would overflow.
+ TYPE_OVERFLOW = 2, // Value would underflow.
+ TYPE_INVALID = 3 // Source value is invalid (i.e. NaN).
+};
+
+// This macro creates a RangeCheckResult from an upper and lower bound
+// check by taking advantage of the fact that only NaN can be out of range in
+// both directions at once.
+#define BASE_NUMERIC_RANGE_CHECK_RESULT(is_in_upper_bound, is_in_lower_bound) \
+ RangeCheckResult(((is_in_upper_bound) ? 0 : TYPE_OVERFLOW) | \
+ ((is_in_lower_bound) ? 0 : TYPE_UNDERFLOW))
+
+template <typename Dst,
+ typename Src,
+ DstSign IsDstSigned = std::numeric_limits<Dst>::is_signed ?
+ DST_SIGNED : DST_UNSIGNED,
+ SrcSign IsSrcSigned = std::numeric_limits<Src>::is_signed ?
+ SRC_SIGNED : SRC_UNSIGNED,
+ DstRange IsSrcRangeContained = StaticRangeCheck<Dst, Src>::value>
+struct RangeCheckImpl {};
+
+// The following templates are for ranges that must be verified at runtime. We
+// split it into checks based on signedness to avoid confusing casts and
+// compiler warnings on signed an unsigned comparisons.
+
+// Dst range always contains the result: nothing to check.
+template <typename Dst, typename Src, DstSign IsDstSigned, SrcSign IsSrcSigned>
+struct RangeCheckImpl<Dst, Src, IsDstSigned, IsSrcSigned, CONTAINS_RANGE> {
+ static RangeCheckResult Check(Src value) {
+ return TYPE_VALID;
+ }
+};
+
+// Signed to signed narrowing.
+template <typename Dst, typename Src>
+struct RangeCheckImpl<Dst, Src, DST_SIGNED, SRC_SIGNED, OVERLAPS_RANGE> {
+ static RangeCheckResult Check(Src value) {
+ typedef std::numeric_limits<Dst> DstLimits;
+ return DstLimits::is_iec559 ?
+ BASE_NUMERIC_RANGE_CHECK_RESULT(
+ value <= static_cast<Src>(DstLimits::max()),
+ value >= static_cast<Src>(DstLimits::max() * -1)) :
+ BASE_NUMERIC_RANGE_CHECK_RESULT(
+ value <= static_cast<Src>(DstLimits::max()),
+ value >= static_cast<Src>(DstLimits::min()));
+ }
+};
+
+// Unsigned to unsigned narrowing.
+template <typename Dst, typename Src>
+struct RangeCheckImpl<Dst, Src, DST_UNSIGNED, SRC_UNSIGNED, OVERLAPS_RANGE> {
+ static RangeCheckResult Check(Src value) {
+ typedef std::numeric_limits<Dst> DstLimits;
+ return BASE_NUMERIC_RANGE_CHECK_RESULT(
+ value <= static_cast<Src>(DstLimits::max()), true);
+ }
+};
+
+// Unsigned to signed.
+template <typename Dst, typename Src>
+struct RangeCheckImpl<Dst, Src, DST_SIGNED, SRC_UNSIGNED, OVERLAPS_RANGE> {
+ static RangeCheckResult Check(Src value) {
+ typedef std::numeric_limits<Dst> DstLimits;
+ return sizeof(Dst) > sizeof(Src) ? TYPE_VALID :
+ BASE_NUMERIC_RANGE_CHECK_RESULT(
+ value <= static_cast<Src>(DstLimits::max()), true);
+ }
+};
+
+// Signed to unsigned.
+template <typename Dst, typename Src>
+struct RangeCheckImpl<Dst, Src, DST_UNSIGNED, SRC_SIGNED, OVERLAPS_RANGE> {
+ static RangeCheckResult Check(Src value) {
+ typedef std::numeric_limits<Dst> DstLimits;
+ typedef std::numeric_limits<Src> SrcLimits;
+ // Compare based on max_exponent, which we must compute for integrals.
+ static const size_t kDstMaxExponent = sizeof(Dst) * 8;
+ static const size_t kSrcMaxExponent = SrcLimits::is_iec559 ?
+ SrcLimits::max_exponent :
+ (sizeof(Src) * 8 - 1);
+ return (kDstMaxExponent >= kSrcMaxExponent) ?
+ BASE_NUMERIC_RANGE_CHECK_RESULT(true, value >= static_cast<Src>(0)) :
+ BASE_NUMERIC_RANGE_CHECK_RESULT(
+ value <= static_cast<Src>(DstLimits::max()),
+ value >= static_cast<Src>(0));
+ }
+};
+
+template <typename Dst, typename Src>
+inline RangeCheckResult RangeCheck(Src value) {
+ COMPILE_ASSERT(std::numeric_limits<Src>::is_specialized,
+ argument_must_be_numeric);
+ COMPILE_ASSERT(std::numeric_limits<Dst>::is_specialized,
+ result_must_be_numeric);
+ return RangeCheckImpl<Dst, Src>::Check(value);
+}
+
+} // namespace internal
+} // namespace base
+
+#endif // BASE_SAFE_NUMERICS_IMPL_H_
+
diff --git a/base/safe_numerics_unittest.cc b/base/safe_numerics_unittest.cc
index c66e56f3..1bcd38f 100644
--- a/base/safe_numerics_unittest.cc
+++ b/base/safe_numerics_unittest.cc
@@ -2,149 +2,277 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
-#include <gtest/gtest.h>
-
-#include <sstream>
-#include <vector>
-
#include "base/safe_numerics.h"
+#include <stdint.h>
+
+#include <limits>
+
+#include "base/compiler_specific.h"
+#include "testing/gtest/include/gtest/gtest.h"
+
namespace base {
namespace internal {
-// This is far (far, far) too slow to run normally, but if you're refactoring
-// it might be useful.
-// #define RUN_EXHAUSTIVE_TEST
+// Enumerates the five different conversions types we need to test.
+enum NumericConversionType {
+ SIGN_PRESERVING_VALUE_PRESERVING,
+ SIGN_PRESERVING_NARROW,
+ SIGN_TO_UNSIGN_WIDEN_OR_EQUAL,
+ SIGN_TO_UNSIGN_NARROW,
+ UNSIGN_TO_SIGN_NARROW_OR_EQUAL,
+};
-#ifdef RUN_EXHAUSTIVE_TEST
+// Template covering the different conversion tests.
+template <typename Dst, typename Src, NumericConversionType conversion>
+struct TestNumericConversion {};
-template <class From, class To> void ExhaustiveCheckFromTo() {
- fprintf(stderr, ".");
- From i = std::numeric_limits<From>::min();
- for (;;) {
- std::ostringstream str_from, str_to;
- str_from << i;
- To to = static_cast<To>(i);
- str_to << to;
- bool strings_equal = str_from.str() == str_to.str();
- EXPECT_EQ(IsValidNumericCast<To>(i), strings_equal);
- fprintf(stderr, "\r%s vs %s\x1B[K",
- str_from.str().c_str(), str_to.str().c_str());
- ++i;
- // If we wrap, then we've tested everything.
- if (i == std::numeric_limits<From>::min())
- break;
+// EXPECT_EQ wrapper providing specific detail on test failures.
+#define TEST_EXPECTED_RANGE(expected, actual) \
+ EXPECT_EQ(expected, RangeCheck<Dst>(actual)) << \
+ "Conversion test: " << src << " value " << actual << \
+ " to " << dst << " on line " << line;
+
+template <typename Dst, typename Src>
+struct TestNumericConversion<Dst, Src, SIGN_PRESERVING_VALUE_PRESERVING> {
+ static void Test(const char *dst, const char *src, int line) {
+ typedef std::numeric_limits<Src> SrcLimits;
+ typedef std::numeric_limits<Dst> DstLimits;
+ // Integral to floating.
+ COMPILE_ASSERT((DstLimits::is_iec559 && SrcLimits::is_integer) ||
+ // Not floating to integral and...
+ (!(DstLimits::is_integer && SrcLimits::is_iec559) &&
+ // Same sign, same numeric, source is narrower or same.
+ ((SrcLimits::is_signed == DstLimits::is_signed &&
+ sizeof(Dst) >= sizeof(Src)) ||
+ // Or signed destination and source is smaller
+ (DstLimits::is_signed && sizeof(Dst) > sizeof(Src)))),
+ comparison_must_be_sign_preserving_and_value_preserving);
+
+ TEST_EXPECTED_RANGE(TYPE_VALID, SrcLimits::max());
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(1));
+ if (SrcLimits::is_iec559) {
+ TEST_EXPECTED_RANGE(TYPE_VALID, SrcLimits::max() * static_cast<Src>(-1));
+ TEST_EXPECTED_RANGE(TYPE_OVERFLOW, SrcLimits::infinity());
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::infinity() * -1);
+ TEST_EXPECTED_RANGE(TYPE_INVALID, SrcLimits::quiet_NaN());
+ } else if (std::numeric_limits<Src>::is_signed) {
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(-1));
+ TEST_EXPECTED_RANGE(TYPE_VALID, SrcLimits::min());
+ }
}
+};
+
+template <typename Dst, typename Src>
+struct TestNumericConversion<Dst, Src, SIGN_PRESERVING_NARROW> {
+ static void Test(const char *dst, const char *src, int line) {
+ typedef std::numeric_limits<Src> SrcLimits;
+ typedef std::numeric_limits<Dst> DstLimits;
+ COMPILE_ASSERT(SrcLimits::is_signed == DstLimits::is_signed,
+ destination_and_source_sign_must_be_the_same);
+ COMPILE_ASSERT(sizeof(Dst) < sizeof(Src) ||
+ (DstLimits::is_integer && SrcLimits::is_iec559),
+ destination_must_be_narrower_than_source);
+
+ TEST_EXPECTED_RANGE(TYPE_OVERFLOW, SrcLimits::max());
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(1));
+ if (SrcLimits::is_iec559) {
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::max() * -1);
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(-1));
+ TEST_EXPECTED_RANGE(TYPE_OVERFLOW, SrcLimits::infinity());
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::infinity() * -1);
+ TEST_EXPECTED_RANGE(TYPE_INVALID, SrcLimits::quiet_NaN());
+ } else if (SrcLimits::is_signed) {
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::min());
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(-1));
+ } else {
+ TEST_EXPECTED_RANGE(TYPE_VALID, SrcLimits::min());
+ }
+ }
+};
+
+template <typename Dst, typename Src>
+struct TestNumericConversion<Dst, Src, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL> {
+ static void Test(const char *dst, const char *src, int line) {
+ typedef std::numeric_limits<Src> SrcLimits;
+ typedef std::numeric_limits<Dst> DstLimits;
+ COMPILE_ASSERT(sizeof(Dst) >= sizeof(Src),
+ destination_must_be_equal_or_wider_than_source);
+ COMPILE_ASSERT(SrcLimits::is_signed, source_must_be_signed);
+ COMPILE_ASSERT(!DstLimits::is_signed, destination_must_be_unsigned);
+
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::min());
+ TEST_EXPECTED_RANGE(TYPE_VALID, SrcLimits::max());
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(1));
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, static_cast<Src>(-1));
+ }
+};
+
+template <typename Dst, typename Src>
+struct TestNumericConversion<Dst, Src, SIGN_TO_UNSIGN_NARROW> {
+ static void Test(const char *dst, const char *src, int line) {
+ typedef std::numeric_limits<Src> SrcLimits;
+ typedef std::numeric_limits<Dst> DstLimits;
+ COMPILE_ASSERT((DstLimits::is_integer && SrcLimits::is_iec559) ||
+ (sizeof(Dst) < sizeof(Src)),
+ destination_must_be_narrower_than_source);
+ COMPILE_ASSERT(SrcLimits::is_signed, source_must_be_signed);
+ COMPILE_ASSERT(!DstLimits::is_signed, destination_must_be_unsigned);
+
+ TEST_EXPECTED_RANGE(TYPE_OVERFLOW, SrcLimits::max());
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(1));
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, static_cast<Src>(-1));
+ if (SrcLimits::is_iec559) {
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::max() * -1);
+ TEST_EXPECTED_RANGE(TYPE_OVERFLOW, SrcLimits::infinity());
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::infinity() * -1);
+ TEST_EXPECTED_RANGE(TYPE_INVALID, SrcLimits::quiet_NaN());
+ } else {
+ TEST_EXPECTED_RANGE(TYPE_UNDERFLOW, SrcLimits::min());
+ }
+ }
+};
+
+template <typename Dst, typename Src>
+struct TestNumericConversion<Dst, Src, UNSIGN_TO_SIGN_NARROW_OR_EQUAL> {
+ static void Test(const char *dst, const char *src, int line) {
+ typedef std::numeric_limits<Src> SrcLimits;
+ typedef std::numeric_limits<Dst> DstLimits;
+ COMPILE_ASSERT(sizeof(Dst) <= sizeof(Src),
+ destination_must_be_narrower_or_equal_to_source);
+ COMPILE_ASSERT(!SrcLimits::is_signed, source_must_be_unsigned);
+ COMPILE_ASSERT(DstLimits::is_signed, destination_must_be_signed);
+
+ TEST_EXPECTED_RANGE(TYPE_VALID, SrcLimits::min());
+ TEST_EXPECTED_RANGE(TYPE_OVERFLOW, SrcLimits::max());
+ TEST_EXPECTED_RANGE(TYPE_VALID, static_cast<Src>(1));
+ }
+};
+
+// Helper macro to wrap displaying the conversion types and line numbers
+#define TEST_NUMERIC_CONVERSION(d, s, t) \
+ TestNumericConversion<d, s, t>::Test(#d, #s, __LINE__)
+
+TEST(SafeNumerics, IntMinConversions) {
+ TEST_NUMERIC_CONVERSION(int8_t, int8_t, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(uint8_t, uint8_t, SIGN_PRESERVING_VALUE_PRESERVING);
+
+ TEST_NUMERIC_CONVERSION(int8_t, int, SIGN_PRESERVING_NARROW);
+ TEST_NUMERIC_CONVERSION(uint8_t, unsigned int, SIGN_PRESERVING_NARROW);
+ TEST_NUMERIC_CONVERSION(int8_t, float, SIGN_PRESERVING_NARROW);
+
+ TEST_NUMERIC_CONVERSION(uint8_t, int8_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
+
+ TEST_NUMERIC_CONVERSION(uint8_t, int, SIGN_TO_UNSIGN_NARROW);
+ TEST_NUMERIC_CONVERSION(uint8_t, intmax_t, SIGN_TO_UNSIGN_NARROW);
+ TEST_NUMERIC_CONVERSION(uint8_t, float, SIGN_TO_UNSIGN_NARROW);
+
+ TEST_NUMERIC_CONVERSION(int8_t, unsigned int, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
+ TEST_NUMERIC_CONVERSION(int8_t, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
}
-template <class From> void ExhaustiveCheckFrom() {
- ExhaustiveCheckFromTo<From, short>();
- ExhaustiveCheckFromTo<From, unsigned short>();
- ExhaustiveCheckFromTo<From, int>();
- ExhaustiveCheckFromTo<From, unsigned int>();
- ExhaustiveCheckFromTo<From, long long>();
- ExhaustiveCheckFromTo<From, unsigned long long>();
- ExhaustiveCheckFromTo<From, size_t>();
- fprintf(stderr, "\n");
+TEST(SafeNumerics, IntConversions) {
+ TEST_NUMERIC_CONVERSION(int, int, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(unsigned int, unsigned int,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(int, int8_t, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(unsigned int, uint8_t,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(int, uint8_t, SIGN_PRESERVING_VALUE_PRESERVING);
+
+ TEST_NUMERIC_CONVERSION(int, intmax_t, SIGN_PRESERVING_NARROW);
+ TEST_NUMERIC_CONVERSION(unsigned int, uintmax_t, SIGN_PRESERVING_NARROW);
+ TEST_NUMERIC_CONVERSION(int, float, SIGN_PRESERVING_NARROW);
+ TEST_NUMERIC_CONVERSION(int, double, SIGN_PRESERVING_NARROW);
+
+ TEST_NUMERIC_CONVERSION(unsigned int, int, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
+ TEST_NUMERIC_CONVERSION(unsigned int, int8_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
+
+ TEST_NUMERIC_CONVERSION(unsigned int, intmax_t, SIGN_TO_UNSIGN_NARROW);
+ TEST_NUMERIC_CONVERSION(unsigned int, float, SIGN_TO_UNSIGN_NARROW);
+ TEST_NUMERIC_CONVERSION(unsigned int, double, SIGN_TO_UNSIGN_NARROW);
+
+ TEST_NUMERIC_CONVERSION(int, unsigned int, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
+ TEST_NUMERIC_CONVERSION(int, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
}
+TEST(SafeNumerics, IntMaxConversions) {
+ TEST_NUMERIC_CONVERSION(intmax_t, intmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(uintmax_t, uintmax_t,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(intmax_t, int, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(uintmax_t, unsigned int,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(intmax_t, unsigned int,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(intmax_t, uint8_t, SIGN_PRESERVING_VALUE_PRESERVING);
+
+ TEST_NUMERIC_CONVERSION(intmax_t, float, SIGN_PRESERVING_NARROW);
+ TEST_NUMERIC_CONVERSION(intmax_t, double, SIGN_PRESERVING_NARROW);
+
+ TEST_NUMERIC_CONVERSION(uintmax_t, int, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
+ TEST_NUMERIC_CONVERSION(uintmax_t, int8_t, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
+
+ TEST_NUMERIC_CONVERSION(uintmax_t, float, SIGN_TO_UNSIGN_NARROW);
+ TEST_NUMERIC_CONVERSION(uintmax_t, double, SIGN_TO_UNSIGN_NARROW);
+
+ TEST_NUMERIC_CONVERSION(intmax_t, uintmax_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
+}
+
+TEST(SafeNumerics, FloatConversions) {
+ TEST_NUMERIC_CONVERSION(float, intmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(float, uintmax_t,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(float, int, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(float, unsigned int,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+
+ TEST_NUMERIC_CONVERSION(float, double, SIGN_PRESERVING_NARROW);
+}
+
+TEST(SafeNumerics, DoubleConversions) {
+ TEST_NUMERIC_CONVERSION(double, intmax_t, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(double, uintmax_t,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(double, int, SIGN_PRESERVING_VALUE_PRESERVING);
+ TEST_NUMERIC_CONVERSION(double, unsigned int,
+ SIGN_PRESERVING_VALUE_PRESERVING);
+}
+
+TEST(SafeNumerics, SizeTConversions) {
+ TEST_NUMERIC_CONVERSION(size_t, int, SIGN_TO_UNSIGN_WIDEN_OR_EQUAL);
+ TEST_NUMERIC_CONVERSION(int, size_t, UNSIGN_TO_SIGN_NARROW_OR_EQUAL);
+}
+
+TEST(SafeNumerics, CastTests) {
+// MSVC catches and warns that we're forcing saturation in these tests.
+// Since that's intentional, we need to shut this warning off.
+#if defined(COMPILER_MSVC)
+#pragma warning(disable : 4756)
#endif
-
-TEST(SafeNumerics, NumericCast) {
int small_positive = 1;
int small_negative = -1;
- int large_positive = INT_MAX;
- int large_negative = INT_MIN;
- size_t size_t_small = 1;
- size_t size_t_large = UINT_MAX;
+ double double_small = 1.0;
+ double double_large = std::numeric_limits<double>::max();
+ double double_infinity = std::numeric_limits<float>::infinity();
- // Narrow signed destination.
- EXPECT_TRUE(IsValidNumericCast<signed char>(small_positive));
- EXPECT_TRUE(IsValidNumericCast<signed char>(small_negative));
- EXPECT_FALSE(IsValidNumericCast<signed char>(large_positive));
- EXPECT_FALSE(IsValidNumericCast<signed char>(large_negative));
- EXPECT_TRUE(IsValidNumericCast<signed short>(small_positive));
- EXPECT_TRUE(IsValidNumericCast<signed short>(small_negative));
+ // Just test that the cast compiles, since the other tests cover logic.
+ EXPECT_EQ(0, base::checked_numeric_cast<int>(static_cast<size_t>(0)));
- // Narrow unsigned destination.
- EXPECT_TRUE(IsValidNumericCast<unsigned char>(small_positive));
- EXPECT_FALSE(IsValidNumericCast<unsigned char>(small_negative));
- EXPECT_FALSE(IsValidNumericCast<unsigned char>(large_positive));
- EXPECT_FALSE(IsValidNumericCast<unsigned char>(large_negative));
- EXPECT_FALSE(IsValidNumericCast<unsigned short>(small_negative));
- EXPECT_FALSE(IsValidNumericCast<unsigned short>(large_negative));
-
- // Same width signed destination.
- EXPECT_TRUE(IsValidNumericCast<signed int>(small_positive));
- EXPECT_TRUE(IsValidNumericCast<signed int>(small_negative));
- EXPECT_TRUE(IsValidNumericCast<signed int>(large_positive));
- EXPECT_TRUE(IsValidNumericCast<signed int>(large_negative));
-
- // Same width unsigned destination.
- EXPECT_TRUE(IsValidNumericCast<unsigned int>(small_positive));
- EXPECT_FALSE(IsValidNumericCast<unsigned int>(small_negative));
- EXPECT_TRUE(IsValidNumericCast<unsigned int>(large_positive));
- EXPECT_FALSE(IsValidNumericCast<unsigned int>(large_negative));
-
- // Wider signed destination.
- EXPECT_TRUE(IsValidNumericCast<long long>(small_positive));
- EXPECT_TRUE(IsValidNumericCast<long long>(large_negative));
- EXPECT_TRUE(IsValidNumericCast<long long>(small_positive));
- EXPECT_TRUE(IsValidNumericCast<long long>(large_negative));
-
- // Wider unsigned destination.
- EXPECT_TRUE(IsValidNumericCast<unsigned long long>(small_positive));
- EXPECT_FALSE(IsValidNumericCast<unsigned long long>(small_negative));
- EXPECT_TRUE(IsValidNumericCast<unsigned long long>(large_positive));
- EXPECT_FALSE(IsValidNumericCast<unsigned long long>(large_negative));
-
- // Negative to size_t.
- EXPECT_FALSE(IsValidNumericCast<size_t>(small_negative));
- EXPECT_FALSE(IsValidNumericCast<size_t>(large_negative));
-
- // From unsigned.
- // Small.
- EXPECT_TRUE(IsValidNumericCast<signed char>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<unsigned char>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<short>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<unsigned short>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<int>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<unsigned int>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<long long>(size_t_small));
- EXPECT_TRUE(IsValidNumericCast<unsigned long long>(size_t_small));
-
- // Large.
- EXPECT_FALSE(IsValidNumericCast<signed char>(size_t_large));
- EXPECT_FALSE(IsValidNumericCast<unsigned char>(size_t_large));
- EXPECT_FALSE(IsValidNumericCast<short>(size_t_large));
- EXPECT_FALSE(IsValidNumericCast<unsigned short>(size_t_large));
- EXPECT_FALSE(IsValidNumericCast<int>(size_t_large));
- EXPECT_TRUE(IsValidNumericCast<unsigned int>(size_t_large));
- EXPECT_TRUE(IsValidNumericCast<long long>(size_t_large));
- EXPECT_TRUE(IsValidNumericCast<unsigned long long>(size_t_large));
-
- // Various edge cases.
- EXPECT_TRUE(IsValidNumericCast<int>(static_cast<short>(SHRT_MIN)));
- EXPECT_FALSE(
- IsValidNumericCast<unsigned short>(static_cast<short>(SHRT_MIN)));
- EXPECT_FALSE(IsValidNumericCast<unsigned short>(SHRT_MIN));
-
- // Confirm that checked_numeric_cast<> actually compiles.
- std::vector<int> v;
- unsigned int checked_size =
- base::checked_numeric_cast<unsigned int>(v.size());
- EXPECT_EQ(0u, checked_size);
-
-#ifdef RUN_EXHAUSTIVE_TEST
- ExhaustiveCheckFrom<short>();
- ExhaustiveCheckFrom<unsigned short>();
- ExhaustiveCheckFrom<int>();
- ExhaustiveCheckFrom<unsigned int>();
- ExhaustiveCheckFrom<long long>();
- ExhaustiveCheckFrom<unsigned long long>();
- ExhaustiveCheckFrom<size_t>();
-#endif
+ // Test various saturation corner cases.
+ EXPECT_EQ(saturated_cast<int>(small_negative),
+ static_cast<int>(small_negative));
+ EXPECT_EQ(saturated_cast<int>(small_positive),
+ static_cast<int>(small_positive));
+ EXPECT_EQ(saturated_cast<unsigned>(small_negative),
+ static_cast<unsigned>(0));
+ EXPECT_EQ(saturated_cast<int>(double_small),
+ static_cast<int>(double_small));
+ EXPECT_EQ(saturated_cast<int>(double_large),
+ std::numeric_limits<int>::max());
+ EXPECT_EQ(saturated_cast<float>(double_large), double_infinity);
+ EXPECT_EQ(saturated_cast<float>(-double_large), -double_infinity);
}
} // namespace internal
diff --git a/base/safe_numerics_unittest.nc b/base/safe_numerics_unittest.nc
deleted file mode 100644
index 4219cd5..0000000
--- a/base/safe_numerics_unittest.nc
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright (c) 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.
-
-#include <float.h>
-
-#include "base/safe_numerics.h"
-
-using base::internal::IsValidNumericCast;
-
-#if defined(NCTEST_NO_FLOATING_POINT_1) // [r"size of array is negative"]
-
-void WontCompile() {
- IsValidNumericCast<float>(0.0);
-}
-
-#elif defined(NCTEST_NO_FLOATING_POINT_2) // [r"size of array is negative"]
-
-void WontCompile() {
- IsValidNumericCast<double>(0.0f);
-}
-
-#elif defined(NCTEST_NO_FLOATING_POINT_3) // [r"size of array is negative"]
-
-void WontCompile() {
- IsValidNumericCast<int>(DBL_MAX);
-}
-
-#endif