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