| 6 | #define BASE_NUMERICS_SAFE_CONVERSIONS_H_ |
| 7 |
| 8 | #include <stddef.h> |
| 9 |
| 10 | #include <limits> |
| 11 | #include <type_traits> |
| 12 |
| 13 | #include "base/numerics/safe_conversions_impl.h" |
| 14 |
| 15 | #if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__)) |
| 16 | #include "base/numerics/safe_conversions_arm_impl.h" |
| 17 | #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1) |
| 18 | #else |
| 19 | #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0) |
| 20 | #endif |
| 21 |
| 22 | #if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS |
| 23 | #include <ostream> |
| 24 | #endif |
| 25 |
| 26 | namespace base { |
| 27 | namespace internal { |
| 28 |
| 29 | #if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS |
| 30 | template <typename Dst, typename Src> |
| 31 | struct SaturateFastAsmOp { |
| 32 | static const bool is_supported = false; |
| 33 | static constexpr Dst Do(Src) { |
| 34 | // Force a compile failure if instantiated. |
| 35 | return CheckOnFailure::template HandleFailure<Dst>(); |
| 36 | } |
| 37 | }; |
| 38 | #endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS |
| 39 | #undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS |
| 40 |
| 41 | // The following special case a few specific integer conversions where we can |
| 42 | // eke out better performance than range checking. |
| 43 | template <typename Dst, typename Src, typename Enable = void> |
| 44 | struct IsValueInRangeFastOp { |
| 45 | static const bool is_supported = false; |
| 46 | static constexpr bool Do(Src value) { |
| 47 | // Force a compile failure if instantiated. |
| 48 | return CheckOnFailure::template HandleFailure<bool>(); |
| 49 | } |
| 50 | }; |
| 51 |
| 52 | // Signed to signed range comparison. |
| 53 | template <typename Dst, typename Src> |
| 54 | struct IsValueInRangeFastOp< |
| 55 | Dst, |
| 56 | Src, |
| 57 | typename std::enable_if< |
| 58 | std::is_integral<Dst>::value && std::is_integral<Src>::value && |
| 59 | std::is_signed<Dst>::value && std::is_signed<Src>::value && |
| 60 | !IsTypeInRangeForNumericType<Dst, Src>::value>::type> { |
| 61 | static const bool is_supported = true; |
| 62 |
| 63 | static constexpr bool Do(Src value) { |
| 64 | // Just downcast to the smaller type, sign extend it back to the original |
| 65 | // type, and then see if it matches the original value. |
| 66 | return value == static_cast<Dst>(value); |
| 67 | } |
| 68 | }; |
| 69 |
| 70 | // Signed to unsigned range comparison. |
| 71 | template <typename Dst, typename Src> |
| 72 | struct IsValueInRangeFastOp< |
| 73 | Dst, |
| 74 | Src, |
| 75 | typename std::enable_if< |
| 76 | std::is_integral<Dst>::value && std::is_integral<Src>::value && |
| 77 | !std::is_signed<Dst>::value && std::is_signed<Src>::value && |
| 78 | !IsTypeInRangeForNumericType<Dst, Src>::value>::type> { |
| 79 | static const bool is_supported = true; |
| 80 |
| 81 | static constexpr bool Do(Src value) { |
| 82 | // We cast a signed as unsigned to overflow negative values to the top, |
| 83 | // then compare against whichever maximum is smaller, as our upper bound. |
| 84 | return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>()); |
| 85 | } |
| 86 | }; |
| 87 |
| 88 | // Convenience function that returns true if the supplied value is in range |
| 89 | // for the destination type. |
| 90 | template <typename Dst, typename Src> |
| 91 | constexpr bool IsValueInRangeForNumericType(Src value) { |
| 92 | using SrcType = typename internal::UnderlyingType<Src>::type; |
| 93 | return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported |
| 94 | ? internal::IsValueInRangeFastOp<Dst, SrcType>::Do( |
| 95 | static_cast<SrcType>(value)) |
| 96 | : internal::DstRangeRelationToSrcRange<Dst>( |
| 97 | static_cast<SrcType>(value)) |
| 98 | .IsValid(); |
| 99 | } |
| 100 |
| 101 | // checked_cast<> is analogous to static_cast<> for numeric types, |
| 102 | // except that it CHECKs that the specified numeric conversion will not |
| 103 | // overflow or underflow. NaN source will always trigger a CHECK. |
| 104 | template <typename Dst, |
| 105 | class CheckHandler = internal::CheckOnFailure, |
| 106 | typename Src> |
| 107 | constexpr Dst checked_cast(Src value) { |
| 108 | // This throws a compile-time error on evaluating the constexpr if it can be |
| 109 | // determined at compile-time as failing, otherwise it will CHECK at runtime. |
| 110 | using SrcType = typename internal::UnderlyingType<Src>::type; |
| 111 | return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value))) |
| 112 | ? static_cast<Dst>(static_cast<SrcType>(value)) |
| 113 | : CheckHandler::template HandleFailure<Dst>(); |
| 114 | } |
| 115 |
| 116 | // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN. |
| 117 | // You may provide your own limits (e.g. to saturated_cast) so long as you |
| 118 | // implement all of the static constexpr member functions in the class below. |
| 119 | template <typename T> |
| 120 | struct SaturationDefaultLimits : public std::numeric_limits<T> { |
| 121 | static constexpr T NaN() { |
| 122 | return std::numeric_limits<T>::has_quiet_NaN |
| 123 | ? std::numeric_limits<T>::quiet_NaN() |
| 124 | : T(); |
| 125 | } |
| 126 | using std::numeric_limits<T>::max; |
| 127 | static constexpr T Overflow() { |
| 128 | return std::numeric_limits<T>::has_infinity |
| 129 | ? std::numeric_limits<T>::infinity() |
| 130 | : std::numeric_limits<T>::max(); |
| 131 | } |
| 132 | using std::numeric_limits<T>::lowest; |
| 133 | static constexpr T Underflow() { |
| 134 | return std::numeric_limits<T>::has_infinity |
| 135 | ? std::numeric_limits<T>::infinity() * -1 |
| 136 | : std::numeric_limits<T>::lowest(); |
| 137 | } |
| 138 | }; |
| 139 |
| 140 | template <typename Dst, template <typename> class S, typename Src> |
| 141 | constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) { |
| 142 | // For some reason clang generates much better code when the branch is |
| 143 | // structured exactly this way, rather than a sequence of checks. |
| 144 | return !constraint.IsOverflowFlagSet() |
| 145 | ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value) |
| 146 | : S<Dst>::Underflow()) |
| 147 | // Skip this check for integral Src, which cannot be NaN. |
| 148 | : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet() |
| 149 | ? S<Dst>::Overflow() |
| 150 | : S<Dst>::NaN()); |
| 151 | } |
| 152 |
| 153 | // We can reduce the number of conditions and get slightly better performance |
| 154 | // for normal signed and unsigned integer ranges. And in the specific case of |
| 155 | // Arm, we can use the optimized saturation instructions. |
| 156 | template <typename Dst, typename Src, typename Enable = void> |
| 157 | struct SaturateFastOp { |
| 158 | static const bool is_supported = false; |
| 159 | static constexpr Dst Do(Src value) { |
| 160 | // Force a compile failure if instantiated. |
| 161 | return CheckOnFailure::template HandleFailure<Dst>(); |
| 162 | } |
| 163 | }; |
| 164 |
| 165 | template <typename Dst, typename Src> |
| 166 | struct SaturateFastOp< |
| 167 | Dst, |
| 168 | Src, |
| 169 | typename std::enable_if<std::is_integral<Src>::value && |
| 170 | std::is_integral<Dst>::value && |
| 171 | SaturateFastAsmOp<Dst, Src>::is_supported>::type> { |
| 172 | static const bool is_supported = true; |
| 173 | static Dst Do(Src value) { return SaturateFastAsmOp<Dst, Src>::Do(value); } |
| 174 | }; |
| 175 |
| 176 | template <typename Dst, typename Src> |
| 177 | struct SaturateFastOp< |
| 178 | Dst, |
| 179 | Src, |
| 180 | typename std::enable_if<std::is_integral<Src>::value && |
| 181 | std::is_integral<Dst>::value && |
| 182 | !SaturateFastAsmOp<Dst, Src>::is_supported>::type> { |
| 183 | static const bool is_supported = true; |
| 184 | static Dst Do(Src value) { |
| 185 | // The exact order of the following is structured to hit the correct |
| 186 | // optimization heuristics across compilers. Do not change without |
| 187 | // checking the emitted code. |
| 188 | Dst saturated = CommonMaxOrMin<Dst, Src>( |
| 189 | IsMaxInRangeForNumericType<Dst, Src>() || |
| 190 | (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value))); |
| 191 | return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value)) |
| 192 | ? static_cast<Dst>(value) |
| 193 | : saturated; |
| 194 | } |
| 195 | }; |
| 196 |
| 197 | // saturated_cast<> is analogous to static_cast<> for numeric types, except |
| 198 | // that the specified numeric conversion will saturate by default rather than |
| 199 | // overflow or underflow, and NaN assignment to an integral will return 0. |
| 200 | // All boundary condition behaviors can be overriden with a custom handler. |
| 201 | template <typename Dst, |
| 202 | template <typename> class SaturationHandler = SaturationDefaultLimits, |
| 203 | typename Src> |
| 204 | constexpr Dst saturated_cast(Src value) { |
| 205 | using SrcType = typename UnderlyingType<Src>::type; |
| 206 | return !IsCompileTimeConstant(value) && |
| 207 | SaturateFastOp<Dst, SrcType>::is_supported && |
| 208 | std::is_same<SaturationHandler<Dst>, |
| 209 | SaturationDefaultLimits<Dst>>::value |
| 210 | ? SaturateFastOp<Dst, SrcType>::Do(static_cast<SrcType>(value)) |
| 211 | : saturated_cast_impl<Dst, SaturationHandler, SrcType>( |
| 212 | static_cast<SrcType>(value), |
| 213 | DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>( |
| 214 | static_cast<SrcType>(value))); |
| 215 | } |
| 216 |
| 217 | // strict_cast<> is analogous to static_cast<> for numeric types, except that |
| 218 | // it will cause a compile failure if the destination type is not large enough |
| 219 | // to contain any value in the source type. It performs no runtime checking. |
| 220 | template <typename Dst, typename Src> |
| 221 | constexpr Dst strict_cast(Src value) { |
| 222 | using SrcType = typename UnderlyingType<Src>::type; |
| 223 | static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric."); |
| 224 | static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric."); |
| 225 |
| 226 | // If you got here from a compiler error, it's because you tried to assign |
| 227 | // from a source type to a destination type that has insufficient range. |
| 228 | // The solution may be to change the destination type you're assigning to, |
| 229 | // and use one large enough to represent the source. |
| 230 | // Alternatively, you may be better served with the checked_cast<> or |
| 231 | // saturated_cast<> template functions for your particular use case. |
| 232 | static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value == |
| 233 | NUMERIC_RANGE_CONTAINED, |
| 234 | "The source type is out of range for the destination type. " |
| 235 | "Please see strict_cast<> comments for more information."); |
| 236 |
| 237 | return static_cast<Dst>(static_cast<SrcType>(value)); |
| 238 | } |
| 239 |
| 240 | // Some wrappers to statically check that a type is in range. |
| 241 | template <typename Dst, typename Src, class Enable = void> |
| 242 | struct IsNumericRangeContained { |
| 243 | static const bool value = false; |
| 244 | }; |
| 245 |
| 246 | template <typename Dst, typename Src> |
| 247 | struct IsNumericRangeContained< |
| 248 | Dst, |
| 249 | Src, |
| 250 | typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value && |
| 251 | ArithmeticOrUnderlyingEnum<Src>::value>::type> { |
| 252 | static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value == |
| 253 | NUMERIC_RANGE_CONTAINED; |
| 254 | }; |
| 255 |
| 256 | // StrictNumeric implements compile time range checking between numeric types by |
| 257 | // wrapping assignment operations in a strict_cast. This class is intended to be |
| 258 | // used for function arguments and return types, to ensure the destination type |
| 259 | // can always contain the source type. This is essentially the same as enforcing |
| 260 | // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied |
| 261 | // incrementally at API boundaries, making it easier to convert code so that it |
| 262 | // compiles cleanly with truncation warnings enabled. |
| 263 | // This template should introduce no runtime overhead, but it also provides no |
| 264 | // runtime checking of any of the associated mathematical operations. Use |
| 265 | // CheckedNumeric for runtime range checks of the actual value being assigned. |
| 266 | template <typename T> |
| 267 | class StrictNumeric { |
| 268 | public: |
| 269 | using type = T; |
| 270 |
| 271 | constexpr StrictNumeric() : value_(0) {} |
| 272 |
| 273 | // Copy constructor. |
| 274 | template <typename Src> |
| 275 | constexpr StrictNumeric(const StrictNumeric<Src>& rhs) |
| 276 | : value_(strict_cast<T>(rhs.value_)) {} |
| 277 |
| 278 | // This is not an explicit constructor because we implicitly upgrade regular |
| 279 | // numerics to StrictNumerics to make them easier to use. |
| 280 | template <typename Src> |
| 281 | constexpr StrictNumeric(Src value) // NOLINT(runtime/explicit) |
| 282 | : value_(strict_cast<T>(value)) {} |
| 283 |
| 284 | // If you got here from a compiler error, it's because you tried to assign |
| 285 | // from a source type to a destination type that has insufficient range. |
| 286 | // The solution may be to change the destination type you're assigning to, |
| 287 | // and use one large enough to represent the source. |
| 288 | // If you're assigning from a CheckedNumeric<> class, you may be able to use |
| 289 | // the AssignIfValid() member function, specify a narrower destination type to |
| 290 | // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one |
| 291 | // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)). |
| 292 | // If you've encountered an _ambiguous overload_ you can use a static_cast<> |
| 293 | // to explicitly cast the result to the destination type. |
| 294 | // If none of that works, you may be better served with the checked_cast<> or |
| 295 | // saturated_cast<> template functions for your particular use case. |
| 296 | template <typename Dst, |
| 297 | typename std::enable_if< |
| 298 | IsNumericRangeContained<Dst, T>::value>::type* = nullptr> |
| 299 | constexpr operator Dst() const { |
| 300 | return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_); |
| 301 | } |
| 302 |
| 303 | private: |
| 304 | const T value_; |
| 305 | }; |
| 306 |
| 307 | // Convience wrapper returns a StrictNumeric from the provided arithmetic type. |
| 308 | template <typename T> |
| 309 | constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum( |
| 310 | const T value) { |
| 311 | return value; |
| 312 | } |
| 313 |
| 314 | #if !BASE_NUMERICS_DISABLE_OSTREAM_OPERATORS |
| 315 | // Overload the ostream output operator to make logging work nicely. |
| 316 | template <typename T> |
| 317 | std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) { |
| 318 | os << static_cast<T>(value); |
| 319 | return os; |
| 320 | } |
| 321 | #endif |
| 322 |
| 323 | #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \ |
| 324 | template <typename L, typename R, \ |
| 325 | typename std::enable_if< \ |
| 326 | internal::Is##CLASS##Op<L, R>::value>::type* = nullptr> \ |
| 327 | constexpr bool operator OP(const L lhs, const R rhs) { \ |
| 328 | return SafeCompare<NAME, typename UnderlyingType<L>::type, \ |
| 329 | typename UnderlyingType<R>::type>(lhs, rhs); \ |
| 330 | } |
| 331 |
| 332 | BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <) |
| 333 | BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=) |
| 334 | BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >) |
| 335 | BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=) |
| 336 | BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==) |
| 337 | BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=) |
| 338 |
| 339 | } // namespace internal |
| 340 |
| 341 | using internal::as_signed; |
| 342 | using internal::as_unsigned; |
| 343 | using internal::checked_cast; |
| 344 | using internal::strict_cast; |
| 345 | using internal::saturated_cast; |
| 346 | using internal::SafeUnsignedAbs; |
| 347 | using internal::StrictNumeric; |
| 348 | using internal::MakeStrictNum; |
| 349 | using internal::IsValueInRangeForNumericType; |
| 350 | using internal::IsTypeInRangeForNumericType; |
| 351 | using internal::IsValueNegative; |
| 352 |
| 353 | // Explicitly make a shorter size_t alias for convenience. |
| 354 | using SizeT = StrictNumeric<size_t>; |
| 355 |
| 356 | } // namespace base |
| 357 |
| 358 | #endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_ |
| 359 |