10 #include <type_traits> 16 #if !defined(NDEBUG) || defined(ARMNN_NUMERIC_CAST_TESTABLE) 17 #define ENABLE_NUMERIC_CAST_CHECKS 1 19 #define ENABLE_NUMERIC_CAST_CHECKS 0 22 #if defined(ARMNN_NUMERIC_CAST_TESTABLE) 23 # define ARMNN_NUMERIC_CAST_CHECK(cond, msg) ConditionalThrow<std::bad_cast>(cond) 25 # define ARMNN_NUMERIC_CAST_CHECK(cond, msg) ARMNN_ASSERT_MSG(cond, msg) 28 template<
typename Dest,
typename Source>
29 typename std::enable_if_t<
30 std::is_unsigned<Source>::value &&
31 std::is_unsigned<Dest>::value
35 #if ENABLE_NUMERIC_CAST_CHECKS 36 if (source > std::numeric_limits<Dest>::max())
39 "narrower unsigned type. Overflow detected.");
41 #endif // ENABLE_NUMERIC_CAST_CHECKS 43 return static_cast<Dest
>(source);
46 template<
typename Dest,
typename Source>
47 typename std::enable_if_t<
48 std::is_signed<Source>::value &&
49 std::is_signed<Dest>::value
53 static_assert(!std::is_floating_point<Source>::value && !std::is_floating_point<Dest>::value,
54 "numeric_cast doesn't cast float.");
56 #if ENABLE_NUMERIC_CAST_CHECKS 57 if (source > std::numeric_limits<Dest>::max())
60 "Overflow detected.");
63 if (source < std::numeric_limits<Dest>::lowest())
66 "Underflow detected.");
68 #endif // ENABLE_NUMERIC_CAST_CHECKS 70 return static_cast<Dest
>(source);
74 template<
typename Dest,
typename Source>
75 typename std::enable_if_t<
76 std::is_signed<Dest>::value &&
77 std::is_unsigned<Source>::value
81 static_assert(!std::is_floating_point<Dest>::value,
"numeric_cast doesn't cast to float.");
83 #if ENABLE_NUMERIC_CAST_CHECKS 84 if (sValue >
static_cast< typename std::make_unsigned<Dest>::type
>(std::numeric_limits<Dest>::max()))
87 "Overflow detected.");
89 #endif // ENABLE_NUMERIC_CAST_CHECKS 91 return static_cast<Dest
>(sValue);
95 template<
typename Dest,
typename Source>
96 typename std::enable_if_t<
97 std::is_unsigned<Dest>::value &&
98 std::is_signed<Source>::value
102 static_assert(!std::is_floating_point<Source>::value && !std::is_floating_point<Dest>::value,
103 "numeric_cast doesn't cast floats.");
105 #if ENABLE_NUMERIC_CAST_CHECKS 109 "Underflow detected.");
112 if (
static_cast< typename std::make_unsigned<Source>::type
>(sValue) > std::numeric_limits<Dest>::max())
115 "Overflow detected.");
118 #endif // ENABLE_NUMERIC_CAST_CHECKS 119 return static_cast<Dest
>(sValue);
122 #undef ENABLE_NUMERIC_CAST_CHECKS Copyright (c) 2020 ARM Limited.
#define ARMNN_NUMERIC_CAST_CHECK(cond, msg)
std::enable_if_t< std::is_unsigned< Source >::value &&std::is_unsigned< Dest >::value, Dest > numeric_cast(Source source)