Chromium Code Reviews| OLD | NEW |
|---|---|
| 1 // Copyright 2014 The Chromium Authors. All rights reserved. | 1 // Copyright 2014 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
| 4 | 4 |
| 5 #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_ | 5 #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_ |
| 6 #define BASE_NUMERICS_SAFE_CONVERSIONS_H_ | 6 #define BASE_NUMERICS_SAFE_CONVERSIONS_H_ |
| 7 | 7 |
| 8 #include <stddef.h> | 8 #include <stddef.h> |
| 9 #include <stdlib.h> | |
| 9 | 10 |
| 10 #include <cassert> | 11 #include <cassert> |
| 11 #include <limits> | 12 #include <limits> |
| 13 #include <ostream> | |
| 12 #include <type_traits> | 14 #include <type_traits> |
| 13 | 15 |
| 14 #include "base/numerics/safe_conversions_impl.h" | 16 #include "base/numerics/safe_conversions_impl.h" |
| 15 | 17 |
| 16 namespace base { | 18 namespace base { |
| 17 | 19 |
| 18 // Convenience function that returns true if the supplied value is in range | 20 // Convenience function that returns true if the supplied value is in range |
| 19 // for the destination type. | 21 // for the destination type. |
| 20 template <typename Dst, typename Src> | 22 template <typename Dst, typename Src> |
| 21 constexpr bool IsValueInRangeForNumericType(Src value) { | 23 constexpr bool IsValueInRangeForNumericType(Src value) { |
| (...skipping 62 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
| 84 constexpr Dst saturated_cast_impl(const Src value, | 86 constexpr Dst saturated_cast_impl(const Src value, |
| 85 const RangeConstraint constraint) { | 87 const RangeConstraint constraint) { |
| 86 return constraint == RANGE_VALID | 88 return constraint == RANGE_VALID |
| 87 ? static_cast<Dst>(value) | 89 ? static_cast<Dst>(value) |
| 88 : (constraint == RANGE_UNDERFLOW | 90 : (constraint == RANGE_UNDERFLOW |
| 89 ? std::numeric_limits<Dst>::min() | 91 ? std::numeric_limits<Dst>::min() |
| 90 : (constraint == RANGE_OVERFLOW | 92 : (constraint == RANGE_OVERFLOW |
| 91 ? std::numeric_limits<Dst>::max() | 93 ? std::numeric_limits<Dst>::max() |
| 92 : NaNHandler::template HandleFailure<Dst>())); | 94 : NaNHandler::template HandleFailure<Dst>())); |
| 93 } | 95 } |
| 94 } // namespace internal | |
| 95 | 96 |
| 96 // saturated_cast<> is analogous to static_cast<> for numeric types, except | 97 // saturated_cast<> is analogous to static_cast<> for numeric types, except |
| 97 // that the specified numeric conversion will saturate rather than overflow or | 98 // that the specified numeric conversion will saturate rather than overflow or |
| 98 // underflow. NaN assignment to an integral will defer the behavior to a | 99 // underflow. NaN assignment to an integral will defer the behavior to a |
| 99 // specified class. By default, it will return 0. | 100 // specified class. By default, it will return 0. |
| 100 template <typename Dst, | 101 template <typename Dst, |
| 101 class NaNHandler = SaturatedCastNaNBehaviorReturnZero, | 102 class NaNHandler = SaturatedCastNaNBehaviorReturnZero, |
| 102 typename Src> | 103 typename Src> |
| 103 constexpr Dst saturated_cast(Src value) { | 104 constexpr Dst saturated_cast(Src value) { |
| 104 return std::numeric_limits<Dst>::is_iec559 | 105 return std::numeric_limits<Dst>::is_iec559 |
| 105 ? static_cast<Dst>(value) // Floating point optimization. | 106 ? static_cast<Dst>(value) // Floating point optimization. |
| 106 : internal::saturated_cast_impl<Dst, NaNHandler>( | 107 : internal::saturated_cast_impl<Dst, NaNHandler>( |
| 107 value, internal::DstRangeRelationToSrcRange<Dst>(value)); | 108 value, internal::DstRangeRelationToSrcRange<Dst>(value)); |
| 108 } | 109 } |
| 109 | 110 |
| 111 // The following macro attempts to determine if the passed expression is a | |
| 112 // compile-time constant. GCC and clang have a compiler intrinsic for this, | |
| 113 // but MSVS needs to use a hack where compile-time expression evaluation will | |
| 114 // generate a zero constant that will trigger a different function overload | |
| 115 // than a compile-time variable would. | |
| 116 #if defined(__GNUC__) || defined(__clang__) | |
| 117 #define IS_COMPILE_TIME_CONSTANT(V) __builtin_constant_p(V) | |
| 118 #else | |
| 119 struct ConstTest { | |
| 120 struct PlaceHolder { | |
| 121 PlaceHolder(int64_t x) {} | |
| 122 }; | |
| 123 static int8_t Test(void*) { return int8_t(); } | |
| 124 static int64_t Test(PlaceHolder) { return int64_t(); } | |
| 125 }; | |
| 126 | |
| 127 #define IS_COMPILE_TIME_CONSTANT(V) \ | |
| 128 (std::is_same<int8_t, decltype(internal::ConstTest::Test((V) - (V)))>::value) | |
| 129 #endif | |
| 130 | |
| 131 // The test goes here because we undef the macro when we're done with it. | |
| 132 inline void TestCompileTimeConstantSupport() { | |
| 133 const int kCompileTimeConstant = 10; | |
| 134 int compile_time_variable = rand(); | |
| 135 static_assert(IS_COMPILE_TIME_CONSTANT(std::numeric_limits<int>::is_signed), | |
| 136 ""); | |
| 137 static_assert(IS_COMPILE_TIME_CONSTANT(kCompileTimeConstant), ""); | |
| 138 static_assert(!IS_COMPILE_TIME_CONSTANT(compile_time_variable), ""); | |
| 139 (void)compile_time_variable; | |
| 140 } | |
| 141 | |
| 110 // strict_cast<> is analogous to static_cast<> for numeric types, except that | 142 // strict_cast<> is analogous to static_cast<> for numeric types, except that |
| 111 // it will cause a compile failure if the destination type is not large enough | 143 // it will cause a compile failure if the destination type is not large enough |
| 112 // to contain any value in the source type. It performs no runtime checking. | 144 // to contain any value in the source type. It performs no runtime checking. |
| 113 template <typename Dst, typename Src> | 145 template <typename Dst, typename Src> |
| 114 constexpr Dst strict_cast(Src value) { | 146 constexpr Dst strict_cast(Src value) { |
| 115 static_assert(std::numeric_limits<Src>::is_specialized, | 147 static_assert(std::numeric_limits<Src>::is_specialized, |
| 116 "Argument must be numeric."); | 148 "Argument must be numeric."); |
| 117 static_assert(std::numeric_limits<Dst>::is_specialized, | 149 static_assert(std::numeric_limits<Dst>::is_specialized, |
| 118 "Result must be numeric."); | 150 "Result must be numeric."); |
| 119 static_assert((internal::StaticDstRangeRelationToSrcRange<Dst, Src>::value == | 151 |
| 120 internal::NUMERIC_RANGE_CONTAINED), | 152 // We try to make compile-time constants just work regardless of type. |
| 121 "The numeric conversion is out of range for this type. You " | 153 static_assert( |
| 122 "should probably use one of the following conversion " | 154 IS_COMPILE_TIME_CONSTANT(value) |
| 123 "mechanisms on the value you want to pass:\n" | 155 ? IsValueInRangeForNumericType<Dst>(value) |
| 124 "- base::checked_cast\n" | 156 : internal::StaticDstRangeRelationToSrcRange<Dst, Src>::value == |
| 125 "- base::saturated_cast\n" | 157 internal::NUMERIC_RANGE_CONTAINED, |
| 126 "- base::CheckedNumeric"); | 158 "The source type is out of range for the destination type"); |
| 127 | 159 |
| 128 return static_cast<Dst>(value); | 160 return static_cast<Dst>(value); |
| 129 } | 161 } |
| 130 | 162 |
| 163 #undef IS_COMPILE_TIME_CONSTANT | |
| 164 | |
| 131 // StrictNumeric implements compile time range checking between numeric types by | 165 // StrictNumeric implements compile time range checking between numeric types by |
| 132 // wrapping assignment operations in a strict_cast. This class is intended to be | 166 // wrapping assignment operations in a strict_cast. This class is intended to be |
| 133 // used for function arguments and return types, to ensure the destination type | 167 // used for function arguments and return types, to ensure the destination type |
| 134 // can always contain the source type. This is essentially the same as enforcing | 168 // can always contain the source type. This is essentially the same as enforcing |
| 135 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied | 169 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied |
| 136 // incrementally at API boundaries, making it easier to convert code so that it | 170 // incrementally at API boundaries, making it easier to convert code so that it |
| 137 // compiles cleanly with truncation warnings enabled. | 171 // compiles cleanly with truncation warnings enabled. |
| 138 // This template should introduce no runtime overhead, but it also provides no | 172 // This template should introduce no runtime overhead, but it also provides no |
| 139 // runtime checking of any of the associated mathematical operations. Use | 173 // runtime checking of any of the associated mathematical operations. Use |
| 140 // CheckedNumeric for runtime range checks of the actual value being assigned. | 174 // CheckedNumeric for runtime range checks of the actual value being assigned. |
| 141 template <typename T> | 175 template <typename T> |
| 142 class StrictNumeric { | 176 class StrictNumeric { |
| 143 public: | 177 public: |
| 144 typedef T type; | 178 typedef T type; |
| 145 | 179 |
| 146 constexpr StrictNumeric() : value_(0) {} | 180 constexpr StrictNumeric() : value_(0) {} |
| 147 | 181 |
| 148 // Copy constructor. | 182 // Copy constructor. |
| 149 template <typename Src> | 183 template <typename Src> |
| 150 constexpr StrictNumeric(const StrictNumeric<Src>& rhs) | 184 constexpr StrictNumeric(const StrictNumeric<Src>& rhs) |
| 151 : value_(strict_cast<T>(rhs.value_)) {} | 185 : value_(strict_cast<T>(rhs.value_)) {} |
| 152 | 186 |
| 153 // This is not an explicit constructor because we implicitly upgrade regular | 187 // This is not an explicit constructor because we implicitly upgrade regular |
| 154 // numerics to StrictNumerics to make them easier to use. | 188 // numerics to StrictNumerics to make them easier to use. |
| 155 template <typename Src> | 189 template <typename Src> |
| 156 constexpr StrictNumeric(Src value) | 190 constexpr StrictNumeric(Src value) |
| 157 : value_(strict_cast<T>(value)) {} | 191 : value_(strict_cast<T>(value)) {} |
| 158 | 192 |
| 159 // The numeric cast operator basically handles all the magic. | 193 // The numeric cast operator basically handles all the magic. |
| 160 template <typename Dst> | 194 template <typename Dst, |
| 195 typename std::enable_if< | |
| 196 ArithmeticOrUnderlyingEnum<Dst>::value>::type* = nullptr> | |
| 161 constexpr operator Dst() const { | 197 constexpr operator Dst() const { |
| 162 return strict_cast<Dst>(value_); | 198 return strict_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_); |
| 163 } | 199 } |
| 164 | 200 |
| 165 private: | 201 private: |
| 166 const T value_; | 202 const T value_; |
| 167 }; | 203 }; |
| 168 | 204 |
| 205 template <typename T> | |
| 206 std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) { | |
| 207 os << static_cast<T>(value); | |
| 208 return os; | |
| 209 } | |
| 210 | |
| 211 // We allow simple pointer arithmetic. | |
|
Tom Sepez
2016/11/29 20:06:26
For extra credit: Can we make this blow up if R is
jschuh
2016/11/29 21:04:47
It would be very easy to just call the correspondi
jschuh
2016/11/30 23:38:52
Okay, I decided that wrapping here is always unsaf
| |
| 212 template <typename L, typename R> | |
| 213 constexpr L* operator+(L* lhs, const StrictNumeric<R>& rhs) { | |
| 214 return lhs + static_cast<R>(rhs); | |
| 215 } | |
| 216 | |
| 217 template <typename L, typename R> | |
| 218 constexpr L* operator-(L* lhs, const StrictNumeric<R>& rhs) { | |
| 219 return lhs - static_cast<R>(rhs); | |
| 220 } | |
| 221 | |
| 222 #define STRICT_COMPARISON_OP(NAME, OP) \ | |
| 223 template <typename L, typename R, \ | |
| 224 typename std::enable_if< \ | |
| 225 internal::IsStrictOp<L, R>::value>::type* = nullptr> \ | |
| 226 constexpr bool operator OP(const L lhs, const R rhs) { \ | |
| 227 return SafeCompare<NAME, typename UnderlyingType<L>::type, \ | |
| 228 typename UnderlyingType<R>::type>(lhs, rhs); \ | |
| 229 } | |
| 230 | |
| 231 STRICT_COMPARISON_OP(IsLess, <); | |
| 232 STRICT_COMPARISON_OP(IsLessOrEqual, <=); | |
| 233 STRICT_COMPARISON_OP(IsGreater, >); | |
| 234 STRICT_COMPARISON_OP(IsGreaterOrEqual, >=); | |
| 235 STRICT_COMPARISON_OP(IsEqual, ==); | |
| 236 STRICT_COMPARISON_OP(IsNotEqual, !=); | |
| 237 | |
| 238 #undef STRICT_COMPARISON_OP | |
| 239 }; | |
| 240 | |
| 241 using internal::strict_cast; | |
| 242 using internal::saturated_cast; | |
| 243 using internal::StrictNumeric; | |
| 244 | |
| 169 // Explicitly make a shorter size_t typedef for convenience. | 245 // Explicitly make a shorter size_t typedef for convenience. |
| 170 typedef StrictNumeric<size_t> SizeT; | 246 typedef StrictNumeric<size_t> SizeT; |
| 171 | 247 |
| 172 } // namespace base | 248 } // namespace base |
| 173 | 249 |
| 174 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_ | 250 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_ |
| OLD | NEW |