Home | History | Annotate | Download | only in numerics
      1 // Copyright 2014 The Chromium Authors. All rights reserved.
      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 PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_CONVERSIONS_H_
      6 #define PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_CONVERSIONS_H_
      7 
      8 #include <stddef.h>
      9 
     10 #include <limits>
     11 #include <ostream>
     12 #include <type_traits>
     13 
     14 #include "third_party/base/numerics/safe_conversions_impl.h"
     15 
     16 namespace pdfium {
     17 namespace base {
     18 
     19 // The following are helper constexpr template functions and classes for safely
     20 // performing a range of conversions, assignments, and tests:
     21 //
     22 //  checked_cast<> - Analogous to static_cast<> for numeric types, except
     23 //      that it CHECKs that the specified numeric conversion will not overflow
     24 //      or underflow. NaN source will always trigger a CHECK.
     25 //      The default CHECK triggers a crash, but the handler can be overriden.
     26 //  saturated_cast<> - Analogous to static_cast<> for numeric types, except
     27 //      that it returns a saturated result when the specified numeric conversion
     28 //      would otherwise overflow or underflow. An NaN source returns 0 by
     29 //      default, but can be overridden to return a different result.
     30 //  strict_cast<> - Analogous to static_cast<> for numeric types, except that
     31 //      it will cause a compile failure if the destination type is not large
     32 //      enough to contain any value in the source type. It performs no runtime
     33 //      checking and thus introduces no runtime overhead.
     34 //  IsValueInRangeForNumericType<>() - A convenience function that returns true
     35 //      if the type supplied to the template parameter can represent the value
     36 //      passed as an argument to the function.
     37 //  IsValueNegative<>() - A convenience function that will accept any arithmetic
     38 //      type as an argument and will return whether the value is less than zero.
     39 //      Unsigned types always return false.
     40 //  SafeUnsignedAbs() - Returns the absolute value of the supplied integer
     41 //      parameter as an unsigned result (thus avoiding an overflow if the value
     42 //      is the signed, two's complement minimum).
     43 //  StrictNumeric<> - A wrapper type that performs assignments and copies via
     44 //      the strict_cast<> template, and can perform valid arithmetic comparisons
     45 //      across any range of arithmetic types. StrictNumeric is the return type
     46 //      for values extracted from a CheckedNumeric class instance. The raw
     47 //      arithmetic value is extracted via static_cast to the underlying type.
     48 //  MakeStrictNum() - Creates a new StrictNumeric from the underlying type of
     49 //      the supplied arithmetic or StrictNumeric type.
     50 
     51 // Convenience function that returns true if the supplied value is in range
     52 // for the destination type.
     53 template <typename Dst, typename Src>
     54 constexpr bool IsValueInRangeForNumericType(Src value) {
     55   return internal::DstRangeRelationToSrcRange<Dst>(value).IsValid();
     56 }
     57 
     58 // Forces a crash, like a CHECK(false). Used for numeric boundary errors.
     59 struct CheckOnFailure {
     60   template <typename T>
     61   static T HandleFailure() {
     62 #if defined(__GNUC__) || defined(__clang__)
     63     __builtin_trap();
     64 #else
     65     ((void)(*(volatile char*)0 = 0));
     66 #endif
     67     return T();
     68   }
     69 };
     70 
     71 // checked_cast<> is analogous to static_cast<> for numeric types,
     72 // except that it CHECKs that the specified numeric conversion will not
     73 // overflow or underflow. NaN source will always trigger a CHECK.
     74 template <typename Dst, class CheckHandler = CheckOnFailure, typename Src>
     75 constexpr Dst checked_cast(Src value) {
     76   // This throws a compile-time error on evaluating the constexpr if it can be
     77   // determined at compile-time as failing, otherwise it will CHECK at runtime.
     78   using SrcType = typename internal::UnderlyingType<Src>::type;
     79   return IsValueInRangeForNumericType<Dst, SrcType>(value)
     80              ? static_cast<Dst>(static_cast<SrcType>(value))
     81              : CheckHandler::template HandleFailure<Dst>();
     82 }
     83 
     84 // Default boundaries for integral/float: max/infinity, lowest/-infinity, 0/NaN.
     85 template <typename T>
     86 struct SaturationDefaultHandler {
     87   static constexpr T NaN() {
     88     return std::numeric_limits<T>::has_quiet_NaN
     89                ? std::numeric_limits<T>::quiet_NaN()
     90                : T();
     91   }
     92   static constexpr T max() { return std::numeric_limits<T>::max(); }
     93   static constexpr T Overflow() {
     94     return std::numeric_limits<T>::has_infinity
     95                ? std::numeric_limits<T>::infinity()
     96                : std::numeric_limits<T>::max();
     97   }
     98   static constexpr T lowest() { return std::numeric_limits<T>::lowest(); }
     99   static constexpr T Underflow() {
    100     return std::numeric_limits<T>::has_infinity
    101                ? std::numeric_limits<T>::infinity() * -1
    102                : std::numeric_limits<T>::lowest();
    103   }
    104 };
    105 
    106 namespace internal {
    107 
    108 template <typename Dst, template <typename> class S, typename Src>
    109 constexpr Dst saturated_cast_impl(Src value, RangeCheck constraint) {
    110   // For some reason clang generates much better code when the branch is
    111   // structured exactly this way, rather than a sequence of checks.
    112   return !constraint.IsOverflowFlagSet()
    113              ? (!constraint.IsUnderflowFlagSet() ? static_cast<Dst>(value)
    114                                                  : S<Dst>::Underflow())
    115              // Skip this check for integral Src, which cannot be NaN.
    116              : (std::is_integral<Src>::value || !constraint.IsUnderflowFlagSet()
    117                     ? S<Dst>::Overflow()
    118                     : S<Dst>::NaN());
    119 }
    120 
    121 // saturated_cast<> is analogous to static_cast<> for numeric types, except
    122 // that the specified numeric conversion will saturate by default rather than
    123 // overflow or underflow, and NaN assignment to an integral will return 0.
    124 // All boundary condition behaviors can be overriden with a custom handler.
    125 template <typename Dst,
    126           template <typename>
    127           class SaturationHandler = SaturationDefaultHandler,
    128           typename Src>
    129 constexpr Dst saturated_cast(Src value) {
    130   using SrcType = typename UnderlyingType<Src>::type;
    131   return saturated_cast_impl<Dst, SaturationHandler, SrcType>(
    132       value,
    133       DstRangeRelationToSrcRange<Dst, SaturationHandler, SrcType>(value));
    134 }
    135 
    136 // strict_cast<> is analogous to static_cast<> for numeric types, except that
    137 // it will cause a compile failure if the destination type is not large enough
    138 // to contain any value in the source type. It performs no runtime checking.
    139 template <typename Dst, typename Src>
    140 constexpr Dst strict_cast(Src value) {
    141   using SrcType = typename UnderlyingType<Src>::type;
    142   static_assert(UnderlyingType<Src>::is_numeric, "Argument must be numeric.");
    143   static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
    144 
    145   // If you got here from a compiler error, it's because you tried to assign
    146   // from a source type to a destination type that has insufficient range.
    147   // The solution may be to change the destination type you're assigning to,
    148   // and use one large enough to represent the source.
    149   // Alternatively, you may be better served with the checked_cast<> or
    150   // saturated_cast<> template functions for your particular use case.
    151   static_assert(StaticDstRangeRelationToSrcRange<Dst, SrcType>::value ==
    152                     NUMERIC_RANGE_CONTAINED,
    153                 "The source type is out of range for the destination type. "
    154                 "Please see strict_cast<> comments for more information.");
    155 
    156   return static_cast<Dst>(static_cast<SrcType>(value));
    157 }
    158 
    159 // Some wrappers to statically check that a type is in range.
    160 template <typename Dst, typename Src, class Enable = void>
    161 struct IsNumericRangeContained {
    162   static const bool value = false;
    163 };
    164 
    165 template <typename Dst, typename Src>
    166 struct IsNumericRangeContained<
    167     Dst,
    168     Src,
    169     typename std::enable_if<ArithmeticOrUnderlyingEnum<Dst>::value &&
    170                             ArithmeticOrUnderlyingEnum<Src>::value>::type> {
    171   static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
    172                             NUMERIC_RANGE_CONTAINED;
    173 };
    174 
    175 // StrictNumeric implements compile time range checking between numeric types by
    176 // wrapping assignment operations in a strict_cast. This class is intended to be
    177 // used for function arguments and return types, to ensure the destination type
    178 // can always contain the source type. This is essentially the same as enforcing
    179 // -Wconversion in gcc and C4302 warnings on MSVC, but it can be applied
    180 // incrementally at API boundaries, making it easier to convert code so that it
    181 // compiles cleanly with truncation warnings enabled.
    182 // This template should introduce no runtime overhead, but it also provides no
    183 // runtime checking of any of the associated mathematical operations. Use
    184 // CheckedNumeric for runtime range checks of the actual value being assigned.
    185 template <typename T>
    186 class StrictNumeric {
    187  public:
    188   using type = T;
    189 
    190   constexpr StrictNumeric() : value_(0) {}
    191 
    192   // Copy constructor.
    193   template <typename Src>
    194   constexpr StrictNumeric(const StrictNumeric<Src>& rhs)
    195       : value_(strict_cast<T>(rhs.value_)) {}
    196 
    197   // This is not an explicit constructor because we implicitly upgrade regular
    198   // numerics to StrictNumerics to make them easier to use.
    199   template <typename Src>
    200   constexpr StrictNumeric(Src value)  // NOLINT(runtime/explicit)
    201       : value_(strict_cast<T>(value)) {}
    202 
    203   // If you got here from a compiler error, it's because you tried to assign
    204   // from a source type to a destination type that has insufficient range.
    205   // The solution may be to change the destination type you're assigning to,
    206   // and use one large enough to represent the source.
    207   // If you're assigning from a CheckedNumeric<> class, you may be able to use
    208   // the AssignIfValid() member function, specify a narrower destination type to
    209   // the member value functions (e.g. val.template ValueOrDie<Dst>()), use one
    210   // of the value helper functions (e.g. ValueOrDieForType<Dst>(val)).
    211   // If you've encountered an _ambiguous overload_ you can use a static_cast<>
    212   // to explicitly cast the result to the destination type.
    213   // If none of that works, you may be better served with the checked_cast<> or
    214   // saturated_cast<> template functions for your particular use case.
    215   template <typename Dst,
    216             typename std::enable_if<
    217                 IsNumericRangeContained<Dst, T>::value>::type* = nullptr>
    218   constexpr operator Dst() const {
    219     return static_cast<typename ArithmeticOrUnderlyingEnum<Dst>::type>(value_);
    220   }
    221 
    222  private:
    223   const T value_;
    224 };
    225 
    226 // Convience wrapper returns a StrictNumeric from the provided arithmetic type.
    227 template <typename T>
    228 constexpr StrictNumeric<typename UnderlyingType<T>::type> MakeStrictNum(
    229     const T value) {
    230   return value;
    231 }
    232 
    233 // Overload the ostream output operator to make logging work nicely.
    234 template <typename T>
    235 std::ostream& operator<<(std::ostream& os, const StrictNumeric<T>& value) {
    236   os << static_cast<T>(value);
    237   return os;
    238 }
    239 
    240 #define STRICT_COMPARISON_OP(NAME, OP)                               \
    241   template <typename L, typename R,                                  \
    242             typename std::enable_if<                                 \
    243                 internal::IsStrictOp<L, R>::value>::type* = nullptr> \
    244   constexpr bool operator OP(const L lhs, const R rhs) {             \
    245     return SafeCompare<NAME, typename UnderlyingType<L>::type,       \
    246                        typename UnderlyingType<R>::type>(lhs, rhs);  \
    247   }
    248 
    249 STRICT_COMPARISON_OP(IsLess, <);
    250 STRICT_COMPARISON_OP(IsLessOrEqual, <=);
    251 STRICT_COMPARISON_OP(IsGreater, >);
    252 STRICT_COMPARISON_OP(IsGreaterOrEqual, >=);
    253 STRICT_COMPARISON_OP(IsEqual, ==);
    254 STRICT_COMPARISON_OP(IsNotEqual, !=);
    255 
    256 #undef STRICT_COMPARISON_OP
    257 };
    258 
    259 using internal::strict_cast;
    260 using internal::saturated_cast;
    261 using internal::SafeUnsignedAbs;
    262 using internal::StrictNumeric;
    263 using internal::MakeStrictNum;
    264 using internal::IsValueNegative;
    265 
    266 // Explicitly make a shorter size_t alias for convenience.
    267 using SizeT = StrictNumeric<size_t>;
    268 
    269 }  // namespace base
    270 }  // namespace pdfium
    271 
    272 #endif  // PDFIUM_THIRD_PARTY_BASE_NUMERICS_SAFE_CONVERSIONS_H_
    273