safe_conversions.h (16807B)
1 // Copyright 2014 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_NUMERICS_SAFE_CONVERSIONS_H_ 6 #define BASE_NUMERICS_SAFE_CONVERSIONS_H_ 7 8 #include <stddef.h> 9 10 #include <cmath> 11 #include <limits> 12 #include <type_traits> 13 14 #include "base/numerics/safe_conversions_impl.h" 15 16 #if defined(__ARMEL__) && !defined(__native_client__) 17 #include "base/numerics/safe_conversions_arm_impl.h" 18 #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1) 19 #else 20 #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0) 21 #endif 22 23 namespace base { 24 namespace internal { 25 26 #if !BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS 27 template <typename Dst, typename Src> 28 struct SaturateFastAsmOp { 29 static constexpr bool is_supported = false; 30 static constexpr Dst Do(Src) { 31 // Force a compile failure if instantiated. 32 return CheckOnFailure::template HandleFailure<Dst>(); 33 } 34 }; 35 #endif // BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS 36 #undef BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS 37 38 // The following special case a few specific integer conversions where we can 39 // eke out better performance than range checking. 40 template <typename Dst, typename Src, typename Enable = void> 41 struct IsValueInRangeFastOp { 42 static constexpr bool is_supported = false; 43 static constexpr bool Do(Src value) { 44 // Force a compile failure if instantiated. 45 return CheckOnFailure::template HandleFailure<bool>(); 46 } 47 }; 48 49 // Signed to signed range comparison. 50 template <typename Dst, typename Src> 51 struct IsValueInRangeFastOp< 52 Dst, 53 Src, 54 std::enable_if_t<std::is_integral_v<Dst> && std::is_integral_v<Src> && 55 std::is_signed_v<Dst> && std::is_signed_v<Src> && 56 !IsTypeInRangeForNumericType<Dst, Src>::value>> { 57 static constexpr bool is_supported = true; 58 59 static constexpr bool Do(Src value) { 60 // Just downcast to the smaller type, sign extend it back to the original 61 // type, and then see if it matches the original value. 62 return value == static_cast<Dst>(value); 63 } 64 }; 65 66 // Signed to unsigned range comparison. 67 template <typename Dst, typename Src> 68 struct IsValueInRangeFastOp< 69 Dst, 70 Src, 71 std::enable_if_t<std::is_integral_v<Dst> && std::is_integral_v<Src> && 72 !std::is_signed_v<Dst> && std::is_signed_v<Src> && 73 !IsTypeInRangeForNumericType<Dst, Src>::value>> { 74 static constexpr bool is_supported = true; 75 76 static constexpr bool Do(Src value) { 77 // We cast a signed as unsigned to overflow negative values to the top, 78 // then compare against whichever maximum is smaller, as our upper bound. 79 return as_unsigned(value) <= as_unsigned(CommonMax<Src, Dst>()); 80 } 81 }; 82 83 // Convenience function that returns true if the supplied value is in range 84 // for the destination type. 85 template <typename Dst, typename Src> 86 constexpr bool IsValueInRangeForNumericType(Src value) { 87 using SrcType = typename internal::UnderlyingType<Src>::type; 88 return internal::IsValueInRangeFastOp<Dst, SrcType>::is_supported 89 ? internal::IsValueInRangeFastOp<Dst, SrcType>::Do( 90 static_cast<SrcType>(value)) 91 : internal::DstRangeRelationToSrcRange<Dst>( 92 static_cast<SrcType>(value)) 93 .IsValid(); 94 } 95 96 // checked_cast<> is analogous to static_cast<> for numeric types, 97 // except that it CHECKs that the specified numeric conversion will not 98 // overflow or underflow. NaN source will always trigger a CHECK. 99 template <typename Dst, 100 class CheckHandler = internal::CheckOnFailure, 101 typename Src> 102 constexpr Dst checked_cast(Src value) { 103 // This throws a compile-time error on evaluating the constexpr if it can be 104 // determined at compile-time as failing, otherwise it will CHECK at runtime. 105 using SrcType = typename internal::UnderlyingType<Src>::type; 106 return BASE_NUMERICS_LIKELY((IsValueInRangeForNumericType<Dst>(value))) 107 ? static_cast<Dst>(static_cast<SrcType>(value)) 108 : CheckHandler::template HandleFailure<Dst>(); 109 } 110 111 // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN. 112 // You may provide your own limits (e.g. to saturated_cast) so long as you 113 // implement all of the static constexpr member functions in the class below. 114 template <typename T> 115 struct SaturationDefaultLimits : public std::numeric_limits<T> { 116 static constexpr T NaN() { 117 if constexpr (std::numeric_limits<T>::has_quiet_NaN) { 118 return std::numeric_limits<T>::quiet_NaN(); 119 } else { 120 return T(); 121 } 122 } 123 using std::numeric_limits<T>::max; 124 static constexpr T Overflow() { 125 if constexpr (std::numeric_limits<T>::has_infinity) { 126 return std::numeric_limits<T>::infinity(); 127 } else { 128 return std::numeric_limits<T>::max(); 129 } 130 } 131 using std::numeric_limits<T>::lowest; 132 static constexpr T Underflow() { 133 if constexpr (std::numeric_limits<T>::has_infinity) { 134 return std::numeric_limits<T>::infinity() * -1; 135 } else { 136 return std::numeric_limits<T>::lowest(); 137 } 138 } 139 }; 140 141 template <typename Dst, template <typename> class S, typename Src> 142 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) { 143 // For some reason clang generates much better code when the branch is 144 // structured exactly this way, rather than a sequence of checks. 145 return !constraint.IsOverflowFlagSet() 146 ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value) 147 : S<Dst>::Underflow()) 148 // Skip this check for integral Src, which cannot be NaN. 149 : (std::is_integral_v<Src> || !constraint.IsUnderflowFlagSet() 150 ? S<Dst>::Overflow() 151 : S<Dst>::NaN()); 152 } 153 154 // We can reduce the number of conditions and get slightly better performance 155 // for normal signed and unsigned integer ranges. And in the specific case of 156 // Arm, we can use the optimized saturation instructions. 157 template <typename Dst, typename Src, typename Enable = void> 158 struct SaturateFastOp { 159 static constexpr bool is_supported = false; 160 static constexpr Dst Do(Src value) { 161 // Force a compile failure if instantiated. 162 return CheckOnFailure::template HandleFailure<Dst>(); 163 } 164 }; 165 166 template <typename Dst, typename Src> 167 struct SaturateFastOp< 168 Dst, 169 Src, 170 std::enable_if_t<std::is_integral_v<Src> && std::is_integral_v<Dst> && 171 SaturateFastAsmOp<Dst, Src>::is_supported>> { 172 static constexpr bool is_supported = true; 173 static constexpr Dst Do(Src value) { 174 return SaturateFastAsmOp<Dst, Src>::Do(value); 175 } 176 }; 177 178 template <typename Dst, typename Src> 179 struct SaturateFastOp< 180 Dst, 181 Src, 182 std::enable_if_t<std::is_integral_v<Src> && std::is_integral_v<Dst> && 183 !SaturateFastAsmOp<Dst, Src>::is_supported>> { 184 static constexpr bool is_supported = true; 185 static constexpr Dst Do(Src value) { 186 // The exact order of the following is structured to hit the correct 187 // optimization heuristics across compilers. Do not change without 188 // checking the emitted code. 189 const Dst saturated = CommonMaxOrMin<Dst, Src>( 190 IsMaxInRangeForNumericType<Dst, Src>() || 191 (!IsMinInRangeForNumericType<Dst, Src>() && IsValueNegative(value))); 192 return BASE_NUMERICS_LIKELY(IsValueInRangeForNumericType<Dst>(value)) 193 ? static_cast<Dst>(value) 194 : saturated; 195 } 196 }; 197 198 // saturated_cast<> is analogous to static_cast<> for numeric types, except 199 // that the specified numeric conversion will saturate by default rather than 200 // overflow or underflow, and NaN assignment to an integral will return 0. 201 // All boundary condition behaviors can be overridden with a custom handler. 202 template <typename Dst, 203 template <typename> class SaturationHandler = SaturationDefaultLimits, 204 typename Src> 205 constexpr Dst saturated_cast(Src value) { 206 using SrcType = typename UnderlyingType<Src>::type; 207 return !IsConstantEvaluated() && SaturateFastOp<Dst, SrcType>::is_supported && 208 std::is_same_v<SaturationHandler<Dst>, 209 SaturationDefaultLimits<Dst>> 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_v<Dst>, "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 constexpr bool value = false; 244 }; 245 246 template <typename Dst, typename Src> 247 struct IsNumericRangeContained< 248 Dst, 249 Src, 250 std::enable_if_t<ArithmeticOrUnderlyingEnum<Dst>::value && 251 ArithmeticOrUnderlyingEnum<Src>::value>> { 252 static constexpr bool value = 253 StaticDstRangeRelationToSrcRange<Dst, Src>::value == 254 NUMERIC_RANGE_CONTAINED; 255 }; 256 257 // StrictNumeric implements compile time range checking between numeric types by 258 // wrapping assignment operations in a strict_cast. This class is intended to be 259 // used for function arguments and return types, to ensure the destination type 260 // can always contain the source type. This is essentially the same as enforcing 261 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied 262 // incrementally at API boundaries, making it easier to convert code so that it 263 // compiles cleanly with truncation warnings enabled. 264 // This template should introduce no runtime overhead, but it also provides no 265 // runtime checking of any of the associated mathematical operations. Use 266 // CheckedNumeric for runtime range checks of the actual value being assigned. 267 template <typename T> 268 class StrictNumeric { 269 public: 270 using type = T; 271 272 constexpr StrictNumeric() : value_(0) {} 273 274 // Copy constructor. 275 template <typename Src> 276 constexpr StrictNumeric(const StrictNumeric<Src>& rhs) 277 : value_(strict_cast<T>(rhs.value_)) {} 278 279 // Strictly speaking, this is not necessary, but declaring this allows class 280 // template argument deduction to be used so that it is possible to simply 281 // write `StrictNumeric(777)` instead of `StrictNumeric<int>(777)`. 282 // NOLINTNEXTLINE(google-explicit-constructor) 283 constexpr StrictNumeric(T value) : value_(value) {} 284 285 // This is not an explicit constructor because we implicitly upgrade regular 286 // numerics to StrictNumerics to make them easier to use. 287 template <typename Src> 288 // NOLINTNEXTLINE(google-explicit-constructor) 289 constexpr StrictNumeric(Src value) : value_(strict_cast<T>(value)) {} 290 291 // If you got here from a compiler error, it's because you tried to assign 292 // from a source type to a destination type that has insufficient range. 293 // The solution may be to change the destination type you're assigning to, 294 // and use one large enough to represent the source. 295 // If you're assigning from a CheckedNumeric<> class, you may be able to use 296 // the AssignIfValid() member function, specify a narrower destination type to 297 // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one 298 // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)). 299 // If you've encountered an _ambiguous overload_ you can use a static_cast<> 300 // to explicitly cast the result to the destination type. 301 // If none of that works, you may be better served with the checked_cast<> or 302 // saturated_cast<> template functions for your particular use case. 303 template <typename Dst, 304 std::enable_if_t<IsNumericRangeContained<Dst, T>::value>* = nullptr> 305 constexpr operator Dst() const { 306 return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_); 307 } 308 309 private: 310 const T value_; 311 }; 312 313 // Convenience wrapper returns a StrictNumeric from the provided arithmetic 314 // type. 315 template <typename T> 316 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum( 317 const T value) { 318 return value; 319 } 320 321 #define BASE_NUMERIC_COMPARISON_OPERATORS(CLASS, NAME, OP) \ 322 template <typename L, typename R, \ 323 std::enable_if_t<internal::Is##CLASS##Op<L, R>::value>* = nullptr> \ 324 constexpr bool operator OP(const L lhs, const R rhs) { \ 325 return SafeCompare<NAME, typename UnderlyingType<L>::type, \ 326 typename UnderlyingType<R>::type>(lhs, rhs); \ 327 } 328 329 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLess, <) 330 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsLessOrEqual, <=) 331 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreater, >) 332 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsGreaterOrEqual, >=) 333 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsEqual, ==) 334 BASE_NUMERIC_COMPARISON_OPERATORS(Strict, IsNotEqual, !=) 335 336 } // namespace internal 337 338 using internal::as_signed; 339 using internal::as_unsigned; 340 using internal::checked_cast; 341 using internal::IsTypeInRangeForNumericType; 342 using internal::IsValueInRangeForNumericType; 343 using internal::IsValueNegative; 344 using internal::MakeStrictNum; 345 using internal::SafeUnsignedAbs; 346 using internal::saturated_cast; 347 using internal::strict_cast; 348 using internal::StrictNumeric; 349 350 // Explicitly make a shorter size_t alias for convenience. 351 using SizeT = StrictNumeric<size_t>; 352 353 // floating -> integral conversions that saturate and thus can actually return 354 // an integral type. 355 // 356 // Generally, what you want is saturated_cast<Dst>(std::nearbyint(x)), which 357 // rounds correctly according to IEEE-754 (round to nearest, ties go to nearest 358 // even number; this avoids bias). If your code is performance-critical 359 // and you are sure that you will never overflow, you can use std::lrint() 360 // or std::llrint(), which return a long or long long directly. 361 // 362 // Below are convenience functions around similar patterns, except that 363 // they round in nonstandard directions and will generally be slower. 364 365 // Rounds towards negative infinity (i.e., down). 366 template <typename Dst = int, 367 typename Src, 368 typename = std::enable_if_t<std::is_integral_v<Dst> && 369 std::is_floating_point_v<Src>>> 370 Dst ClampFloor(Src value) { 371 return saturated_cast<Dst>(std::floor(value)); 372 } 373 374 // Rounds towards positive infinity (i.e., up). 375 template <typename Dst = int, 376 typename Src, 377 typename = std::enable_if_t<std::is_integral_v<Dst> && 378 std::is_floating_point_v<Src>>> 379 Dst ClampCeil(Src value) { 380 return saturated_cast<Dst>(std::ceil(value)); 381 } 382 383 // Rounds towards nearest integer, with ties away from zero. 384 // This means that 0.5 will be rounded to 1 and 1.5 will be rounded to 2. 385 // Similarly, -0.5 will be rounded to -1 and -1.5 will be rounded to -2. 386 // 387 // This is normally not what you want accuracy-wise (it introduces a small bias 388 // away from zero), and it is not the fastest option, but it is frequently what 389 // existing code expects. Compare with saturated_cast<Dst>(std::nearbyint(x)) 390 // or std::lrint(x), which would round 0.5 and -0.5 to 0 but 1.5 to 2 and 391 // -1.5 to -2. 392 template <typename Dst = int, 393 typename Src, 394 typename = std::enable_if_t<std::is_integral_v<Dst> && 395 std::is_floating_point_v<Src>>> 396 Dst ClampRound(Src value) { 397 const Src rounded = std::round(value); 398 return saturated_cast<Dst>(rounded); 399 } 400 401 } // namespace base 402 403 #endif // BASE_NUMERICS_SAFE_CONVERSIONS_H_