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 BASE_SAFE_CONVERSIONS_IMPL_H_
      6 #define BASE_SAFE_CONVERSIONS_IMPL_H_
      7 
      8 #include <limits>
      9 
     10 #include "base/macros.h"
     11 #include "base/template_util.h"
     12 
     13 namespace base {
     14 namespace internal {
     15 
     16 // The std library doesn't provide a binary max_exponent for integers, however
     17 // we can compute one by adding one to the number of non-sign bits. This allows
     18 // for accurate range comparisons between floating point and integer types.
     19 template <typename NumericType>
     20 struct MaxExponent {
     21   static const int value = std::numeric_limits<NumericType>::is_iec559
     22                                ? std::numeric_limits<NumericType>::max_exponent
     23                                : (sizeof(NumericType) * 8 + 1 -
     24                                   std::numeric_limits<NumericType>::is_signed);
     25 };
     26 
     27 enum IntegerRepresentation {
     28   INTEGER_REPRESENTATION_UNSIGNED,
     29   INTEGER_REPRESENTATION_SIGNED
     30 };
     31 
     32 // A range for a given nunmeric Src type is contained for a given numeric Dst
     33 // type if both numeric_limits<Src>::max() <= numeric_limits<Dst>::max() and
     34 // numeric_limits<Src>::min() >= numeric_limits<Dst>::min() are true.
     35 // We implement this as template specializations rather than simple static
     36 // comparisons to ensure type correctness in our comparisons.
     37 enum NumericRangeRepresentation {
     38   NUMERIC_RANGE_NOT_CONTAINED,
     39   NUMERIC_RANGE_CONTAINED
     40 };
     41 
     42 // Helper templates to statically determine if our destination type can contain
     43 // maximum and minimum values represented by the source type.
     44 
     45 template <
     46     typename Dst,
     47     typename Src,
     48     IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed
     49                                             ? INTEGER_REPRESENTATION_SIGNED
     50                                             : INTEGER_REPRESENTATION_UNSIGNED,
     51     IntegerRepresentation SrcSign =
     52         std::numeric_limits<Src>::is_signed
     53             ? INTEGER_REPRESENTATION_SIGNED
     54             : INTEGER_REPRESENTATION_UNSIGNED >
     55 struct StaticDstRangeRelationToSrcRange;
     56 
     57 // Same sign: Dst is guaranteed to contain Src only if its range is equal or
     58 // larger.
     59 template <typename Dst, typename Src, IntegerRepresentation Sign>
     60 struct StaticDstRangeRelationToSrcRange<Dst, Src, Sign, Sign> {
     61   static const NumericRangeRepresentation value =
     62       MaxExponent<Dst>::value >= MaxExponent<Src>::value
     63           ? NUMERIC_RANGE_CONTAINED
     64           : NUMERIC_RANGE_NOT_CONTAINED;
     65 };
     66 
     67 // Unsigned to signed: Dst is guaranteed to contain source only if its range is
     68 // larger.
     69 template <typename Dst, typename Src>
     70 struct StaticDstRangeRelationToSrcRange<Dst,
     71                                         Src,
     72                                         INTEGER_REPRESENTATION_SIGNED,
     73                                         INTEGER_REPRESENTATION_UNSIGNED> {
     74   static const NumericRangeRepresentation value =
     75       MaxExponent<Dst>::value > MaxExponent<Src>::value
     76           ? NUMERIC_RANGE_CONTAINED
     77           : NUMERIC_RANGE_NOT_CONTAINED;
     78 };
     79 
     80 // Signed to unsigned: Dst cannot be statically determined to contain Src.
     81 template <typename Dst, typename Src>
     82 struct StaticDstRangeRelationToSrcRange<Dst,
     83                                         Src,
     84                                         INTEGER_REPRESENTATION_UNSIGNED,
     85                                         INTEGER_REPRESENTATION_SIGNED> {
     86   static const NumericRangeRepresentation value = NUMERIC_RANGE_NOT_CONTAINED;
     87 };
     88 
     89 enum RangeConstraint {
     90   RANGE_VALID = 0x0,  // Value can be represented by the destination type.
     91   RANGE_UNDERFLOW = 0x1,  // Value would overflow.
     92   RANGE_OVERFLOW = 0x2,  // Value would underflow.
     93   RANGE_INVALID = RANGE_UNDERFLOW | RANGE_OVERFLOW  // Invalid (i.e. NaN).
     94 };
     95 
     96 // Helper function for coercing an int back to a RangeContraint.
     97 inline RangeConstraint GetRangeConstraint(int integer_range_constraint) {
     98   DCHECK(integer_range_constraint >= RANGE_VALID &&
     99          integer_range_constraint <= RANGE_INVALID);
    100   return static_cast<RangeConstraint>(integer_range_constraint);
    101 }
    102 
    103 // This function creates a RangeConstraint from an upper and lower bound
    104 // check by taking advantage of the fact that only NaN can be out of range in
    105 // both directions at once.
    106 inline RangeConstraint GetRangeConstraint(bool is_in_upper_bound,
    107                                    bool is_in_lower_bound) {
    108   return GetRangeConstraint((is_in_upper_bound ? 0 : RANGE_OVERFLOW) |
    109                             (is_in_lower_bound ? 0 : RANGE_UNDERFLOW));
    110 }
    111 
    112 template <
    113     typename Dst,
    114     typename Src,
    115     IntegerRepresentation DstSign = std::numeric_limits<Dst>::is_signed
    116                                             ? INTEGER_REPRESENTATION_SIGNED
    117                                             : INTEGER_REPRESENTATION_UNSIGNED,
    118     IntegerRepresentation SrcSign = std::numeric_limits<Src>::is_signed
    119                                             ? INTEGER_REPRESENTATION_SIGNED
    120                                             : INTEGER_REPRESENTATION_UNSIGNED,
    121     NumericRangeRepresentation DstRange =
    122         StaticDstRangeRelationToSrcRange<Dst, Src>::value >
    123 struct DstRangeRelationToSrcRangeImpl;
    124 
    125 // The following templates are for ranges that must be verified at runtime. We
    126 // split it into checks based on signedness to avoid confusing casts and
    127 // compiler warnings on signed an unsigned comparisons.
    128 
    129 // Dst range is statically determined to contain Src: Nothing to check.
    130 template <typename Dst,
    131           typename Src,
    132           IntegerRepresentation DstSign,
    133           IntegerRepresentation SrcSign>
    134 struct DstRangeRelationToSrcRangeImpl<Dst,
    135                                       Src,
    136                                       DstSign,
    137                                       SrcSign,
    138                                       NUMERIC_RANGE_CONTAINED> {
    139   static RangeConstraint Check(Src value) { return RANGE_VALID; }
    140 };
    141 
    142 // Signed to signed narrowing: Both the upper and lower boundaries may be
    143 // exceeded.
    144 template <typename Dst, typename Src>
    145 struct DstRangeRelationToSrcRangeImpl<Dst,
    146                                       Src,
    147                                       INTEGER_REPRESENTATION_SIGNED,
    148                                       INTEGER_REPRESENTATION_SIGNED,
    149                                       NUMERIC_RANGE_NOT_CONTAINED> {
    150   static RangeConstraint Check(Src value) {
    151     return std::numeric_limits<Dst>::is_iec559
    152                ? GetRangeConstraint(value <= std::numeric_limits<Dst>::max(),
    153                                     value >= -std::numeric_limits<Dst>::max())
    154                : GetRangeConstraint(value <= std::numeric_limits<Dst>::max(),
    155                                     value >= std::numeric_limits<Dst>::min());
    156   }
    157 };
    158 
    159 // Unsigned to unsigned narrowing: Only the upper boundary can be exceeded.
    160 template <typename Dst, typename Src>
    161 struct DstRangeRelationToSrcRangeImpl<Dst,
    162                                       Src,
    163                                       INTEGER_REPRESENTATION_UNSIGNED,
    164                                       INTEGER_REPRESENTATION_UNSIGNED,
    165                                       NUMERIC_RANGE_NOT_CONTAINED> {
    166   static RangeConstraint Check(Src value) {
    167     return GetRangeConstraint(value <= std::numeric_limits<Dst>::max(), true);
    168   }
    169 };
    170 
    171 // Unsigned to signed: The upper boundary may be exceeded.
    172 template <typename Dst, typename Src>
    173 struct DstRangeRelationToSrcRangeImpl<Dst,
    174                                       Src,
    175                                       INTEGER_REPRESENTATION_SIGNED,
    176                                       INTEGER_REPRESENTATION_UNSIGNED,
    177                                       NUMERIC_RANGE_NOT_CONTAINED> {
    178   static RangeConstraint Check(Src value) {
    179     return sizeof(Dst) > sizeof(Src)
    180                ? RANGE_VALID
    181                : GetRangeConstraint(
    182                      value <= static_cast<Src>(std::numeric_limits<Dst>::max()),
    183                      true);
    184   }
    185 };
    186 
    187 // Signed to unsigned: The upper boundary may be exceeded for a narrower Dst,
    188 // and any negative value exceeds the lower boundary.
    189 template <typename Dst, typename Src>
    190 struct DstRangeRelationToSrcRangeImpl<Dst,
    191                                       Src,
    192                                       INTEGER_REPRESENTATION_UNSIGNED,
    193                                       INTEGER_REPRESENTATION_SIGNED,
    194                                       NUMERIC_RANGE_NOT_CONTAINED> {
    195   static RangeConstraint Check(Src value) {
    196     return (MaxExponent<Dst>::value >= MaxExponent<Src>::value)
    197                ? GetRangeConstraint(true, value >= static_cast<Src>(0))
    198                : GetRangeConstraint(
    199                      value <= static_cast<Src>(std::numeric_limits<Dst>::max()),
    200                      value >= static_cast<Src>(0));
    201   }
    202 };
    203 
    204 template <typename Dst, typename Src>
    205 inline RangeConstraint DstRangeRelationToSrcRange(Src value) {
    206   COMPILE_ASSERT(std::numeric_limits<Src>::is_specialized,
    207                  argument_must_be_numeric);
    208   COMPILE_ASSERT(std::numeric_limits<Dst>::is_specialized,
    209                  result_must_be_numeric);
    210   return DstRangeRelationToSrcRangeImpl<Dst, Src>::Check(value);
    211 }
    212 
    213 }  // namespace internal
    214 }  // namespace base
    215 
    216 #endif  // BASE_SAFE_CONVERSIONS_IMPL_H_
    217 
    218