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