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